CptGoodar
CptGoodar

Reputation: 303

Getting VBA to display a formula with Subtracting

I asked a question yesterday on how to use VBA to display formulas within cells, which I now can use, except for my attempt at a subtraction.

I have my code here, is anyone able to point me in the right direction to get this to work.

With Worksheets(c10)
.Cells(NewEngineRowNumber + 3, 2).Formula = "=Sum((" & .Range(.Cells(NewEngineRowNumber + 6, 2)).Address(0, 0) & ") - (" & .Range(.Cells(NewEngineRowNumber + 2, 2)).Address(0, 0) & "))" 
End With

I belived this to be the most likly method after a few different attempt to make it work.

To produce something like in Cells(NewEngineRowNumber+3,2) in the formula bar to display =Cells(BX) - Cells(BY), where X = NewEngineRowNumber +6 and Y = NewEngineRowNumber +2

Any help in helping me understand how to edit this to make it work would be much appreciated.

Thanks

Upvotes: 0

Views: 367

Answers (1)

Axel Richter
Axel Richter

Reputation: 61880

Don't try doing all in one code line. Do separating it in multiple code lines is better for debugging:

With Worksheets(c10)
 sAddress1 = .Cells(NewEngineRowNumber + 6, 2).Address(0, 0)
 sAddress2 = .Cells(NewEngineRowNumber + 2, 2).Address(0, 0)
 sFormula = "=Sum(" & sAddress1 & "-" & sAddress2 & ")"

 .Cells(NewEngineRowNumber + 3, 2).Formula = sFormula
End With

But why are you thinking the SUM is necessary at all?

 sFormula = "=" & sAddress1 & "-" & sAddress2

should also work.

Upvotes: 1

Related Questions