Home > OS >  Word-vba: Identifying the table hosting a range
Word-vba: Identifying the table hosting a range

Time:12-07

I am trying to identify the table index of a range; or more specifically: I have a Word doc with some tables, and each of the tables hold ContentControls of type the checkbox. I am looping through the ContentControls and if the type is CheckBox then I want to manipulate the text in the table, but to do that I need to know the table index. I can determine if the CheckBox is in fact within a table (either of two methods), and I can identify both row and column number, but I havent figured out how to establish the Table number.

Dim docActive As Document
Dim ContCtrl As ContentControl
Dim TableNo As Integer
Dim UpperLeftText As String
Set docActive = ActiveDocument

For Each ContCtrl In docActive.ContentControls
  If ContCtrl.Type = wdContentControlCheckBox Then
    If ContCtrl.Range.Information(wdWithInTable)
       MsgBox ("RowNumber: " & ContCtrl.Range.Information(wdEndOfRangeRowNumber))
       TableNo = ContCtrl.Range.Information(wdTableNumber))  ' This doesn't work, I know, and this is the line for which I need help
       MsgBox ("TableRef: " & TableNo)
       UpperLeftText = docActive.Tables(TableNo).Rows(1).Cells(1).Range.Text ' Contents of upper left cell assigned to variable UpperLeftText
    End If
  End If
Next

Any ideas?

Yes, I could figure out the number of tables and then loop through the tables which would then be a known number, but that is not really elegant...

CodePudding user response:

You do not need to access the table that the content control is located in by using its index in the document's tables collection. You can simply use the Tables collection of the content control's range, i.e.

UpperLeftText = ContCtrl.Range.Tables(1).Rows(1).Cells(1).Range.Text
  • Related