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:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may