vba - 如何快速识别Word中的空白表格列?
问题描述
我在自动生成的 word 文档中有很多大表,我想删除其中没有值的列。它们都有标题,所以基本上我需要检查第 2 行的值到最后,或者只是在一个字符串中获取整个列并在我理解的第一个 chr(14) 之后检查是列标记。
这是否可能无需逐行循环单元格,这似乎很慢,或者选择似乎导致屏幕出现问题并且 UI 冻结的列,有时会导致 Word 崩溃。
解决方案
你想做的事情是完全可能的,但可能会遇到问题。报告的选择范围内的单元格数量(以及要处理的文本)存在差异,具体取决于您是否使用
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
推荐阅读
- marko - MarkoJS 组件中“无法读取未定义的属性'insertInto'”错误的原因是什么?
- python - 如何向选定的用户发送邮件
- c# - 如何在 Code Xamarin Android 中设置 VerticalOptions、HorizontalOptions?
- powershell - 如何使用 Powershell 检查重复的文件名?
- javascript - 防止路由器出口默认属性
- django - 将进度返回到 Django 中每个值更改的模板
- flutter - 我是否在颤振应用程序中使用了正确的 .yaml 缩进?
- javascript - 如何使用vuejs根据数据禁用复选框
- python - angular 或 python django 哪个最适合开发 Web 应用程序?
- dialogflow-es - 聊天机器人迁移到第 2 版的确切时间是什么时候?