自动填充动态范围最后一行和最后一列

时间:2012-05-25 11:50:52

标签: excel excel-vba excel-formula autofill vba

我有一个包含多张不同大小的工作簿。我想在最后一行之后添加一个总列,并在所有列中复制公式。我已经定义了最后一行和列,并且公式在正确的位置显示为预期但我在尝试填充时收到错误。如何正确引用两个动态单元格进行填充?我现在只是用一张纸进行测试,但最终会循环遍历书中的所有表格。

Sub Addtotals()

    Dim Bord As Worksheet
    Dim LRow As Long
    Dim LCol As Long
    Dim frmcell As Range

    Set Bord = Sheets("Borders")
    With Bord
    '--> Define last rows and columns
        LRow = .Range("A" & Rows.Count).End(xlUp).Row
        LCol = .Range("A" & Columns.Count).End(xlToLeft).Column

    '--> Add Total text to first column
        .Range("A" & LRow).Offset(1, 0).Select
        ActiveCell = "Total"

    '--> Add formula to next column
        Set frmcell = Range("B" & LRow + 1)
        frmcell.Formula = "=sum(B2:B" & LRow & ")"

    '--> Fill formula across range
        frmcell.Select
        Selection.AutoFill Destination:=Range(frmcell & LCol), Type:=xlFillDefault
    End With
End Sub

谢谢:)

1 个答案:

答案 0 :(得分:2)

喜欢这个吗?

Option Explicit

Sub Addtotals()
    Dim Bord As Worksheet
    Dim LRow As Long, LCol As Long

    Set Bord = Sheets("Borders")
    With Bord
    '--> Define last rows and columns
        LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
        LCol = .Cells(1, Columns.Count).End(xlToLeft).Column

    '--> Add Total text to first column
        .Range("A" & LRow).Value = "Total"

    '--> Fill formula across range
        .Range("B" & LRow & ":" & _
        Split(Cells(, LCol).Address, "$")(1) & LRow).Formula = _
        "=Sum(B2:B" & LRow - 1 & ")"
    End With
End Sub