This guide demonstrates how to convert numbers to English words within a Word document using VBA. Follow these steps:
- Select the Number to Convert:
- Choose the number you want to convert to words.
- Press
Alt + F11
to open the Microsoft Visual Basic for Application window.
- Insert a New Module:
- Click on
Insert > Module
. - Copy the VBA code below and paste it into the Module window.
- Click on
Sub ConvertNumberToWord()
‘ Update by Extendoffice 20181010
Dim xDigit As Double
Dim xBuff As String
On Error Resume Next
Selection.MoveLeft wdWord, 1, wdMove
Selection.MoveRight wdWord, 1, wdExtend
xDigit = Val(Trim(Selection.Text))
If xDigit = 0 And Str(xDigit) <> Trim(Selection.Text) Then Exit Sub
If xDigit > 999999 Then
If xDigit <= 999999999 Then
xBuff = Trim(Int(Str(xDigit / 1000000)))
Selection.Fields.Add Selection.Range, wdFieldEmpty, “= ” + xBuff + ” \* CardText”, True
Selection.MoveLeft wdWord, 1, wdExtend
xBuff = Selection.Text & ” million “
xDigit = Right(Str(xDigit), 6)
End If
End If
If xDigit <= 999999 Then
Selection.Fields.Add Selection.Range, wdFieldEmpty, “= ” + Str(xDigit) + ” \* CardText”, True
Selection.MoveLeft wdWord, 1, wdExtend
xDigit = xBuff & Selection.Text
Selection.TypeText xDigit + ” “
Else
MsgBox “Number too large”, vbOKOnly, “Kutool for Word”
End If
End Sub
‘ Update by Extendoffice 20181010
Dim xDigit As Double
Dim xBuff As String
On Error Resume Next
Selection.MoveLeft wdWord, 1, wdMove
Selection.MoveRight wdWord, 1, wdExtend
xDigit = Val(Trim(Selection.Text))
If xDigit = 0 And Str(xDigit) <> Trim(Selection.Text) Then Exit Sub
If xDigit > 999999 Then
If xDigit <= 999999999 Then
xBuff = Trim(Int(Str(xDigit / 1000000)))
Selection.Fields.Add Selection.Range, wdFieldEmpty, “= ” + xBuff + ” \* CardText”, True
Selection.MoveLeft wdWord, 1, wdExtend
xBuff = Selection.Text & ” million “
xDigit = Right(Str(xDigit), 6)
End If
End If
If xDigit <= 999999 Then
Selection.Fields.Add Selection.Range, wdFieldEmpty, “= ” + Str(xDigit) + ” \* CardText”, True
Selection.MoveLeft wdWord, 1, wdExtend
xDigit = xBuff & Selection.Text
Selection.TypeText xDigit + ” “
Else
MsgBox “Number too large”, vbOKOnly, “Kutool for Word”
End If
End Sub
- Press
F5
to Run the Code. The number is now converted to words.
Note:
- The code works for one number at a time.