Search code examples
excel-formulaoutputformulacell

Need macro to write the formula in a cell not the answer (ouput)


I cannot figure this out - I either get a Named? error or Application defined error on trying everything.

Dim sAmt As Integer
Dim sOriginalAmount As Integer
sOriginalAmount = ActiveCell.Value
sAmt = Application.InputBox("How much additional cost?", Type:=2)
ActiveCell.Formula = sOriginalAmount + sAmt

What I want Excel to do is write the formula in the cell not the output.

For example - Currently if I have sOriginalAmount as 15 and I enter sAmt as 20, on running the code, it gives the answer 35 in the cell, but I want it to write =sum(valueofsOriginalAmount + valueofsAmt) so that at a later time I can see what was the original amount and how much was added.

Can anyone please help? I have tried & "" in various combinations but I just can't get it. Apologies for such a noobie question, but I am self learned and I code for my work only.


Solution

  • This should work.

    ActiveCell.Formula = "=" & sOriginalAmount & "+" & sAmt
    

    Or if you actually want to use SUM.

    ActiveCell.Formula = "=SUM(" & sOriginalAmount & "," & sAmt & ")"