How can I increase a cell reference automatically in Excel VBA so that a macro is run in every column?

Cdurell :

So I have a macro that references specific cells in a workbook. How can I repeat this macro in the next fifty columns without manually typing out the cell references fifty times?

If I was just using excel formulas and not VBA I could click and drag to automatically repeat the formulas in the next column. The cell references I would like to remain the same I would define as $absolute$ references. But in VBA I don't know how to do it.

Here is the code:

If Worksheets("Enter Data Here").Range("D11") = "" Then
    Worksheets("SDS").Range("R5") = Worksheets("SDS").Range("R5") & ""

ElseIf Worksheets("Enter Data Here").Range("D11") = "/" Then
    Worksheets("SDS").Range("R5") = Worksheets("SDS").Range("R5") & ";" & Worksheets("Enter Data Here").Range("D10")

ElseIf Worksheets("Enter Data Here").Range("D11") = "//" Then
    Worksheets("SDS").Range("R5") = Worksheets("SDS").Range("R5") & ";" & Worksheets("Enter Data Here").Range("D10") & "x2"

ElseIf Worksheets("Enter Data Here").Range("D11") = "///" Then
    Worksheets("SDS").Range("R5") = Worksheets("SDS").Range("R5") & ";" & Worksheets("Enter Data Here").Range("D10") & "x3"


End If

Worksheets("SDS").Range("R5") is the absolute cell reference and does not change, but I would like the others to shift along to the next column without typing it. e.g. D becomes E, then F.

There must be a labour saving way of doing this. Maybe looping?

Cheers.

SJR :

Try this.

Sub x()

Dim r1 As Range, i As Long

Set r1 = Worksheets("Enter Data Here").Range("D11") 'define starting cell

For i = 1 To 50 'repeat this 50 times
    With Worksheets("SDS").Range("R5")
        If r1 = "" Then
             .Value = .Value & "" 'not sure what purpose this serves
        ElseIf r1.Value = "/" Then
            .Value = .Value & ";" & r1.Offset(-1).Value
        ElseIf r1.Value = "//" Then
            .Value = .Value & ";" & r1.Offset(-1).Value & "x2"
        ElseIf r1.Value = "///" Then
            .Value = .Value & ";" & r1.Offset(-1).Value & "x3"
        End If
    End With
    Set r1 = r1.Offset(, 1) 'move to cell to the right, E11, F11 etc
Next i

End Sub

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398024&siteId=1