通过VBA为Word表格单元格添加多公式时首列的异常行为
Word VBA表格公式批量添加异常问题解答
你遇到的这个现象不正常,属于Word VBA操作表格公式时的常见问题。
问题原因
在Word的VBA对象模型中,执行.Cell(...).Formula设置公式后,Word会自动将光标定位到该公式所在单元格的末尾。如果紧接着直接调用下一个单元格的.Formula方法,Word会因光标位置的干扰,错误地将后续所有公式都插入到当前光标所在的第一个单元格(也就是你先设置的Cell(5,1)),最终只保留最后一次写入的公式。
解决方案
有两种简单的修复方式:
方式一:设置公式后移动光标
每次设置完单元格公式后,将光标移出当前单元格,避免后续操作受光标位置影响:
Dim myTable As Table Selection.EndKey Unit:=wdStory Selection.TypeParagraph Set myTable = ActiveDocument.Tables.Add(Selection.Range, 5, 6) myTable.AutoFormat Format:=wdTableFormatGrid1 For i = 1 To myTable.Rows.count - 1 For j = 1 To myTable.Columns.count myTable.Cell(i, j).Range.InsertAfter i + j Next j Next i With myTable .Cell(5, 1).Formula "=SUM(ABOVE)" ' 移动光标到下一个单元格 Selection.MoveRight Unit:=wdCell .Cell(5, 2).Formula "=AVERAGE(ABOVE)" Selection.MoveRight Unit:=wdCell .Cell(5, 3).Formula "=MIN(ABOVE)" Selection.MoveRight Unit:=wdCell .Cell(5, 4).Formula "=Max(Above)" Selection.MoveRight Unit:=wdCell .Cell(5, 5).Formula "=Count(Above)" Selection.MoveRight Unit:=wdCell .Cell(5, 6).Formula "=Product(Above)" End With
方式二:直接操作单元格的Range对象
不依赖.Cell.Formula方法,改用单元格的Range.Formula属性赋值,彻底避开光标干扰问题:
Dim myTable As Table Selection.EndKey Unit:=wdStory Selection.TypeParagraph Set myTable = ActiveDocument.Tables.Add(Selection.Range, 5, 6) myTable.AutoFormat Format:=wdTableFormatGrid1 For i = 1 To myTable.Rows.count - 1 For j = 1 To myTable.Columns.count myTable.Cell(i, j).Range.InsertAfter i + j Next j Next i With myTable .Cell(5, 1).Range.Formula = "=SUM(ABOVE)" .Cell(5, 2).Range.Formula = "=AVERAGE(ABOVE)" .Cell(5, 3).Range.Formula = "=MIN(ABOVE)" .Cell(5, 4).Range.Formula = "=Max(Above)" .Cell(5, 5).Range.Formula = "=Count(Above)" .Cell(5, 6).Range.Formula = "=Product(Above)" End With
内容的提问来源于stack exchange,提问作者Hennadii Kolomoiets
相关产品推荐
相关产品推荐

