VBA 集合 - 列出在 MsgBox 中找到的项目

VBA collections - List found items in MsgBox

我想知道如何在 Word 文档中制作一个单词搜索器。以前,我设法创建的只是一个代码,可以突出显示我添加到列表中的单词:

Sub example

Dim w(3) as String
Dim k, l as Integer

w(1)= "word1"
w(2)= "word2"
w(3)= "word3"


Set r = Selection
r.HomeKey Unit:=wdStory

    For k = 1 To 3
        With r.Find
            .ClearFormatting
            .Text = w(k)
            For l = 1 To 10
                .Execute Wrap:=wdFindStop, Forward:=True
                     If .Found = False Then
                       Exit For
                     End If
                r.Range.HighlightColorIndex = wdRed
                r.Collapse Direction:=wdCollapseEnd
            Next
        End With
      r.HomeKey Unit:=wdStory
    Next
End Sub

而且效果很好。但我的目标是在 MsgBox 中显示所有找到的单词。所以我更新了代码:

Sub example

Dim w(3) as String
Dim k, l as Integer

w(1)= "word1"
w(2)= "word2"
w(3)= "word3"

Dim wcoll As Collection
Set wcoll = New Collection


Set r = Selection
r.HomeKey Unit:=wdStory

    For k = 1 To 3
        With r.Find
            .ClearFormatting
            .Text = w(k)
            For l = 1 To 10
                .Execute Wrap:=wdFindStop, Forward:=True
                     If .Found = False Then
                       Exit For
                     End If
                r.Range.HighlightColorIndex = wdRed
                r.Collapse Direction:=wdCollapseEnd

                wcoll.Add (w(k))

            Next
        End With
      r.HomeKey Unit:=wdStory
    Next

MsgBox("Found words: " & wcoll(1) & " " & wcoll(2) & " " & wcoll(3)) 

End Sub

我最后才意识到的问题是,当文档只包含搜索到的两个词时,但我尝试使用索引值 3 作为下标 [=14] 来显示=] MsgBox 不会弹出。相反,我得到一个下标超出范围的错误。我应该如何解决这个问题,以显示所有单词(即使只有相同的单词)?

您可以按如下方式进行。我的添加检查集合 wcoll 是否包含任何成员。如果是,则将显示在 MsgBox 中的文本连接起来。首先分配静态文本,然后循环集合的成员并将值附加到字符串。如果没有成员,则分配默认文本。

Sub example()    
  Dim w(3) As String, foundWords As String
  Dim k, l As Integer
  Dim wcoll As Collection
  Dim r as Selection

w(1) = "word1"
w(2) = "word2"
w(3) = "word3"

Set wcoll = New Collection        
Set r = Selection
r.HomeKey Unit:=wdStory

    For k = 1 To 3
        With r.Find
            .ClearFormatting
            .Text = w(k)
            For l = 1 To 10
                .Execute wrap:=wdFindStop, Forward:=True
                     If .found = False Then
                       Exit For
                     End If
                r.Range.HighlightColorIndex = wdRed
                r.Collapse Direction:=wdCollapseEnd

                wcoll.Add (w(k))    
            Next
        End With
      r.HomeKey Unit:=wdStory
    Next

    If wcoll.Count > 0 Then
        foundWords = "Found words: "
        For k = 1 To wcoll.Count
            foundWords = foundWords & " " & wcoll(k)
        Next
    Else
        foundWords = "No words were found."
    End If
    MsgBox foundWords    
End Sub