for loop excel vba code example

Example 1: vba for loop

' For VBA//VB/Visual Basic only

' ================================================================
' METHOD: FUNDAMENTAL

'EXAMPLE
  Dim iTotalPrints As Integer
  iTotalPrints = 5

  For iCount = 1 To iTotalPrints
      MsgBox Prompt:=iCount, Title:="Method: Fundamental"
  Next

'SYNTAX
'	For <your-variable-to-be-used> = <first-number> To <last-number>
'		'Code that uses <your-variable-to-be-used>
'	Next

' ================================================================
' METHOD: WITHIN AN ARRAY

 'EXAMPLE
  Dim sTextList(4) As String 'Note: doesn't have to be of "String" data-type
  sTextList(0) = "aaa"
  sTextList(1) = "bbb"
  sTextList(2) = "ccc"
  sTextList(3) = "ddd"
  sTextList(4) = "eee"

  For Each sSeparateText In sTextList
    MsgBox Prompt:=sSeparateText, Title:="Method: Within an Array"
  Next

'SYNTAX
'	For Each <your-variable-to-be-used> In <your-array-of-texts> 
'		'Code that uses <your-variable-to-be-used>
'	Next

Example 2: excel vba for each

Dim Found, MyObject, MyCollection 
Found = False    ' Initialize variable. 
For Each MyObject In MyCollection    ' Iterate through each element.  
    If MyObject.Text = "Hello" Then    ' If Text equals "Hello". 
        Found = True    ' Set Found to True. 
        Exit For    ' Exit loop. 
    End If 
Next

Tags:

Vb Example