Word宏以VBA格式着色文本

时间:2016-10-29 03:19:21

标签: word-vba

我有一个包含VBA代码块的Word文档。有没有人看过一个宏,它会通过着色关键字blue,注释绿色等来格式化它,以便它看起来像它在VBA编辑器中的显示方式?

1 个答案:

答案 0 :(得分:0)

您可以使用此代码突出显示关键字。代码通过搜索所选范围并更改单词颜色来工作。

您可以在End If代码的第一部分之后添加并更改文本。 祝你好运!

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