2

I have a word macro that counts all text in a document that is either highlighted or Un-underlined bold. The macro works fine - although the counts are slightly higher than what the "Find" feature returns on some documents (if anyone knows why I'd be excited to figure it out).

The issue with the macro is that it is remarkably inefficient and lags my computer for a non-trivial amount of time when running on documents of around 50 pages in length. Does anyone see a more efficient way to write a macro of similar functionality?

    Dim highlightCount
    Dim boldCount
    Dim wordTotal
    boldCount = 0
    highlightCount = 0

    For Each w In ActiveDocument.Words
        If w.HighlightColorIndex <> wdNoHighlight Then
            highlightCount = highlightCount + 1
        End If
        If w.Font.Bold = True Then
            If w.HighlightColorIndex = wdNoHighlight Then
                If w.Font.Underline = False Then
                    boldCount = boldCount + 1
                End If
            End If
        End If
    Next
    wordTotal = highlightCount + boldCount
    MsgBox ("There are " & wordTotal & " words to be spread")
End Sub
4

1 回答 1

2

我无法回答您关于计数器结果太高的问题,因为我在您的代码中看不到问题。但我可以提出另一种解决方案,我使用Find对象,我猜它会比你的想法快得多。唯一的问题是您必须为您定义的两种单词条件分别运行两次“搜索”(以下两个循环)。

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

你能否给我们一个线索,如果它更快,因为我没有 50 页的文件进行测试。

于 2013-03-16T07:15:46.727 回答