Macro to find string in table in defined paragraph

95 Views Asked by At

I have MS Word document that structure is defined:

  • I use 3-level numbered item Heading:

5 Heading1

5.1 Heading2

5.1.1 Heading3

. . .

5.1.7 Heading3

  • in Item 5.X.7 I have table with results of my experiment
  • "X" can start from 1 up to approx 20

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"?

1

There are 1 best solutions below

1
On BEST ANSWER

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