我正在尝试创建一个宏,该宏可以标记正在使用的前缀“ pre”的实例。我可以创建一个突出显示所有“ pre”实例的实例,但这会标记诸如“ present”,“ pretend”等词。
我要解决的计划是创建一个带有我不想被标记的单词的数组(例如“ present”),然后使用AND操作,以便文本等于“ pre”且不等于我不想举报的单词。我的代码在下面,运行时在.Text <> Exceptions
行上有语法错误。有没有更好的方法来解决这个问题?谢谢!
Sub NeedPrefix()
Dim range As range
Dim i As Long
Dim TargetList
Dim Exception
TargetList = Array(" pre")
Exceptions = Array("prepare", "preparation", "present", "presentation", "presented", "prepared", "pretense", "pretend")
For i = 0 To UBound(TargetList)
Set range = ActiveDocument.range
With range.Find
.Text = TargetList(i)
.Text <> Exceptions
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute(Forward:=True) = True
ActiveDocument.Comments.Add range, "Is the use of a prefix appropriate?"
Loop
End With
Next
End Sub
答案 0 :(得分:1)
这里是比较术语列表和找到的范围的一种可能性。
为每个“命中”创建一个数组是可能的,尽管很耗时。相反,可以使用Instr
将找到的Range与列表进行比较。如果找到的范围不在字符串中,则返回0。
为使此功能有效,需要将找到的范围扩展到涵盖整个单词,因此要扩展范围的端点,直到找到一个空格为止。
如果在列表中找到一个术语,则无需执行任何操作,则可以省去代码片段的Else
部分。
range.Collapse wdCollapseEnd
将下一个“查找”循环的起点放置在找到的项之后,否则循环将在相同的“ pre”上无休止地重复。
我已将变量名从range
更改为rng
-在VBA中,使用保留字(属于Word或VBA的对象,方法或属性的名称)总是一个坏主意)作为变量名。另外,还要注意包含.Wrap = wdFindStop
,这一点很重要,因为否则该代码可能会从文档开始处重新开始。
Sub NeedPrefix()
Dim rng As Range
Dim i As Long
Dim TargetList
Dim Exceptions As String
Dim theException As String
TargetList = Array(" pre")
Exceptions = "prepare preparation present presentation presented prepared pretense pretend"
For i = 0 To UBound(TargetList)
Set rng = ActiveDocument.Content
With rng.Find
.Text = TargetList(i)
.Format = False
.Wrap = wdFindStop
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
Do While .Execute(Forward:=True) = True
Debug.Print "Characters moved: " & rng.MoveEndUntil(" " & Chr(13))
If InStr(Exceptions, rng.Text) = 0 Then
ActiveDocument.Comments.Add rng, "Is the use of a prefix appropriate?"
Else
theException = Mid(Exceptions, InStr(Exceptions, rng.Text))
theException = Mid(theException, 2)
theException = Left(theException, InStr(theException, " ") - 1)
Debug.Print "An exception was found: " & theException
End If
rng.Collapse wdCollapseEnd
Loop
End With
Next
End Sub