How To Loop Through Rows In Excel Vba

Looping through Rows in Excel VBA

In Excel VBA, you can loop through rows using various methods and techniques. Here, we will discuss a few common ways to achieve this.

Method 1: Using For Loop

The simplest way to loop through rows is by using a For Loop. This allows you to iterate through each row in a specified range.


    Sub LoopThroughRows()
        Dim rng As Range
        Dim row As Range
        
        Set rng = Range("A1:A10") ' Change the range as per your requirement
        
        For Each row In rng.Rows
            ' Perform actions on the current row
            ' Example: Print the values in column B of each row
            Debug.Print row.Offset(, 1).Value
        Next row
    End Sub
  

Method 2: Using Do While Loop

Another way to loop through rows is by using a Do While Loop. This allows you to iterate until a specific condition is met.


    Sub LoopThroughRows()
        Dim lastRow As Long
        Dim currentRow As Long
        
        lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Get the last row in column A
        
        currentRow = 1
        
        Do While currentRow <= lastRow
            ' Perform actions on the current row
            ' Example: Print the values in column B of each row
            Debug.Print Cells(currentRow, 2).Value
            
            currentRow = currentRow + 1
        Loop
    End Sub
  

Method 3: Using For Each Loop with UsedRange

If you want to loop through all the rows in the worksheet, you can use the UsedRange property to dynamically determine the range.


    Sub LoopThroughRows()
        Dim rng As Range
        Dim row As Range
        
        Set rng = UsedRange.Rows
        
        For Each row In rng
            ' Perform actions on the current row
            ' Example: Print the values in column B of each row
            Debug.Print row.Offset(, 1).Value
        Next row
    End Sub
  

These are just a few examples of how you can loop through rows in Excel VBA. You can modify and customize the code to suit your specific requirements. Remember to adjust the range and actions based on your needs.

Same cateogry post

Leave a comment