Word VBA向含合并单元格的表格右侧添加列的问题求助
问题描述
我有一个包含近1400个表格的Word文档,各表格列数不同且存在横向、纵向合并单元格,需为每个表格右侧添加一列。
注:以下代码为修改后的版本,目前仅测试第一个表格,功能正常后将循环处理所有表格。
编辑1:单元格合并引发运行时错误
代码执行t.Cell(r, 1).Select时出现错误:
Runtime error '5941':
The requested member of the collection does not exist.
推测问题原因:将表格最大行数存入变量q后,从第1行循环到第q行。测试表格最多6行,但第一列有1个标题单元格,剩余5行是纵向合并单元格,循环到第3行时,第一列对应单元格因合并不存在,引发错误。恳请提供解决方案。
测试代码:
Sub Atest() Dim t As Table, r As Long, p As Long Set t = ActiveDocument.Tables(1) t.Cell(1, 1).Select 'select table first cell p = Selection.Information(wdMaximumNumberOfColumns) 'get current column count t.Cell(1, p).Select 'select table first row, last cell q = Selection.Information(wdMaximumNumberOfRows) 'get current row count For r = 1 To q t.Cell(r, 1).Select p = Selection.Information(wdMaximumNumberOfColumns) 'get column count of current row Debug.Print "the value of r is "; r Debug.Print "the value of p is "; p t.Cell(r, p).Select Selection.InsertCells (0) 'insert cell right Next r End Sub
编辑2:列添加位置不符合预期
测试表格结构:第一列包含1个标题单元格,下方5行为纵向合并单元格,表格总计6行。
运行以下代码后,表格开头新增2列,而非预期的末尾加1列:
Sub AddNewColumnToTable() Dim t As Table Set t = ActiveDocument.Tables(1) t.Select Selection.Columns.Add End Sub
运行以下代码后,在第2列后新增2列:
Sub InsertNewColumnToTable() Dim t As Table Set t = ActiveDocument.Tables(1) t.Select Selection.InsertColumnsRight End Sub
内容的提问来源于stack exchange,提问作者Nate
相关产品推荐
相关产品推荐

