Creating a Loop in VBA Macro for Excel?

后端 未结 1 1404
广开言路
广开言路 2021-01-26 15:39

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

相关标签:
1条回答
  • 2021-01-26 16:13

    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
    
    0 讨论(0)
提交回复
热议问题