Search code examples
excelvbaloopsformulabloomberg

How to introduce loop numeration into a formula in order to skip columns


I'm a beginner with Vba. I have the following code:

Sub addbdh()
Dim i As Integer
Dim n As Integer

Range("A3").Select
Range(Selection, Selection.End(xlToRight)).Select

n = Selection.Count

For i = 1 To n
Cells(3, i * 2 - 1).Formula = "=BDH(B" & i * 2 - 1 & ",A1 ,B1 ,Today())"
Next i
End Sub

Initally it was aimed to introduce a formula in columns of 3rd row but skipping one column in the middle each time the loop rounds.

Neverthless, I realized my code works for the concept just described but transposed (skipping rows to introduce the formula in the rows of B column).

Since columns are named with alphabet letters, I don't know how can I introduce in a loop within a formula en element to skip columns as I've done at first with rows in the instruction:

Cells(3, i * 2 - 1).Formula = "=BDH(B" & i * 2 - 1 & ",A1 ,B1 ,Today())"

More specifically, I don't know how to convert "=BDH(B" & i * 2 - 1 & ",A1 ,B1 ,Today())" in order to skip one column each time instead of one row.

Could Someone help me?

Lot of thanks


Solution

  • When using indexed values in formulas, it is sometimes easier to use R1C1 formula style than A1 style.

    In your case, your R1C1 formula could be:

    Cells(3, i * 2 - 1).FormulaR1C1 = "=BDH(RC" & i * 2 - 1 & ",R1C1 ,R1C2 ,Today())"
    

    which means for the first parameter "cell in the same row as the current cell, (2*i-1)th column ", for the second one "cell in row 1 column 1 (aka A1)" and for the last "cell in row 1 column 2 (aka B1)".