如何快速识别Word中的空白表列?

问题描述 投票:1回答:1

我在自动生成的word文档中有很多大表,我想删除没有值的列。它们都有标题,所以基本上我需要检查第2行到最后的值,或者只是在字符串中得到整列,然后检查第一个chr(14),我理解的是列标记。

这是否可能没有循环遍历单元格,逐行,这看起来很慢,或者选择似乎导致屏幕出现问题并且UI冻结的列,有时会崩溃Word。

vba word-vba
1个回答
1
投票

您想要做的事情是完全可能的,但可能会遇到问题。报告的选择范围中的单元格数量(以及因此要处理的文本)存在差异,具体取决于您是否使用

selection.cells

要么

selection.range.cells

前者按预期工作,后者则不然。

下面的代码以您描述的方式删除列,并且还包括debug.print语句以演示该问题。

我在5x6表上测试了代码。您的经历可能有所不同

Sub DeleteEmptyTableColumns(this_table As Word.Table)
    Dim my_cells                As Range
    Dim my_column               As Long
    Dim my_text                 As String
    Dim my_last_row             As Long

    ' Assumes that the Table is uniform
    my_last_row = this_table.Rows.Count
    Application.ScreenUpdating = False

    With this_table
        For my_column = .Columns.Count To 1 Step -1
            DoEvents
            Set my_cells = .Range.Document.Range( _
                Start:=.Cell(2, my_column).Range.Start, _
                End:=.Cell(my_last_row, my_column).Range.End)
            ' We have to use selection to get the correct text
            my_cells.Select

            Debug.Print
            ' Wrong numbers and text
            Debug.Print my_cells.Cells.Count
            Debug.Print my_cells.Text

            ' Correct information
            Debug.Print Selection.Cells.Count
            Debug.Print Selection.Text

            ' Back to the wrong information
            Debug.Print Selection.Range.Cells.Count
            Debug.Print Selection.Range.Text

            my_text = Selection.Text

            ' Add other replacments as required.
            my_text = Replace(my_text, " ", vbNullString)
            my_text = Replace(my_text, vbCrLf, vbNullString)
            my_text = Replace(my_text, Chr$(13), vbNullString)
            my_text = Replace(my_text, Chr$(7), vbNullString)

            If Len(my_text) = 0 Then
                this_table.Columns(my_column).Delete

            End If

        Next

    End With

    Application.ScreenUpdating = True

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.