VBA - 在 word 文档中搜索包含特定字符串的 table 和 return table 数字

VBA - Search a word document for a table containing a specific string and return the table number

我正在尝试在 word 文档中搜索包含特定字符串的 table,然后是 return table 数字。然后我稍后使用 table 号码提取大量相关信息并将其放入 excel。我遇到的问题是 returning table 号码。

我有以下用于搜索字符串的代码,它似乎在进入 if 语句时有效。然而,我完全弄糊涂了,因为这不是 return 正确的 table 数字,而且似乎也卡在了 if 语句中无法启动。任何建议表示赞赏。

With .Range
        With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = "search string"
            .Replacement.Text = ""
            .Forward = True
            .Wrap = wdFindStop
            .Format = False
            .MatchWildcards = True
            .Execute
        End With
        
    Do While .Find.Found
        TableNo = .Tables.Count
        Stop
    Loop
    
    End With

尝试以下方法:

Dim wdDoc As Word.Document, wdRng As Word.Range
Set wdDoc = Word.ActiveDocument
With wdDoc
    Set wdRng = .Range(0, 0)
    With .Range
        With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Text = "search string"
            .Forward = True
            .Format = False
            .Wrap = wdFindStop
            .MatchWildcards = True
        End With
        Do While .Find.Execute
            If .Information(wdWithInTable) = True Then
                wdRng.End = .End
                TableNo = wdRng.Tables.Count
                MsgBox TableNo
            End If
            .Collapse wdCollapseEnd
        Loop
    End With
End With

或者,更简单:

Dim wdDoc As Word.Document, t As Long
Set wdDoc = Word.ActiveDocument
With wdDoc
  For t = 1 To .Tables.Count
    With .Tables(t).Range.Find
      .ClearFormatting
      .Replacement.ClearFormatting
      .Text = "search string"
      .Forward = True
      .Format = False
      .Wrap = wdFindStop
      .MatchWildcards = True
      .Execute
      If .Found = True Then MsgBox t
    End With
  Next
End With