Adriaan
Adriaan

Reputation: 3312

Finding table caption in Word VBA

I want to automatically extract data from tables of a Word document. I do this by iterating over all tables in VBA. I.e.

For Each tbl In wdDoc.Tables
Next

Is it possible to find the caption for a given table? i.e. the document has "Table 3:" and then the table.

Note that not all the tables in the document have got a caption and therefore the table numbers in captions are different than the document table enumeration.

Any help is appreciated.

Upvotes: 4

Views: 9043

Answers (1)

Drew Gaynor
Drew Gaynor

Reputation: 8472

Unfortunately, table captions are not actually associated with their tables through the Word Object Model. When a table caption is created, it is just text placed in a separate Paragraph object.

So, the short answer is that no, there is no good way to find the caption for a given table.

I did write some code that may help you though. It basically iterates through all Paragraph objects in the document and looks for the "Caption" style (alternatively, you could look for text formatted "Table #:", or whatever you'd like). If the very next Paragraph contains tables, it places the text of the caption into the first cell of the first table found.

    Dim p As Paragraph
    Dim lastParagraphWasCaption As Boolean
    Dim lastCaptionText As String
    lastParagraphWasCaption = False

    For Each p In ActiveDocument.Paragraphs
        If lastParagraphWasCaption And p.Range.Tables.Count > 0 Then
            p.Range.Tables(1).Cell(1, 1).Range.Text = lastCaptionText
        End If

        If p.Range.Style = "Caption" Then
            lastParagraphWasCaption = True
            lastCaptionText = p.Range.Text
        Else
            lastParagraphWasCaption = False
        End If
    Next

Keep in mind that this is just an example of how you could tie together a caption with its table. With that said, it is not a very reliable method and I would not recommend using it unless you absolutely need to because table captions could presumably not have the caption styling, or there could be caption styling on something that isn't a caption, etc.

Upvotes: 6

Related Questions