Sunday, February 25, 2024
HomeHackathonVB Code to convert Digit to Text in MS Word Document

VB Code to convert Digit to Text in MS Word Document

Copy the code below by creating a new Macro to convert:

To add shortcut for this macro, you shall follow this article that I’ve written in prior.

Sub DigitToText()
    Dim datasagar_Digits As String
    Dim datasagar_NumText As String

    datasagar_NumText = ""

    ' Select Number from Word Document 
    Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdMove
    Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend

    ' Store digits in variable named datasagar_Digits
    datasagar_Digits = Trim(Selection.Text)

    If Val(datasagar_Digits) > 999999 Then
        If Val(datasagar_Digits) <= 999999999 Then
            datasagar_NumText = Trim(Int(Str(Val(datasagar_Digits) / 1000000)))
            ' For selection range, create a field containing the digits and the cardtext format flag
            Selection.Fields.Add Range:=Selection.Range, _
              Type:=wdFieldEmpty, Text:="= " + datasagar_NumText + " \* CardText", _
              PreserveFormatting:=True

            ' Select the previously created field and copy it
            Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
            datasagar_NumText = Selection.Text & " million "
            datasagar_Digits = Right(datasagar_Digits, 6)
        End If
    End If
    If Val(datasagar_Digits) <= 999999 Then
        ' Create a field containing that digits and the cardtext format flag
        Selection.Fields.Add Range:=Selection.Range, _
          Type:=wdFieldEmpty, Text:="= " + datasagar_Digits + " \* CardText", _
          PreserveFormatting:=True

        ' Select the field and copy it
        Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
        datasagar_Digits = datasagar_NumText & Selection.Text

        ' Replace number with words in the selected area of word document
        Selection.TypeText Text:=datasagar_Digits
        Selection.TypeText Text:=" "
    Else
        MsgBox "Number too large", vbOKOnly
    End If
End Sub

datasagarhttp://www.DataSagar.com
The author of this blog post is a technology fellow, an IT entrepreneur, and Educator in Kathmandu Nepal. With his keen interest in Data Science and Business Intelligence, he writes on random topics occasionally in the DataSagar blog.
RELATED ARTICLES
- Advertisment -

Most Popular