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. eg D becomes E, then F.
There must be a labour saving way of doing this. Maybe looping?
Cheers.
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
it seems to me you should be after this:
Dim cel As Range
Dim s As String
For Each cel In Worksheets("Enter Data Here").Range("D11").Resize(, 50)
Select Case Len(r1) - Len(Replace(r1, "/", vbNullString))
Case 1
s = s & ";" & cel.Offset(-1).Value
Case 2
s = s & ";" & cel.Offset(-1).Value & "x2"
Case 3
s = s & ";" & cel.Offset(-1).Value & "x3"
End If
End Select
End With
Worksheets("SDS").Range("R5").Value = s
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.