I was lucky enough to get a response from someone on a previous question I have asked. See here.
Only thing I am struggling with is creating a loop that will end the ma
While you might actually want to loop until you get to a blank row, most people find it more useful to loop until the last populated row in a particular column, which works even if you have a few (or many) blanks in the column.
Note that you may not even need a loop. Using .autofilter
or .find
are much more efficient. (comparable to using a where clause in a SQL query instead of a cursor)
Having said all that, if you do need the loop, the best approach is to declare a few objects including the worksheet and range so that you can execute the loop without selecting or activating anything in your code. As any Excel VBA developer worth his or her salt will tell you, selecting and activating should always be avoided.
You can use the following as a template:
Sub LoopUntilLastRow()
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Dim lastRow As Long
Dim myColumn As String
Set ws = ThisWorkbook.Sheets("Sheet1")
myColumn = "A"
lastRow = ws.Range(myColumn & ws.Rows.Count).End(xlUp).Row
If lastRow = 1 Then
MsgBox "Column " & UCase(myColumn) & " is empty."
Exit Sub
End If
Set rng = ws.Range(myColumn & "1:" & myColumn & lastRow)
For Each cell In rng
' do something
cell.Interior.Color = vbYellow
Next cell
End Sub