r/vba • u/aloilisia • 12d ago
Solved loop through a specific range and check if cell is not equal to the one before
Essentially, I want to loop the following code:
If Worksheets("Tabelle1").Range("A11") <> Worksheets("Tabelle1").Range("A10") Then
With Worksheets("Tabelle1").Range("A11:G11").Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 0
End With
End If
If Worksheets("Tabelle1").Range("A12") <> Worksheets("Tabelle1").Range("A11") Then
With Worksheets("Tabelle1").Range("A12:G12").Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 0
End With
End If
[...]
If Worksheets("Tabelle1").Range("A64") <> Worksheets("Tabelle1").Range("A63") Then
With Worksheets("Tabelle1").Range("A64:G64").Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlMedium
.ColorIndex = 0
End With
End If
End Sub
This is what I'm currently working with, which is obviously just not very elegant and efficient. I'm assuming there is a way to loop through this, but I'm not proficient enough with VBA to figure it out myself. Can anyone give me some advice?
Thank you in advance.
4
Upvotes
2
u/fanpages 240 12d ago edited 12d ago
What is the context of the looping?
Rows, columns, all cells in a (named) range, tables, list objects, worksheets, and/or workbooks, or something else?
Your thread title suggests: "loop through a specific range and check if cell is not equal to the one before".
How is the subroutine border() executed now? Manually, or from a different subroutine/function?
How is the 'specific range' going to be established?
Will the 'specific range' always be fixed, or will it vary?
What have you tried already?
1
u/idontreallyknow6969 1 12d ago
I think I see what you’re doing. If it’s from row 11 to 64 I’d just do a for loop something like
Dim ws as Worksheet
Set ws = ThisWorkbook.Sheets(“Tabelle1”)
Dim formatRange as Range
Dim i as Long
For i = 11 to 64
If ws.Range(“A” & i).Value <> ws.Range(“A” & i - 1).Value Then
Set formatRange = ws.Range(“A” & i & “:G” & i)
With formatRange
your formatting
End With
End If
Next i
1
u/TastiSqueeze 3 12d ago edited 12d ago
Define the variables as needed. Code below seems to work. You may want to tweak it a bit as this will insert a line after your last row of data.