VBA adding a number of columns based on Variable

bukimi

Board Regular
Joined
Apr 12, 2017
Messages
105
Office Version
  1. 2019
Platform
  1. Windows
Hello!

I'm writing a longer code, but can't find a solution to a problem. I have a variable that is a number of columns that need to be added (from 2 to 4).
The problem is that the columns to add are every 5 columns (left), that is:
VBA Code:
'example for adding 2 columns, variable=2
    ActiveCell.FormulaR1C1 = "=RC[-5]+RC[-10]"
VBA Code:
'example for adding 4 columns, variable=4
    ActiveCell.FormulaR1C1 = "=RC[-5]+RC[-10]+RC[-15]+RC[-20]"
Is there any way to get as many columns in a formula added as variable value? The workaround would be using "Select case" for 2-4, but some time in the future there may be more values needed, so I'm reluctant to use it that way.
 

Excel Facts

Get help while writing formula
Click the italics "fx" icon to the left of the formula bar to open the Functions Arguments dialog. Help is displayed for each argument.
Try something like:
VBA Code:
Sub MyFormula(X As Integer)

Dim i As Integer
Dim FrmText As String

For i = 1 To X
    FrmText = FrmText + "+RC[-" & i * 5 & "]"
Next i

ActiveCell.FormulaR1C1 = "=" & FrmText

End Sub


Sub Test()

Call MyFormula(5)

End Sub
 
Upvote 0
Solution
That's a smart solution. It gives extra "+" at the start of formula, but Excel still gets it right.
For example, the result is:
Excel Formula:
=+N6+I6+D6
Should I cut it with "Right" formula from 2nd character, or would you suggest a different fix?

PS. Thank you very much!
It cuts a dozen of unnecessary lines of code!
 
Last edited:
Upvote 0
The extra "+" doesn't matter. Some people start their formulas with that instead of typing the equals sign.
 
Upvote 0

Forum statistics

Threads
1,214,789
Messages
6,121,605
Members
449,038
Latest member
Arbind kumar

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top