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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several