簡體   English   中英

使用 excel vba 宏將總和擴展到動態范圍

[英]extend sum to dynamic range with excel vba macro

我正在嘗試將總和公式擴展到動態范圍。 總和包括從第 5 行到列中第二個最后使用的行的所有值,然后總和在最后使用的行中。 但是,行數和列數各不相同,唯一保持不變的是總和應始終從第 5 行開始。總和也始終從 C 列開始。我已經設法編寫了一個宏,將總和放入C列的最后一行。我現在正在研究一個宏,該宏將這個總和擴展到工作表中所有其他使用的列,除了最后一列(包含另一個值而不是總和)。 我正在使用 selection.autofill。 但是,我在聲明要填充的范圍時遇到問題。 VBA 給了我一個“預期:語句結束”錯誤,我不知道為什么。 有人可以向我解釋我做錯了什么嗎? 有沒有比 selection.autofill 更好的方法 - 我擔心它可能不會接管列,例如,當擴展到列 D 中的單元格時,實際上對列 D 求和? 這是我已經擁有的:

'
' sumtest Macro
'

'
Dim Cell As Range, sRange As Range
Dim wsDestination As Worksheet

With ThisWorkbook
Set wsDestination = .Worksheets("Overview")


End With

FirstRow = Rows(5).EntireRow
lastRow = wsDestination.Cells(Rows.Count, "A").End(xlUp).Row
LastRow1 = wsDestination.Cells(Rows.Count, "A").End(xlUp).Row
LastColumn1 = wsDestination.Cells(4, wsDestination.Columns.Count).End(xlToLeft).Column

Worksheets("Overview").Select
wsDestination.Cells(lastRow, "C").Select
ActiveCell.Formula = "=SUM(C5:C" & lastRow - 1 & ")"
Range(wsDestination.Cells(LastRow1, 3)).Select
Selection.AutoFill Destination:=Range(wsDestination.Cells(LastRow1,3),wsDestination.Cells(LastRow1,LastColumn -1)) Type:=xlFillDefault

End Sub

此代碼將在最后一行的每一列中寫入總和的

Option Explicit
Sub Sumtest()

    With ThisWorkbook.Sheets("Overview")
        Dim LastCol As Long: LastCol = .Cells(4, .Columns.Count).End(xlToLeft).Column
        Dim Cell As Range
        Dim LastRow As Long
        For Each Cell In .Range("C4", .Cells(4, LastCol))
            LastRow = .Cells(.Rows.Count, Cell.Column).End(xlUp).Row
            .Cells(LastRow, Cell.Column) = Application.Sum(.Range(Cell.Offset(1), .Cells(LastRow - 1, Cell.Column)))
        Next Cell
    End With

End Sub

請注意,代碼將檢查每一列的LastRow ,因此如果列的行數不同,則總數將位於第一行,每列沒有數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM