问题
In order to access the single table within a range (say, rngOuter) I used: tblOuter = rngOuter.Tables[1]; After I placed a nested table within a range (say, rngInner) within that outer range's table, I found that: tblInner = rngInner.Tables[1]; did not work. rngInner.Tables[1] references tblOuter, rather than the table within itself. In fact, Tables collection of rngInner has only one element, and that is tblOuter. In order to access tblInner, I have to get at tblOuter.Range.Tables[1].
Does anyone know if I am making a mistake, or that's the way it is?
回答1:
AFAIK "that's the way it is", but you can look for cells that contain tables by using Cell.Tables rather than Cell.Range.Tables. e.g. to look for cells in the current selection that contain tables you could use
Sub listInnerTables()
Dim c As Cell
Dim r As Range
Dim t As Table
Dim tcount As Long
Set r = Selection.Range
If r.Tables.Count > 0 Then
tcount = 0
For Each t In r.Tables
tcount = tcount + 1
For Each c In t.Range.Cells
If c.Range.InRange(r) Then
If c.Tables.Count > 0 Then
Debug.Print "Table: " & CStr(tcount) & _
vbTab & " Row: " & CStr(c.RowIndex) & _
vbTab & " Col: " & CStr(c.ColumnIndex) & _
vbTab & " Table count: " & CStr(c.Tables.Count)
End If
End If
Next
Next
End If
Set r = Nothing
End Sub
来源:https://stackoverflow.com/questions/12105718/how-to-access-a-table-within-a-range-nested-in-another-table