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:
Please find my code below, if someone can help me, it would be great. Thanks Xavi
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
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 & ")"
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(RC:RC)"
This will create a dynamic formula that is the the same as typing in “=SUM(B200:B201)” into the cell.