Autofill Dynamic Range Last Row and Last Column

百般思念 提交于 2019-12-08 05:52:30

问题


I have a workbook containing multiple sheets of varying sizes. I want to add a total column after the last row and copy the formula across all columns. I have defined the last row and column and the formula appears as expected in the correct place but I receive an error when trying to fill across. How do I correctly reference both dynamic cells for the fill? I'm just using a single sheet for now for testing but will eventually be looping through all the sheets in the book.

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

Thanks :)


回答1:


Like this?

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


来源:https://stackoverflow.com/questions/10753925/autofill-dynamic-range-last-row-and-last-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!