我有一个宏,用于在选定的文本中搜索段落分隔符(“ ^ p”)。我注意到,在Advanced Find & Replace Screen中,单词告诉您已找到多少个搜索项实例。如何提取此计数?
我已经记录了一个VBA宏,该宏可以在选择中进行查找,但是我不知道如何从该选择中提取出现的次数。有谁知道该怎么做(宁愿只从find&replace函数中提取它而不是编写for循环)?
Selection.Find.ClearFormatting
With Selection.Find
.Text = "^p"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindAsk
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
End With
答案 0 :(得分:1)
您不能-不幸的是,开发人员没有接触过!
但是您不必循环Word的查找。您可以使用比对象模型执行得更快的其他功能来计算字符串的实例数。例如,循环Instr
以计算实例数:
Sub TestGetCountOfFoundInstances()
Dim rng As Word.Range
Dim searchTerm As String
Dim nrInstances As Long
Dim bFound As Boolean
searchTerm = Chr(13)
Set rng = Selection.Range
nrInstances = CountNrInstancesSearchTerm(rng, searchTerm)
Debug.Print "The term " & searchTerm & " was found " & nrInstances & _
" times."
bFound = rng.Find.Execute(findText:="^p", ReplaceWith:="^l", Replace:=wdReplaceAll)
End Sub
Function CountNrInstancesSearchTerm( _
rng As Word.Range, searchTerm As String) As Long
Dim counter As Long, loc As Long, startPos As Long
Dim t As String
t = rng.Text
startPos = 1
Do
loc = InStr(startPos, t, searchTerm)
If loc > 0 Then
counter = counter + 1
startPos = loc + 1
End If
Loop While loc > 0
CountNrInstancesSearchTerm = counter
End Function