简体   繁体   中英

Excel VBA: How to sum every row above?

I'm trying to write a formula which does the following: sum all rows above this one until row 3. (Row 1 and 2 are headers). This code has to go from columns E:AQ, What gets tricky for me is that the row with the last line varies monthly. This month it is row 133, next month it could be 145. Here is my code so far:

Sub Fsum()
Dim Rng1 As Range
Set ws1 = Worksheets("Actuals")
Set Rng1 = ws1.Range("A" & ws1.Rows.Count).End(x1Up)
.Range("Rng1:AQ").Formula = "=sum(???lines above???)"
End Sub

You can see where I get confused. Can someone help?

Here is one way to go about it:

Sub test()
Dim lr As Long

Dim ws As Worksheet

Set ws = Worksheets("Actuals")

With ws
    lr = .Cells(1, 5).EntireColumn.Find(what:="*", _
            After:=.Cells(1, 5).EntireColumn.Cells(1), _
            LookAt:=xlPart, _
            LookIn:=xlFormulas, _
            SearchOrder:=xlByRows, _
            SearchDirection:=xlPrevious, _
            MatchCase:=False).Row

    Range(.Cells(lr + 1, 5), .Cells(lr + 1, 43)).Formula = "=Sum(E3:E" & lr & ")"
End With

End Sub

This will find the last used cell in Column E (5 in the code) and set that as the overall last row. Then it will build a sum formula across to column AQ (43 in the code).

Each time you run the code, it will find the last row. So it should be fairly dymanic. If each column has a different last row, that can be done as well, just need to use a loop, but I got the impression that your last row will be different from report to report, not column to column.

Hope this helps!

EDIT*

Here is an alternate way of finding the last row in case the one above gives you problems:

Sub test()
Dim lr As Long

Dim ws As Worksheet

Set ws = Worksheets("Actuals")

With ws
    lr = ws.Range("E" & .Rows.Count).End(xlUp).Row

    Range(.Cells(lr + 1, 5), .Cells(lr + 1, 43)).Formula = "=Sum(E3:E" & lr & ")"
End With

End Sub

You will need to find the #REF! first and here is something for your reference to find the cell.

Option Explicit

Sub FindRef()

Dim Rng As Range
Dim RefRng As Range

Set Rng = Range("A1:F100") ' Use your own range
Set RefRng = Rng.Find(what:="#REF!", LookIn:=xlValues)

MsgBox "Found the #REF! " & RefRng.Column & RefRng.Row

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