如何用vba批量删除word表格中的空白行、空白列?

时间:2024-03-13 21:29:48

在word中处理表格与在excel中处理表格是截然不同的。

如果要删除word表格中的行,可以使用Table对象的Rows属性返回具体的行,然后用Delete方法。

同理,如果要删除word表格中的列,可以使用Table对象的Columns属性返回具体的列,然后用Delete方法。

如果要判断是否为空行或者空列,可以遍历要判断的行或者列,统计下空白单元格的数量是否与总行数或者总列数一致,如果一致,表示当前行或者列均为空,然后就可以用上述的方法删除。

以下是批量删除word表格中的空白列的代码:

Sub QQ1722187970()
    Dim oDoc As Document
    Set oDoc = Word.ActiveDocument
    Dim oT As Table
    Dim oRng As Range
    Dim oCol As Column
    Dim oRow As Row
    Dim oCell As Cell
    With oDoc
        For Each oT In .Tables
            With oT
                iRow = .Rows.Count
                iCol = .Columns.Count
                For j = iCol To 1 Step -1
                    n = 0
                    For i = iRow To 1 Step -1
                        Set oCell = .Cell(i, j)
                        \'空白单元格含有两个字符Chr(13) & Chr(7)
                        If oCell.Range.Text = Chr(13) & Chr(7) Then
                            n = n + 1
                        End If
                    Next i
                    If n = iRow Then
                        .Columns(j).Delete
                    End If
                Next j
            End With
        Next
    End With
End Sub

以下是批量删除word表格中的空白行的代码:

 
Sub QQ1722187970()
    Dim oDoc As Document
    Set oDoc = Word.ActiveDocument
    Dim oT As Table
    Dim oRng As Range
    Dim oCol As Column
    Dim oRow As Row
    Dim oCell As Cell
    With oDoc
        For Each oT In .Tables
            With oT
                iRow = .Rows.Count
                iCol = .Columns.Count
                For i = iRow To 1 Step -1
                    n = 0
                    For j = iCol To 1 Step -1
                        Set oCell = .Cell(i, j)
                        \'空白单元格含有两个字符Chr(13) & Chr(7)
                        If oCell.Range.Text = Chr(13) & Chr(7) Then
                            n = n + 1
                        End If
                    Next j
                    If n = iCol Then
                        .Rows(i).Delete
                    End If
                Next i
            End With
        Next
    End With
End Sub