简体   繁体   中英

Excel VBA Sum Dynamic Range All Sheets

In each sheet, I want to sum column A from A3 downward (there are no empty cells) and insert the sum in the first empty cell.

The code below works fine for sheet1, but the sum value is wrong for sheet2 onward (in sheet2 the sum of sheet1 is doubled and this same value is inserted in sheet3 onward).

I'd be grateful if you could point out what I'm doing wrong, please?

Sub Sum_Dynamic_Rng()

Dim ws As Worksheet
Dim LastCell As Range

    For Each ws In ThisWorkbook.Worksheets


    Set LastCell = ws.Range("A3").End(xlDown).Offset(1, 0)

        LastCell.Formula = WorksheetFunction.Sum(Range(Range("A3"), Range("A3").End(xlDown)))

    Next ws

End Sub

You have to identify the ranges on each worksheet as you loop through them.

Sub Sum_Dynamic_Rng()

    Dim ws As Worksheet
    Dim LastCell As Range

    For Each ws In ThisWorkbook.Worksheets

        Set LastCell = ws.Range("A3").End(xlDown).Offset(1, 0)

        LastCell = WorksheetFunction.Sum(ws.Range(ws.Range("A3"), ws.Range("A3").End(xlDown)))

        'if you actually want a sum formula then,
        'LastCell.FormulaR1C1 = "=SUM(R3C:R[-1]C)"

    Next ws

End Sub

Sum Up Column From Above

'*******************************************************************************
' Purpose:    In all worksheets starting from the specified first cell
'             of a contiguous column range, sums up its values and returns
'             the result a specified number of rows below.
'*******************************************************************************

Sub SumUpColumnFromAbove()

    Const cStrRange As String = "A3"  ' Cell Range Address
    Const cLngOffset As Integer = 2   ' Result Offset (1 for first row below)

    Dim i As Integer

    With ThisWorkbook
        For i = 1 To .Worksheets.Count
            With .Worksheets(i).Range(cStrRange).Cells(1, 1)
                ' Check if range has more than one cell (row) i.e.
                ' the cell below is not empty.
                If Not IsEmpty(.Offset(1, 0)) Then  ' More than one cell.
                    .End(xlDown).Offset(cLngOffset, 0) = WorksheetFunction _
                            .Sum(.Resize(.End(xlDown).Row - 1))
                  Else                              ' One cell only.
                    .Offset(cLngOffset, 0) = WorksheetFunction _
                            .Sum(.Parent.Range(cStrRange))
                End If
            End With
        Next
    End With

End Sub
'*******************************************************************************

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM