How to loop rows with Excel VBA macro? How to loop rows with Excel VBA macro? vba vba

How to loop rows with Excel VBA macro?


Dim cell As RangeFor Each cell In Range("a1:a40")    'do stuff hereNext cell

You can get your current row with cell.Row. Good luck ^_^


How about:

Sub Catchers()    Dim cell As Range    Sheet1.Select 'SHEET: C    For Each cell In Range("C3:C40")        If cell.Value < 35 And cell.Value > 0 Then            With Sheet6                .Range("B" & cell.Row) = cell.Offset(0, 5) _                    & "." & cell.Offset(0, 6)                .Range("C" & cell.Row) = cell.Offset(0, -2) _                    & ", " & cell.Offset(0, -1) _                    & " " & cell.Offset(0, 7)                .Range("D" & cell.Row) = cell.Offset(0, 9) _                    & " " & cell.Offset(0, 2) _                    & " " & cell.Offset(0, 11) _                    & " " & cell.Offset(0, 10)            End With        End If    Next cell    Sheet6.Range("B4:D4").Rows.AutoFit    Sheet6.Range("B4:D4").Columns.AutoFitEnd Sub


There's not a lot you can do, but...

First, don't use the word 'cell' as a variable, it may work, but it's playing with fire, so

Dim curCell as Range

Second, you should loop through the Cells property of the Range

For Each curCell In Range("C3:C40").Cells

Third, you don't need to Select the cell, you can just manipulate the curCell variable

Lastly, you won't need to use ActiveCell, just use the curCell variable.

If curCell.Value < 35 And curCell.Value > 0 Then    cLefta = curCell.Offset(0, 5) & "."

In fact, you could also just use a short variable like 'c' and put the whole thing on one line:

cLeft = c.Offset(0,5) & "." & c.Offset(0,6) & vblf

Note: If your setup is close to the same every time, it would probably be easier to just use worksheet-functions.