【辦公-Word-VB】人民幣大寫轉換-帶完整註釋

完整代碼見:個人CSDN博客ui

 

-------------------- spa

 

應公司財務人員的請求,需在Word中作個:輸入阿拉伯數字,自動轉換成大寫,並填充到Word控件中對應的億、萬、千控件格子的功能,特研究VB。.net

下面是我在網上搜集的將 阿拉伯數字轉換爲 中文大寫的代碼,註釋爲我添加,方便理解,特記錄在此。code

有機會把帶有宏的原Word也發佈,供你們參考。

blog

 

Function mychange(ByVal Myinput)    
    'MyinputA 去除空白符且變成整數(去掉小數)後的數字串
    'MyinputB 翻轉後的數字串
    'MyinputC 轉換爲大寫的金額
    Dim Temp, TempA, MyinputA, MyinputB, MyinputC
    Dim Place As String
    Dim J As Integer
    Place = "分角元拾佰仟萬拾佰仟億拾佰仟萬"
    shuzi1 = "壹貳叄肆伍陸柒捌玖"
    shuzi2 = "整零元零零零萬零零零億零零零萬"
    
    qianzhui = ""
    If Val(Myinput) = 0 Then Myinput = 0
    If Myinput = "" Then Myinput = 0
    If Myinput < 0 Then qianzhui = ""
    
    '將小數轉爲整數,去掉小數點, 123.45 -> 12345
    Myinput = Int(Abs(Myinput) * 100 + 0.5)
    If Myinput > 99999999999# Then
      mychange = "輸入有誤:數字過大"
      Exit Function
    End If
    If Myinput = 0 Then
      mychange = "零元零分"
      Exit Function
    End If
    
    MyinputA = Trim(Str(Myinput))
    shuzilong = Len(MyinputA)
    
    '翻轉金額,12345->54321
    For J = 1 To shuzilong
    MyinputB = Mid(MyinputA, J, 1) & MyinputB
    Next
    
    '1把阿拉伯數字轉爲大寫, 54321, 5->伍
    '2將數字和對應位置的單位拼接,伍肆叄貳壹,伍->伍分
    '3拼接時翻轉回來, 肆角伍分
    '注意0:從 shuzi2 獲得單位,而不是從 Place
    '       12.10->1210->0121->  整 壹角 貳元 壹拾
    '       10.88->1088->8801->捌分 捌角   元 壹拾
    '       30800.25->3080025->5200803->..貳角 元 零 捌佰 零 叄萬
    '               ->叄萬 零 捌佰 零 元 貳角...
    For J = 1 To shuzilong
      Temp = Val(Mid(MyinputB, J, 1))
      If Temp = 0 Then
         MyinputC = Mid(shuzi2, J, 1) & MyinputC
      Else
         MyinputC = Mid(shuzi1, Temp, 1) & Mid(Place, J, 1) & MyinputC
      End If
    Next
    
    '細節:處理零
    '10.46          壹拾零元... -> 壹拾元
    '10 1234.56     壹拾零萬... -> 壹拾萬
    '10 1234 5678.56壹拾零億... -> 壹拾億
    '30800.25       上一步獲得:叄萬 零   捌佰 零     元 貳角伍分
    '               注意並非:叄萬 零仟 捌佰 零拾 零元 貳角伍分
    '30800.25       叄萬零捌佰(零)元.. ->  叄萬零捌佰 元..
    shuzilong = Len(MyinputC)
    For J = 1 To shuzilong - 1
      If Mid(MyinputC, J, 1) = "" Then
         Select Case Mid(MyinputC, J + 1, 1)
            Case "", "", "", "", "":
            MyinputC = left(MyinputC, J - 1) & Mid(MyinputC, J + 1, 30)
            J = J - 1
         End Select
      End If
    Next
    
    '貳億萬... -> 貳億...
    shuzilong = Len(MyinputC)
    For J = 1 To shuzilong - 1
       If Mid(MyinputC, J, 1) = "" And Mid(MyinputC, J + 1, 1) = "" Then
         MyinputC = left(MyinputC, J) & Mid(MyinputC, J + 2, 30)
         Exit For
       End If
    Next
    
    mychange = qianzhui & Trim(MyinputC)
End Function
相關文章
相關標籤/搜索