9/27/2020 excel - How can I insert variable into formula in VBA - Stack Overflow
How can I insert variable into formula in VBA
Asked 3 years, 7 months ago Active 3 years, 7 months ago Viewed 41k times
Can anyone solve this?
7 Sub test
Dim i as integer
For I = 1 to 10
ActiveCell.Offset(0, 2).Formula = "=Sum(E15,&i&)"
3 Next I
End Sub
vba excel formula
edited Jul 9 '18 at 19:34 asked Feb 28 '17 at 8:08
Community ♦ lcc
1 1 261 1 5 17
1 you need to take the i out of the " . But what are you trying to Sum ? – Shai Rado Feb 28 '17 at 8:12
2 Answers Active Oldest Votes
your actual goal is unclear
5 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:
https://stackoverflow.com/questions/42503316/how-can-i-insert-variable-into-formula-in-vba 1/2
9/27/2020 excel - How can I insert variable into formula in VBA - Stack Overflow
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
answered Feb 28 '17 at 8:28
user3598756
26.8k 4 14 23
Actually I did try on this "=Sum(E" & i & ":E15)" but I forgot to leave a space between the ampersand,& and
"i" That's the reason I couldn't have this code work>< – lcc Feb 28 '17 at 8:48
fine. then you may want to mark answer as accepted by clicking on the check mark beside the answer to
toggle it from greyed out to filled in. thank you! – user3598756 Mar 15 '17 at 8:09
You're close, trying to use ampersands ( & ) to concatenate strings.
6 ActiveCell.Offset(0, 2).Formula = "=Sum(E15," & i & ")"
Use the ampersands between strings to merge them, not inside strings.
answered Feb 28 '17 at 8:11
Wolfie
20.5k 7 22 50
1 What is the purpose of the formula =SUM(E15,1) ? – Shai Rado Feb 28 '17 at 8:21
1 Thanks, if it's the accepted answer then please mark it so... @ShaiRado, I agree it's unclear what the OP is
trying to achieve, but this is the solution to their specific problem :) – Wolfie Feb 28 '17 at 10:29
https://stackoverflow.com/questions/42503316/how-can-i-insert-variable-into-formula-in-vba 2/2