Reputation: 133
I have a word document with a lot of tables. I'd like to map each table to the immediate heading they are listed under. Right now I am thinking of passing through the selection cursor through each individual table and somehow find the immediate heading that the selection cursor is under. I am having trouble with finding the heading. I cannot find any documented member functions that can help me do this.
For Each T In wrdDoc.Tables
wrdApp.Selection.GoTo What:=wdGoToTable, Which:=wdGoToNext
'Find heading
Next T
edit To clarify the formatting of the document:
Table 1 Table 2
Table 3
Table 4
Table 5
Table 6
Basically, there are multiple levels of headings. Under each, there may or may not be multiple tables. So in the case above, I'd like to figure out a way to map Tables 1 and 2 to 1, Table 3 to 1.1, Table 4 to 1.1.1 and etc..
Upvotes: 1
Views: 898
Reputation: 1410
I think this does what you want (Word 2003).
Option Explicit
Sub DC1() ' find immediate preceeding header for all tables
Dim tblnum&, swnone&
For tblnum = 1 To ActiveDocument.Tables.Count
swnone = 0 ' to detect "before all numbered paragraphs"
ActiveDocument.Tables(tblnum).Cell(1, 1).Select
Do ' get out of table
If Selection.MoveLeft(wdCharacter, 1) = 0 Then swnone = 1: Exit Do
Loop While Selection.Information(wdWithInTable)
Do ' find previous numbered paragraph
If Selection.Paragraphs(1).Range.ListParagraphs.Count = 1 Then Exit Do
If Selection.MoveLeft(wdCharacter, 1) = 0 Then swnone = 1: Exit Do
Loop
If swnone Then
Debug.Print "Tbl#" & tblnum, "Before first numbered paragraph"
Else
Debug.Print "Tbl#" & tblnum, Selection.Paragraphs(1).Range.ListFormat.ListString
End If
Next tblnum
End Sub
Upvotes: 0
Reputation: 19067
If your heading are list paragraphs then you could use the following solution:
Sub Under_Table_Numbered_List_Item()
Dim TBL As Table
For Each TBL In ActiveDocument.Tables
'get first list item below each table
'select it- not required
ActiveDocument.Range(TBL.Range.End).ListParagraphs(1).Range.Select
'read its text
Debug.Print ActiveDocument.Range(TBL.Range.End).ListParagraphs(1).Range.Text
Next
End Sub
But if you want to find first heading below each table where heading is a style then try with this code:
Sub Under_Table_Heading_style()
Dim TBL As Table
Dim Para As Paragraph
For Each TBL In ActiveDocument.Tables
'get first heading below table
'based on style name
For Each Para In ActiveDocument.Range(TBL.Range.End).Paragraphs
Para.Range.Select
If Para.Range.Style = "Heading 1" Then
'this is your heading
Debug.Print Para.Range.Text
End If
'stop searchin if you reach next table
If Para.Range.Tables.Count > 0 Then Exit For
Next
Next
End Sub
Upvotes: 1