【问题标题】:extract count from find&replace in Word vba从 Word vba 中的查找和替换中提取计数
【发布时间】:2019-01-02 05:06:10
【问题描述】:

我有一个宏,可以在选定的文本中搜索分节符(“^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

【问题讨论】:

  • 您的问题得到解答了吗?

标签: vba replace count ms-word


【解决方案1】:

你不能 - 很遗憾,这并没有暴露给开发人员!

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

【讨论】:

    猜你喜欢
    • 2018-01-18
    • 2012-03-08
    • 1970-01-01
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 2021-03-13
    • 2014-02-26
    相关资源
    最近更新 更多