访问表格行或列时产生的错误

   

如果要访问绘制表格中单独的行或列,而该表格又不统一,则会产生一个运行时错误。例如,如果活动文档中第一张表格的每列中具有不同数量的行,则使用下列指令将导致出错。

Sub RemoveTableBorders()
    ActiveDocument.Tables(1).Rows(1).Borders.Enable = False
End Sub

要避免这种错误,可首先使用 SelectColumnSelectRow 方法选定一列或一行中的单元格。选定单元格后,再使用 Selection 对象的 Cells 属性。下列示例选定第一张文档表格中的第一行。Cells 属性用于访问选定的单元格(第一行中的所有单元格)以删除边框。

Sub RemoveTableBorders()
    ActiveDocument.Tables(1).Cell(1, 1).Select
    With Selection
        .SelectRow
        .Cells.Borders.Enable = False
    End With
End Sub

下列示例选定第一张文档表格的第一列。For Each...Next 循环语句用于在所选内容(第一列中的所有单元格)的每个单元格中添加文字。

Sub AddTextToTableCells()
    Dim intCell As Integer
    Dim oCell As Cell

    ActiveDocument.Tables(1).Cell(1, 1).Select
    Selection.SelectColumn
    intCell = 1

    For Each oCell In Selection.Cells
        oCell.Range.Text = "Cell " & intCell
        intCell = intCell + 1
    Next oCell
End Sub