如何在Excel中动态填充列求和公式至行内最后有效列?
动态填充求和公式到最后一列的VBA解决方案
你的代码存在两处语法错误,导致AutoFill无法正常执行,修正后的代码如下:
Sub IN7() Dim lr As Long, lc As Long ' 获取最后一行和最后一列的位置 lr = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row lc = Cells.Find("*", Cells(1, 1), xlFormulas, xlPart, xlByColumns, xlPrevious, False).Column ' 在目标行的B列写入求和公式 Range("B" & lr + 2).Formula = "=SUM(B2:B" & lr & ")" ' 自动填充公式到最后一列 Range("B" & lr + 2).AutoFill Destination:=Range("B" & lr + 2 & ":" & Cells(lr + 2, lc).Address) End Sub
错误说明与修正点:
- 原代码中
Range("B" & (lr + 2)")多了一个多余的双引号,导致字符串拼接失败,修正为Range("B" & lr + 2) - AutoFill的目标范围写法错误,原代码
Range("B" & (lr + 2)" & lc)无法生成有效的单元格区域,修正为Range("B" & lr + 2 & ":" & Cells(lr + 2, lc).Address),通过Cells(lr + 2, lc).Address动态获取最后一列的单元格地址 - 建议使用
.Formula而非.Value来写入公式,这是VBA中设置单元格公式的标准写法
额外优化建议:
如果你的数据是从其他工作簿提取的,最好明确指定工作表对象,避免因当前激活工作表不同导致的错误,示例如下:
Sub IN7() Dim ws As Worksheet Dim lr As Long, lc As Long ' 指定目标工作表,比如Sheet1,根据实际修改 Set ws = ThisWorkbook.Worksheets("Sheet1") With ws lr = .Cells.Find("*", .Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row lc = .Cells.Find("*", .Cells(1, 1), xlFormulas, xlPart, xlByColumns, xlPrevious, False).Column .Range("B" & lr + 2).Formula = "=SUM(B2:B" & lr & ")" .Range("B" & lr + 2).AutoFill Destination:=.Range("B" & lr + 2 & ":" & .Cells(lr + 2, lc).Address) End With End Sub
内容的提问来源于stack exchange,提问作者nln
相关产品推荐
相关产品推荐

