vba - 从 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
解决方案
你不能 - 不幸的是,这并没有暴露给开发人员!
但你不一定要循环 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
推荐阅读
- python - 如何在 Linux 中获得空闲时间?
- laravel - 如何在laravel 7中从http重定向到https并删除带有子域的www
- kubernetes - Prometheus 速率函数输出为整数
- python - How to store and use data from a text file in python for sentiment-analysis?
- r - compute mean with x range for many variables
- python - How to prevent user input into console when program is running in python?
- java - Google Dataproc API (through Java) does not submit Job to cluster
- excel - VBA: Exporting charts from Excel to PowerPoint, but my PowerPoint Application crashes without an error message
- ios - 当我添加 Google 移动广告 SDK 时,Flutter ios pod install 出现此错误。关于如何解决的任何想法?
- axios - NestJS FilesInterceptor 不解析来自 Axios 请求的文件