The For Each Loop


The For Each Loop

The For Each loop is similar to the For ... Next loop but, instead of running through a set of values for a variable, the For Eachloop runs through every object within a set of objects. For example, the following code shows the For Each loop used to list every Worksheet in the current Excel Workbook:
Dim wSheet As Worksheet
For Each wSheet in Worksheets
    MsgBox "Found Worksheet: " & wSheet.Name
Next wSheet

The Exit For Statement

If, you want to exit a 'For' Loop early, you can use the Exit For statement. This statement causes VBA to jump out of the loop and continue with the next line of code outside of the loop. For example, you may be searching for a particular value in an array. You might loop through each entry of the array, but when you find the value you are looking for, you no longer wish to continue searching, so you might exit the loop before you get to the end of it.
The Exit For statement is illustrated in the following example, which loops through 100 array entries, comparing each to the value 'dVal'. The loop is exited early if dVal is found in the array :
For i = 1 To 100
    If dValues(i) = dVal Then
        IndexVal = i
        Exit For
    End If
Next i

Popular posts from this blog

50 Excel VBA Oral Interview Questions