vba - 通过查找函数进行字数统计返回的结果与宏不同

标签 vba ms-word ms-office

我有一个字数统计功能,可以查找突出显示或粗体且无下划线的文本,然后返回文档中满足该条件的字数。

但是,结果与 Word 中的“查找”函数返回的结果相差很大,有人知道为什么会出现这种差异吗?我是否重复计算了某些内容?

Sub CountWords()

Dim rngWords As Range
Set rngWords = ActiveDocument.Content
Dim boldCount As Long, highlightCount As Long
Dim wordTotal As Long

Do
With rngWords.Find
    .Highlight = True
    .Forward = True
    .Execute
End With
If rngWords.Find.Found = True Then
    highlightCount = highlightCount + rngWords.Words.Count
Else
    Exit Do
End If
Loop

Set rngWords = ActiveDocument.Content

Do
With rngWords.Find
    .Font.Bold = True
    .Highlight = False
    .Font.Underline = wdUnderlineNone
    .Forward = True
    .Execute
End With
If rngWords.Find.Found = True Then
    boldCount = boldCount + rngWords.Words.Count
Else
    Exit Do
End If
Loop
wordTotal = boldCount + highlightCount
MsgBox "There are " & wordTotal & " words to be spread"
End Sub

最佳答案

Words 属性计算标点符号和段落标记。改变

highlightCount = highlightCount + rngWords.Words.Count

highlightCount = highlightCount + rngWords.ComputeStatistics(wdStatisticWords)

它们会匹配。

关于vba - 通过查找函数进行字数统计返回的结果与宏不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15450641/

相关文章:

vba - 将图像添加到Word文档并使用VBA缩放

vba - 计算在vba中合并了多少行

ms-word - 词: Picture hidden behind text

javascript - Word 加载项获取完整的文档文本?

excel - 使用 Microsoft Office 兼容性包的 excelcnv 将 xlsx 转换为 xls

vba - 获取括号之间的值

正则表达式:无法匹配行尾

PHP-MySQL : Not able to fetch multiple record from database into word file

python - 如何将文字样式应用于 Richtext 对象? (docxtpl 库)

c# - 如何从 C# 编辑或取消保护 protected Excel 工作表中的单个单元格?