首页 > 解决方案 > 从 Word vba 中的查找和替换中提取计数

问题描述

我有一个宏,它在选定的文本中搜索分节符(“^p”)。我注意到,在Advanced Find & Replace Screen中,word 会告诉您已找到多少个搜索项实例。如何提取此计数?

我记录了一个 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

标签: vbareplacecountms-word

解决方案


你不能 - 不幸的是,这并没有暴露给开发人员!

但你不一定要循环 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

推荐阅读