Home » excel » excel – How to sum with lastrow+1 and lastrow+2

excel – How to sum with lastrow+1 and lastrow+2

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have a macro in VBA and I would like that my cell B199 (lastrow-2 in my code) returns me the sum of my cell B200 (lastrow-1 in my code) and cell B201 (lastrow in my code). Unfortunately it does not work because by running my macro, the formula returns me an error in cell B199: #NAME?

Apparently, the problem comes in my code from this part of the code: "=SUM(lastrow-1&lastrow )"

Please find my code below, if someone can help me, it would be great. Thanks Xavi

enter image description here

Sub fgdjkgfjbbg2222()
Dim lastrow As Long
lastrow = Worksheets("youpi").Range("B" & Rows.Count).End(xlUp).Row
Worksheets("youpi").Activate
Range("B" & lastrow - 2).Value = "=SUM(lastrow-1&lastrow )"
End Sub
How to&Answers:

If I understand, you’re trying to sum values in Column B, based on what you get as the LastRow in Col. B.

In the formula in VBA, you need to use the variable, as below:

Range("B" & lastrow - 2).Value = "=SUM(B" & lastrow - 1 & ":B" & lastrow & ")"

Answer:

It doesn’t work because you are trying to use your VBA variables as variables in a cell formula. That isn’t possible since the vba variables have no values once they go out of scope (the macro finishes running)

Instead try this

Range("B" & lastrow - 2).FormulaR1C1 = "=SUM(R[1]C:R[2]C)"

This will create a dynamic formula that is the the same as typing in “=SUM(B200:B201)” into the cell.