2012-05-25 77 views
1

我有一個包含多張不同大小的工作簿。我想在最後一行之後添加一個總列,並將公式複製到所有列中。我已經定義了最後一行和列,並且公式在正確的位置出現了預期的結果,但在嘗試填充時收到錯誤。如何正確引用這兩個填充的動態單元格?我現在只是使用單張紙進行測試,但最終會循環閱讀本書中的所有紙張。自動填充動態範圍最後一行和最後一列

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 

謝謝:)

回答

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 
+0

太棒了!非常感謝。 split是什麼功能? –

+1

'斯普利特(細胞(,LCol)。地址,「$」)(1)'返回列名列號:) –

+0

我想我會用分來選擇複製到新的工作表的最後一欄粘貼好? –

相關問題