本文为《别怕,Excel VBA其实特别简单(第3版)》随书问题参考答案
要将数字金额转为中文大写,需要经历以下几个步骤:
1.将阿拉伯小写数字转为中文大写。这可以用到前面章节例子中,将数字转为中文大写的代码,如:
Function RmbDx(ByVal c) As String
Application.Volatile True
c = Val(c)
RmbDx = Application.WorksheetFunction.Text(c, "[DBNum2]")
RmbDx = Replace(RmbDx, "-", "负")
End Function
2.在整数金额的后面添加“元整”.可以借助IF语句及FIX取整函数来判断某个金额是否整数金额。
Function RmbDx(ByVal c) As String
Application.Volatile True
c = Val(c)
RmbDx = Application.WorksheetFunction.Text(c, "[DBNum2]")
RmbDx = Replace(RmbDx, "-", "负")
If c = Fix(c) Then
RmbDx = RmbDx & "元整"
End If
End Function
3.在只包含“角”信息,不含“分”信息的金额中添加“元”和“分”信息.
Function RmbDx(ByVal c) As String
Application.Volatile True
Dim p As Integer
c = Val(c)
RmbDx = Application.WorksheetFunction.Text(c, "[DBNum2]")
RmbDx = Replace(RmbDx, "-", "负")
If c = Fix(c) Then
RmbDx = RmbDx & "元整"
Else
RmbDx = Replace(RmbDx, ".", "元")
If c * 10 = Fix(c * 10) Then
RmbDx = RmbDx & "角"
End If
End If
End Function
4.在包含“角”与“分”信息的数据中添加“角”和“分”信息。
Function RmbDx(ByVal c) As String
Application.Volatile True
Dim p As Integer
c = Val(c)
RmbDx = Application.WorksheetFunction.Text(c, "[DBNum2]")
RmbDx = Replace(RmbDx, "-", "负")
If c = Fix(c) Then
RmbDx = RmbDx & "元整"
Else
p = InStr(RmbDx, ".")
RmbDx = Replace(RmbDx, ".", "元")
If c * 10 = Fix(c * 10) Then
RmbDx = RmbDx & "角"
Else
RmbDx = Left(RmbDx, p) & Mid(RmbDx, p + 1, 1) & "角" & Right(RmbDx, 1) & "分"
End If
End If
End Function
这样即可得到将人民币金额转为中文大写金额的自定义函数RmbDx,效果如下图。