从 Word VBA 中的查找和替换中提取计数



我有一个宏,它在所选文本中搜索断段("^p"(。我注意到,在高级查找&替换屏幕,单词告诉您已经找到了多少个搜索项目的实例。如何提取此计数?

我录制了一个VBA宏,它可以在选定内容中查找,但我不知道如何从该选定内容中提取引用次数。有人知道如何做到这一点吗(比起编写for循环,更喜欢从find&replace函数中提取它(?

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

你不能-不幸的是,这并没有向开发人员公开!

但你不一定要循环Word的Find。您可以使用比对象模型执行得更快的其他功能来计算字符串的实例数。例如循环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

相关内容

最新更新