devxlogo

Use Loop Counters Even After Looping

Use Loop Counters Even After Looping

The value of a loop counter variable is incremented one beyond the set range when the loop is completed. For example, if you use a For i = 0 to 5…Next loop, i equals 6 when all loop iterations have been completed. If you use the For…Next statement with an Exit For statement, you can use the value of the loop counter variable to determine whether a condition was met during the loop. Here’s one possible application of this technique, which can be applied when you have an array of values, each element of which has a unique value:

 Dim sText(10) As String	Dim i As Long	' Initialize strings - A, B, C, D, ...	For i = 1 To 10		sText(i) = Chr$(Asc("A") + i)	Next i

Suppose you want to find which element, if any, has a given value. You could use a Do…Until Loop and a flag:

 Dim i As Long 	Dim IsFound As Boolean	i = 0	Do While Not IsFound		i = i + 1		If i > 10 Then Exit Do		If sText(i) = "J" Then IsFound = True	Loop	If IsFound Then		MsgBox "Found J as element: " & i	Else		MsgBox "Could not find J"	End If

Or you can use a For…Next loop without a flag:

 Dim i As Long	For i = 1 To 10		If sText(i) = "J" Then Exit For	Next i	If i <= 10 Then		MsgBox "Found J at element: " & i	Else		MsgBox "Could not find J"	End If

This search routine is shorter and faster in the second case.

See also  5 Ways to Improve Customer Experience
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist