哎呀!换个思路果然不同了。让单词与关键字列表匹配,这样文档只需遍历一遍,扩展注释、数字、文本加亮也简单了。斑竹大人果然厉害!!我改动了一下:
Sub Highlighter(lang As Integer)
'
' 源代码高亮显示测试, WORD替换调用版
' 宏在 2005-5-21 由 Simon 创建
'
Dim TextLine As String, MyKeyText As String, i As Range
Select Case lang
Case 0
Open "D:\20056210333502\c++.txt" For Input As #1
Case 1
Open "D:\20056210333502\object pascal.txt" For Input As #1
Case 2
Open "D:\20056210333502\sql.txt" For Input As #1
End Select
MyKeyText = "!"
Do While Not EOF(1)
Line Input #1, TextLine
MyKeyText = MyKeyText & Trim(TextLine) & "!"
Loop
Close #1
Application.ScreenUpdating = False
For Each i In Selection.Words
If InStr(MyKeyText, "!" & Trim(i) & "!") > 0 Then
If i.Start = 0 Then GoTo BFC '如果为开始字符则转到指定行号
'如果该RANGE对象前面一个字符为空格或者软回车
If i.Previous(wdCharacter) = " " Or i.Previous(wdCharacter) = Chr(11) Then
BFC: i.Bold = True: i.Font.Color = wdColorRed
End If
End If
Next
Application.ScreenUpdating = True
End Sub
其中,改判断字符"Word!"为"!Word!",否则会误判,如"struct student a, b, c, *head, *p"中的"c"会加亮。
另外,我改word遍历循环为当前选择区域:For Each i In Selection.Words,但是只能选择一段,如果选中不连续的多段文字就不起作用了,请问怎样改写?
又或者遍历当前文档中的指定样式,如只对样式"源代码"中的文本进行高亮,应该怎样写呢?
小弟初学,还请诸位多多指点。 |