Search for table header in Word VBA

I want to automatically extract data from Word document tables. I do this by repeating all the tables in VBA. I.e.

For Each tbl In wdDoc.Tables Next 

Can I find a signature for this table? that is, the document "Table 3:" and then the table.

Please note that not all tables in the document have a title, and therefore the table numbers in the signatures are different from the enumeration of the document table.

Any help is appreciated.

+4
source share
1 answer

Unfortunately, table headers are not actually associated with their tables through the Word object model. When the table title is created, it is just text placed in a separate Paragraph object.

So, the short answer is: no, there is no suitable way to find a signature for this table.

I wrote code that can help you. It basically iterates through all the Paragraph objects in the document and looks for the "Caption" style (alternatively, you can look for text formatted with "Table No.:" or whatever you want). If the next paragraph contains tables, it places the text in 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 might associate a signature with a table. With that said, this is not a very reliable method, and I would not recommend using it if you absolutely do not need it , because the table captions may not have a signature style, or there may be a styling style on something that doesn't is a signature, etc.

+6
source

Source: https://habr.com/ru/post/1385373/


All Articles