vbadatatablems-wordreferencenumbered-list

Macro to find string in table in defined paragraph


I have MS Word document that structure is defined:

5 Heading1

5.1 Heading2

5.1.1 Heading3

. . .

5.1.7 Heading3

I need to search in all items "5.X.7" for tables with results.

Any idea how to select first row, first column in first table in item "5.X.7"?


Solution

  • Since you are new, and even though StackOverflow is not a free coding service ... try something like this to get you started.

    Sub FindTables()
        Dim doc As Word.Document, rng As Word.Range, hRng As Word.Range
        Dim splitStr() As String, tbl As Word.Table
        Set doc = ActiveDocument
        Set rng = doc.Content
        With rng.Find
            .ClearFormatting
            .Format = True
            .Forward = True
            .Style = doc.Styles("Heading 3").NameLocal
            .Text = ""
            .Wrap = wdFindStop
            .Execute
            Do While .found = True
                splitStr = Split(rng.ListParagraphs(1).Range.ListFormat.ListString, ".")
                If splitStr(0) = 5 And splitStr(2) = 7 Then
                    Set hRng = rng.Bookmarks("\HeadingLevel").Range
                    If hRng.Tables.Count > 0 Then
                        Set tbl = hRng.Tables(1).Range
                        'do something with the table
                    End If
                    rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
                Else
                    rng.Collapse Word.WdCollapseDirection.wdCollapseEnd
                End If
            .Execute
            Loop
        End With
    End Sub