为嵌套表格应用格式

Apply formatting for nested tables

在我的文档中,我有一个名为 "Small" 的 table 样式。这是宏,它将改变这种样式的每个 table 中的字体大小:

Sub FormatTables()
    Dim t As Table
    For Each t In ActiveDocument.Tables
        If t.Style = "Small" Then
            t.Range.Font.Size = 8
        End If
    Next
End Sub

问题是,它不适用于嵌套的 table。下图中,黑色table为"Normal",蓝色table为"Small"。如何解决?

这应该处理每个 table,甚至那些嵌套到任意深度的 table。

Sub FormatTables()

    Dim t As Table, col As New Collection
    Dim n As Table

    'add all top-level table(s) to collection
    For Each t In ActiveDocument.Tables
        col.Add t
    Next

    'process each table from the collection
    Do While col.Count > 0
        Set t = col(1) '<< reference the first table from the collection
        col.Remove 1   '<< remove it from collection
        Debug.Print "Table has " & t.Rows.Count & " rows", t.Style

        If t.Style = "Small" Then t.Range.Font.Size = 8

        'gather any nested table(s) for checking
        For Each n In t.Tables
            col.Add n
        Next n
    Loop

End Sub

我也有类似的问题。在发布这个之前我做了很多研究。我创建了一个空文档,插入了两个小 table,将其中一个与另一个 table 嵌套在一起,并使用以下代码进行了测试:

Sub testtest()

Dim aRange As Range

MsgBox ThisDocument.Tables.Count
For Each oTable In ThisDocument.Tables
    For Each oCell In oTable.Range.Cells
        Set aRange = oCell.Range
        aRange.MoveEnd Count:=-2
        aRange.Select
        MsgBox aRange.Tables.Count
        MsgBox oCell.Tables.Count
    Next oCell
Next oTable



End Sub

解释:首先,我将单元格范围的末尾移动 -1 然后移动 -2 的原因是为了排除 a 末尾的可疑 Chr(13)Chr(7)细胞。这就解释了,现在,通过上面的测试,我发现即使没有 table 嵌套在单元格中, aRange.Tables.Count 也始终为 1(永远不会为 0)。直到我通过MsgBox检查了oCell.Tables.Count,我才感到困惑。 -- oTable.TablesoTable.Range.Tables 之间的区别是相似的。 -- 嵌套的 table 嵌套到父级 Table 并且嵌套到上层 Cell,但不嵌套到 table 或单元格的 [=20] =]!

因此,我认为所选答案确实提供了一种利用 Collection 的绝妙方法(这是 vba 所独有的,我似乎记得在某处读过),并且确实有效解决了问题,但是,它并没有指出问题的"hinge"或"knack"。再一次,"knack" 是您可以 "catch" 嵌套的 table 使用 oTable.Tables 而不是 oTable.Range.Tables;相比之下,您可以 "catch" table 中的单元格使用 oTable.Range.Cells 而不是 oTable.Cells.