【问题标题】:Autofill Dynamic Range Last Row and Last Column自动填充动态范围最后一行和最后一列
【发布时间】:2012-06-01 00:10:25
【问题描述】:

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

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

谢谢:)

【问题讨论】:

    标签: excel excel-formula autofill vba


    【解决方案1】:

    像这样?

    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
    

    【讨论】:

    • 太棒了!非常感谢。 split的作用是什么?
    • Split(Cells(, LCol).Address, "$")(1) 从列号返回列名:)
    • 我想我会使用 split 来选择复制和粘贴到新工作表的最后一列?
    • 是的 :) 提供 LCol 包含最后一列的正确列号
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多