0
votes

I have a Word document that includes blocks of VBA code. Has anyone seen a macro that will format it by coloring keywords blue, comments green, and so on, so that it looks the way it appears in the VBA editor?

1

1 Answers

0
votes

You can use this code to highlight the keyword. The code works by searching for the selected range and change the word color.

You can add after the End If the first part of the code and change the text. Good luck!

Private Sub Worksheet_Change(ByVal Target As Range)

    Set myRange = Range("A1:AG100")  'The Range that contains the substring you want to change color
    substr = "t"   'The text you want to change color
    txtColor = 3   'The ColorIndex which represents the color you want to change


    For Each myString In myRange
        lenstr = Len(myString)
        lensubstr = Len(substr)
        For i = 1 To lenstr
            tempString = Mid(myString, i, lensubstr)
            If tempString = substr Then
                myString.Characters(Start:=i, Length:=lensubstr).Font.ColorIndex = txtColor
            End If
        Next i
    Next myString

     Set myRange = Range("A1:AG100")  'The Range that contains the substring you want to change color
    substr = "u"   'The text you want to change color
    txtColor = 4   'The ColorIndex which represents the color you want to change
      For Each myString In myRange
        lenstr = Len(myString)
        lensubstr = Len(substr)
        For i = 1 To lenstr
            tempString = Mid(myString, i, lensubstr)
            If tempString = substr Then
                myString.Characters(Start:=i, Length:=lensubstr).Font.ColorIndex = txtColor
            End If
        Next i
    Next myString
End Sub