Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert variable into formula in VBA

Tags:

excel

vba

formula

Can anyone solve this?

Sub test

Dim i as integer

For I = 1 to 10
   ActiveCell.Offset(0, 2).Formula = "=Sum(E15,&i&)"
Next I

End Sub
like image 502
gonzalloe Avatar asked Feb 28 '17 08:02

gonzalloe


People also ask

How do I add a variable in VBA?

Setting variables In VBA, declaring variables is optional, but you can't declare AND set the variable at the same time. We've added a line that assigns the value of a variable. In VBA, just append “. Value”, an equals sign, and the value you want to assign (in quotation marks).

How do I add a value to a cell in Excel VBA?

If you want a user to specify a value to enter in a cell you can use an input box. Let's say you want to enter the value in cell A1, the code would be like this: Range("A1").

How do I insert a formula in Excel VBA?

Insert VBA code to Excel WorkbookOpen your workbook in Excel. Press Alt + F11 to open Visual Basic Editor (VBE). Right-click on your workbook name in the "Project-VBAProject" pane (at the top left corner of the editor window) and select Insert -> Module from the context menu. Copy the VBA code (from a web-page etc.)


2 Answers

your actual goal is unclear

you may want to start form this code

Sub test()
    Dim i As Integer

    For i = 1 To 10
       cells(i, 4).Formula = "=Sum(E" & i & ":E15)"
    Next
End Sub

and adjust it to your needs, knowing that:

  • it currently writes in cells "D1:D10"

    since cells(i, 4) references a cell in 4th column (i.e.: column "D") 4 and i row, and we're inside a loop where i is looping through 1 to 10

    so if:

    • you want to reference a different column then just change 4 to the proper column index

    • you want to reference a different row then just change i to the proper row index (may be some i+2 if you need to iterate through 1 to 10 but start writing from row 3)

  • the formula written in those cells is:

    =SUM(E1:E15) in D1,

    =SUM(E2:E15) in D2,

    ....

    =SUM(E10:E15) in D10.

    so just change "=Sum(E" & i & ":E15)" to your actual needs

like image 172
user3598756 Avatar answered Nov 07 '22 05:11

user3598756


You're close, trying to use ampersands (&) to concatenate strings.

ActiveCell.Offset(0, 2).Formula = "=Sum(E15," & i & ")"

Use the ampersands between strings to merge them, not inside strings.

like image 7
Wolfie Avatar answered Nov 07 '22 05:11

Wolfie