【问题标题】:Find, Highlight, and Count a word list (or string) in MS Word Macro在 MS Word 宏中查找、突出显示和计算单词列表(或字符串)
【发布时间】:2015-03-06 11:42:12
【问题描述】:

我正在尝试编写一个宏,它将根据当前活动文档中的清单(您将在名为清单的代码中看到它)查找文本。我已将 sn-ps 代码粘贴在一起以制作下面的宏。我的问题在于计数。我试图找出宏突出显示某些内容的次数。稍后,此计数将与类别结合使用,以计算某个类别中突出显示的对象的数量(希望如此!)。我不得不承认,由于我是 VBA 新手,所以我只能模糊地遵循这段代码实际上在做什么。任何帮助将非常感激。我所有试图获得准确计数的尝试都失败了。

此外,有谁知道计算多个列表的方法吗?比如说,我有几个词苹果和橙子属于水果清单,芹菜和西兰花属于蔬菜清单。每次使用苹果(或橙子)时,水果计数都会增加一。蔬菜也是如此。然后我想将这些数据导出到 Excel 表中。我知道这听起来很复杂。对不起。再次感谢任何帮助。

Sub CompareWordList()

'This macro will find all of the words or phrases in the checklist document (to be developed) and highlight them.
'Further to this, the macro will provide a word count which is to be added to certain assessment criteria
'which will be provided by ___ once the development of this macro is complete.

Dim sCheckDoc As String
Dim docRef As Document
Dim docCurrent As Document
Dim wrdRef As Object
Dim count As Integer

sCheckDoc = "C:\Users\Nathaniel\Documents\checklist.docx"
Set docCurrent = Selection.Document
Set docRef = Documents.Open(sCheckDoc)
Set Range = ActiveDocument.Range

Application.ScreenUpdating = False

docCurrent.Activate
Options.DefaultHighlightColorIndex = wdYellow

count = 0

With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    '.Replacement.Font.Bold = True
    .Replacement.Highlight = True
    .Replacement.Text = "^&"
    .Forward = True
    .Format = True
    .MatchWholeWord = True
    .MatchCase = False
    .MatchWildcards = False

' I TRIED HERE* count = count +1
End With


    For Each wrdRef In docRef.Words
    If Asc(Left(wrdRef, 1)) > 32 Then
        With Selection.Find
            .Wrap = wdFindContinue
            .Text = wrdRef
            .MatchCase = False
            .Execute Replace:=wdReplaceAll

        End With

    End If
     'and here *count = count + 1
Next wrdRef

count = count + 1


 If count <> 0 Then

    MsgBox _
    count & " item(s) highlighted "

    Else
        MsgBox "Nothing was not found in the document/selection matching the checklist"
End If


docRef.Close
docCurrent.Activate

Application.ScreenUpdating = True

End Sub

【问题讨论】:

  • 实际上,Word 在 VBA 中不提供确定替换数量的可能性(在您的情况下:突出显示的数量)。所以,有一个解决方法建议here

标签: vba ms-word


【解决方案1】:

您可以使用 RegEx 确定可能的替换数量。将文档的全部内容分配给一个字符串,然后计算 RegEx 匹配的数量。像这样的东西会起作用

Sub CountReplacements() ' Make sure you add a reference to Microsoft VBScript Regular Expressions 5.5
    Dim rex As New RegExp
    rex.Pattern = "[0-9]" ' Change RegEx pattern to whatever works for you
    rex.Global = True
    Dim str As String: str = ActiveDocument.Content
    Debug.Print Rex.Execute(str).Count
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2012-09-09
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多