在用vba处理word的表格时,经常会遇到word表格中的合并单元格。
它不同于excel的合并单元格,word vba表格中没有属性可以判断单元格是否是合并单元格。
当遇到word表格中有合并单元格时,如果用逐个单元格遍历的方式,往往会弹出错误的提示。
如下图所示

如果要用vba将word表格中除了序号以外的所有数字设置为两位小数,用如下的代码:
Sub QQ1722187970()
Dim oCell As Cell
Dim oTable As Table
Dim iCol
For Each oTable In ActiveDocument.Tables
With oTable
For Each oCell In .Range.Cells
If oCell.Column > 1 Then
With oCell
sText = oCell.Range.Text
sText = Replace(sText, Chr(13) & Chr(7), "")
If IsNumeric(sText) Then
sText = VBA.Format(sText, "##0.00")
oCell.Range = sText
End If
End With
End If
Next
End With
Next
End Sub

因为word的表格中含有合并单元格,导致单元格的宽度不一致,所以无法用遍历的方式访问。
在 如何用vba选中word表格中行、列、单元格?一文中,我们介绍了通过用Selection对象的SelectCell、SelectRow、SelectColumn方法可以选中word表格中的行、列、单元格对象。
通过选中word表格行、列后再遍历的方式可以绕开合并单元格的坑,比如上述的案例可以通过如下的代码来解决:
Sub QQ1722187970()
Dim oCell As Cell
Dim oTable As Table
Dim iCol
For Each oTable In ActiveDocument.Tables
With oTable
iCol = .Columns.Count
For i = 2 To iCol
'先选中单个单元格
.Cell(1, i).Select
'再选中整列
Word.Selection.SelectColumn
'然后遍历
For Each oCell In Word.Selection.Cells
With oCell
sText = oCell.Range.Text
sText = Replace(sText, Chr(13) & Chr(7), "")
If IsNumeric(sText) Then
sText = VBA.Format(sText, "##0.00"): oCell.Range = sText
End If
End With
Next
Next i
End With
Next
End Sub


发表评论