Excel VBA - Loop

For…Next

loop through a range with the cells method.

Sub RoundToZero1() 
 For Counter = 1 To 20 
   Set curCell = Worksheets("Sheet1").Cells(Counter, 3) 
   If Abs(curCell.Value) < 0.01 Then curCell.Value = 0 
 Next Counter 
End Sub

For Each…Next

loop through a range is to use a For Each…Next loop with the collection of cells specified in the Range property

Sub RoundToZero2() 
 For Each c In Worksheets("Sheet1").Range("A1:D10").Cells 
     If Abs(c.Value) < 0.01 Then c.Value = 0 
 Next 
End Sub

If you don't know the region, you can use the Excel - Cell property of the ActiveCell.


Powered by ComboStrap