0
votes

I'm having trouble creating a Microsoft-Word macro. Here's the macro that I'm working on. It successfully selects each individual table in a word document.

Sub FindSpecificTables()
    Selection.WholeStory

    Dim iResponse As Integer
    Dim tTable As Table

    'If any tables exist, loop through each table in collection.
    For Each tTable In ActiveDocument.Tables
        tTable.Select
        If response = vbNo Then Exit For 'User chose to leave search.
    Next
    MsgBox prompt:="Search Complete.", buttons:=vbInformation
End Sub

However, I only need to select a table if the table contains a specified string. This should be simple enough, but I can't figure it out. How can I search a table for a specific string?

I've tried adjusting the code with the following conditional statement:
If tTable.Cell(1, 1) = "Adjusted:" Then tTable.Select; see example below.

Sub FindSpecificTables()
    Selection.WholeStory

    Dim iResponse As Integer
    Dim tTable As Table
    'If any tables exist, loop through each table in collection.
    For Each tTable In ActiveDocument.Tables
        If tTable.Cell(1, 1) = "MySpecifiedString:" Then tTable.Select
        If response = vbNo Then Exit For 'User chose to leave search.
    Next
    MsgBox prompt:="Search Complete.", buttons:=vbInformation
End Sub

Unfortunately, this isn't working. Is my syntax wrong? Do you guys have any suggestions or recommendations?

1

1 Answers

2
votes

Try with different approach... instead of looping each table loop search (find) method and check if text found is within table. here is simple solution:

Sub Find_Text_in_table()

    Selection.Find.ClearFormatting
    With Selection.Find
        .Text = "donec"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindAsk
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

    Do While Selection.Find.Execute

        If Selection.Information(wdWithInTable) Then

            Stop
            'now you are in table with text you searched
            'be careful with changing Selection Object
            'do what you need here
        End If
    Loop
End Sub