For loop in VBA

Basic Construct


	Dim x As Integer
	For x = 1 To 10

	Next x
                                                           




Nested For loop


	Dim x As Integer
	Dim y As Integer
	For x = 1 To 10
		For y = 1 To 10	

		Next y
	Next x
                                                           


Using the For loop to initialize a range of cells in Excel


	Sub InitCells()

	Dim x As Integer
	Dim y As Integer
	For x = 1 To 10
		Cells(x, 1) = x
	Next x
                                                           
	End Sub
                                                                            


For loop Step increment


	Dim x As Integer
	For x = 1 To 10 Step 2
		Cells(x, 1) = x
	Next x
                                                           


Exit the For loop


	Sub InitCells()

	Dim x As Integer
	Dim y As Integer
	For x = 1 To 10
		Cells(x, 1) = x
		If x = 5 Then Exit For
	Next x
                                                           
	End Sub
                                                                            


Continue the For loop


	Sub InitCells()

	Dim x As Integer
	Dim y As Integer
	For x = 1 To 10
		If x <= 5 Then
		    Cells(x, 1) = x
		End If
	Next x                                                           
	End Sub
                                                                            


You can also use the GoTo statement.


	Sub InitCells()

	Dim x As Integer
	Dim y As Integer
	For x = 1 To 10
		If x > 5 Then GoTo ContinueLoop
		Cells(x, 1) = x
	ContinueLoop:
	Next x
	Next x                                                           
	End Sub