“Going loopy with Visual Basic!” Presented by Robert Eadie.

35
Going loopy with Visual Basic! Going loopy with Visual Basic! Presented by Presented by Robert Eadie Robert Eadie

Transcript of “Going loopy with Visual Basic!” Presented by Robert Eadie.

Page 1: “Going loopy with Visual Basic!” Presented by Robert Eadie.

““Going loopy with Visual Going loopy with Visual Basic!Basic!””

Presented byPresented by

Robert EadieRobert Eadie

Page 2: “Going loopy with Visual Basic!” Presented by Robert Eadie.

IntroductionIntroduction

In the following set of slides, I will present the In the following set of slides, I will present the most common looping structures used in Visual most common looping structures used in Visual Basic along with examples of their use and pitfalls Basic along with examples of their use and pitfalls to avoid.to avoid.

Page 3: “Going loopy with Visual Basic!” Presented by Robert Eadie.

““What is a loop?What is a loop?””

Loop statements allow you to execute one or Loop statements allow you to execute one or more lines of code repetitively. Many tasks more lines of code repetitively. Many tasks consist of trivial operations that must be consist of trivial operations that must be repeated, so repeated, so looping structureslooping structures are an important are an important part of any programming language.part of any programming language.

Page 4: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Types of loop in Visual Types of loop in Visual BasicBasic

Visual Basic supports the following loop Visual Basic supports the following loop structures: structures: 

1. Do While...Loop1. Do While...Loop

2. Do Until...Loop2. Do Until...Loop

3. Do…Loop While3. Do…Loop While

4. Do…Loop Until4. Do…Loop Until

5. For…Next5. For…Next 6. For Each…Next6. For Each…Next

OpeOpenn

CloseClosedd

Page 5: “Going loopy with Visual Basic!” Presented by Robert Eadie.

1. Do While…Loop1. Do While…Loop

Use the Use the Do While...LoopDo While...Loop statement when you statement when you want to test a condition before you run the loop want to test a condition before you run the loop and then continue to run the loop while the and then continue to run the loop while the condition is condition is TrueTrue..The general format is:The general format is:

Do WhileDo While conditioncondition

statement-blockstatement-block

LoopLoop

Page 6: “Going loopy with Visual Basic!” Presented by Robert Eadie.

1.2 Do While…Loop1.2 Do While…Loop

Example:Example:

The The FunctionFunction procedure in the following slide procedure in the following slide counts the occurrences of a target string within counts the occurrences of a target string within another string by looping as long as the target another string by looping as long as the target string is found. Because the test is at the string is found. Because the test is at the beginning of the loop, the loop runs beginning of the loop, the loop runs only ifonly if the the string contains the target string. string contains the target string.

Page 7: “Going loopy with Visual Basic!” Presented by Robert Eadie.

1.3 Do While…Loop1.3 Do While…Loop

Function CountStrings(longstring, target)Function CountStrings(longstring, target)

position = 1position = 1

Do While InStr(position, longstring, target) 'Returns Do While InStr(position, longstring, target) 'Returns True/FalseTrue/False

position = InStr(position, longstring, target) + 1position = InStr(position, longstring, target) + 1

Count = Count + 1Count = Count + 1

LoopLoop

CountStrings = CountCountStrings = Count

End FunctionEnd Function

Page 8: “Going loopy with Visual Basic!” Presented by Robert Eadie.

2. Do Until…Loop2. Do Until…Loop

Use the Use the Do Until…LoopDo Until…Loop statement if you want to statement if you want to test the condition at the beginning of the loop test the condition at the beginning of the loop and then run the loop until the test condition and then run the loop until the test condition becomes becomes TrueTrue. If the condition is initially . If the condition is initially TrueTrue, , the statements inside the loop never run.the statements inside the loop never run.

The general format is:The general format is:

Do UntilDo Until conditioncondition

statement-blockstatement-block

LoopLoop

Page 9: “Going loopy with Visual Basic!” Presented by Robert Eadie.

2.2 Do Until…Loop2.2 Do Until…Loop

Look at the example below.Look at the example below.

With the test at the beginning of the loop, the With the test at the beginning of the loop, the loop won't run if loop won't run if ResponseResponse is equal to is equal to vbNovbNo..

Response = MsgBox("Do you want to process more data?", Response = MsgBox("Do you want to process more data?", vbYesNo)vbYesNo)

Do Until Response = vbNoDo Until Response = vbNo

ProcessUserData    ProcessUserData    'Call procedure to process 'Call procedure to process datadata

Response = MsgBox("Do you want to process more data?", Response = MsgBox("Do you want to process more data?", vbYesNo)vbYesNo)

LoopLoop

Page 10: “Going loopy with Visual Basic!” Presented by Robert Eadie.

SummarySummary

Both the Do While…Loop and Do Until…Loop are Both the Do While…Loop and Do Until…Loop are known as “pre-test” loops because the condition known as “pre-test” loops because the condition is tested is tested beforebefore the loop is executed. the loop is executed.

This means that the loop may This means that the loop may nevernever be be executed if the condition is not true the first executed if the condition is not true the first time it is checked.time it is checked.In such a case, the program bypasses the loop In such a case, the program bypasses the loop and continues with the and continues with the nextnext instruction. instruction.

Page 11: “Going loopy with Visual Basic!” Presented by Robert Eadie.

3. Do…Loop While3. Do…Loop While

When you want to make sure that the statements When you want to make sure that the statements in a loop will run at least once, use in a loop will run at least once, use Do…Loop Do…Loop WhileWhile to put the test at the end of the loop. The to put the test at the end of the loop. The statements will run statements will run as long asas long as the condition is the condition is TrueTrue..

The general format is:The general format is:

DoDo

statement-blockstatement-block

Loop WhileLoop While conditioncondition

Page 12: “Going loopy with Visual Basic!” Presented by Robert Eadie.

3.1 Do…Loop While3.1 Do…Loop While

In the following Microsoft Excel example, the In the following Microsoft Excel example, the loop runs only if the loop runs only if the FindFind method finds a cell method finds a cell that contains "test.“that contains "test.“

If the text is found, the loop sets the color of the If the text is found, the loop sets the color of the cell, and then searches for the next instance of cell, and then searches for the next instance of "test.“"test.“

If no other instance is found, the loop ends.If no other instance is found, the loop ends.

Page 13: “Going loopy with Visual Basic!” Presented by Robert Eadie.

3.2 Do…Loop While3.2 Do…Loop While

Sub MakeBlue()Sub MakeBlue()Set rSearch = Worksheets("sheet1").Range("a1:a10")Set rSearch = Worksheets("sheet1").Range("a1:a10")Set c = rSearch.Find("test")Set c = rSearch.Find("test")If Not c Is Nothing ThenIf Not c Is Nothing Then

first = c.Addressfirst = c.AddressDoDo

c.Font.ColorIndex = 5c.Font.ColorIndex = 5Set c = rSearch.FindNext(c)Set c = rSearch.FindNext(c)

Loop While (Not c Is Nothing) And (c.Address <> Loop While (Not c Is Nothing) And (c.Address <> first)first)

ElseElseMsgBox "not found“MsgBox "not found“

End IfEnd IfEnd Sub End Sub

Page 14: “Going loopy with Visual Basic!” Presented by Robert Eadie.

4. Do…Loop Until4. Do…Loop Until

With the With the Do…Loop UntilDo…Loop Until statement, which puts statement, which puts the test at the end of the loop, the loop runs at the test at the end of the loop, the loop runs at least once and stops running when the condition least once and stops running when the condition becomesbecomes TrueTrue. .

The general format is:The general format is:

DoDo

statement-blockstatement-block

Loop UntilLoop Until conditioncondition

Page 15: “Going loopy with Visual Basic!” Presented by Robert Eadie.

4.1 Do…Loop Until4.1 Do…Loop Until

Do Do

ProcessUserData    ProcessUserData    'Call procedure to 'Call procedure to process dataprocess data

response = MsgBox("Do you want to process more data?", response = MsgBox("Do you want to process more data?", vbYesNo)vbYesNo)

Loop Until response = vbNoLoop Until response = vbNo

Page 16: “Going loopy with Visual Basic!” Presented by Robert Eadie.

SummarySummary

Both the Do…Loop While and Do…Loop Until are Both the Do…Loop While and Do…Loop Until are known as “post-test” loops because the condition known as “post-test” loops because the condition is not tested until is not tested until afterafter the first execution of the the first execution of the loop.loop.This ensures that the loop will be executed at least This ensures that the loop will be executed at least once.once.

Page 17: “Going loopy with Visual Basic!” Presented by Robert Eadie.

SummarySummary

As stated at the beginning, the loops covered so As stated at the beginning, the loops covered so far are known as “far are known as “open loopsopen loops” in that the ” in that the number of times the loop will be executed is not number of times the loop will be executed is not known at runtime.known at runtime.

Page 18: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5. For…Next5. For…Next

When you know that you must run the statements When you know that you must run the statements a specific number of times, use a a specific number of times, use a For...NextFor...Next loop. loop.

Unlike the many variations of Unlike the many variations of Do…LoopDo…Loop, a , a For...NextFor...Next loop uses a counter variable that loop uses a counter variable that increases or decreases in value during each increases or decreases in value during each repetition of the loop.repetition of the loop. Whereas the variations of Whereas the variations of Do…LoopDo…Loop end when a end when a test condition becomes test condition becomes TrueTrue or or FalseFalse, a , a For...NextFor...Next loop ends when the counter variable loop ends when the counter variable reaches a specified value.reaches a specified value.

Page 19: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5.1 For…Next5.1 For…Next

The general format is:The general format is:

ForFor countercounter = = startvaluestartvalue ToTo endvalueendvalue [ [StepStep stepvaluestepvalue]]

statement-blockstatement-block

NextNext [ [countercounter]]Note: Note:

The variable name after the Next statement is The variable name after the Next statement is optional, but it can make you code easier to read, optional, but it can make you code easier to read, especially if you have several nested For…Next especially if you have several nested For…Next loops.loops.

Page 20: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5.2 For…Next5.2 For…Next

In executing the For…Next loop, Visual Basic does In executing the For…Next loop, Visual Basic does the following:the following:

1. Sets the 1. Sets the countercounter equalequal to to startvaluestartvalue..

2. Tests to see if 2. Tests to see if countercounter is greater than is greater than endvalueendvalue. If so, it . If so, it exits the loop. If exits the loop. If stepvaluestepvalue is is negativenegative, VB test to see , VB test to see if if countercounter is is less thanless than endvalueendvalue, in which case it exits , in which case it exits the loop.the loop.

3. Executes the 3. Executes the statement-blockstatement-block..

Page 21: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5.3 For…Next5.3 For…Next

4. Increments 4. Increments countercounter by the amount specified with the by the amount specified with the stepvaluestepvalue. If the . If the stepvaluestepvalue argument is omitted, argument is omitted, countercounter is incremented by 1. is incremented by 1.

5. Repeats steps 2 through 4.5. Repeats steps 2 through 4.

Note:Note:

The The stepvaluestepvalue argument can be either argument can be either positivepositive or or negativenegative. If . If startvaluestartvalue is greater than is greater than endvalueendvalue, , the the stepvaluestepvalue mustmust be negative. If not, the loop’s be negative. If not, the loop’s body will body will notnot be executed, not even once. be executed, not even once.

Page 22: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5.4 For…Next5.4 For…Next

The The SubSub procedure in the following example procedure in the following example sounds a tone however many times you specify.sounds a tone however many times you specify.

Sub BeepSeveral()Sub BeepSeveral()

numBeeps = InputBox("How many beeps?")numBeeps = InputBox("How many beeps?")

For counter = 1 To numBeepsFor counter = 1 To numBeeps

BeepBeep

Next counterNext counter

End SubEnd Sub

Page 23: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5.5 For…Next5.5 For…Next

Because it wasn’t specified otherwise, the counter Because it wasn’t specified otherwise, the counter variable in the preceding example increases by 1 variable in the preceding example increases by 1 each time the loop repeats.each time the loop repeats.

You can use the You can use the StepStep keyword to specify a keyword to specify a different increment for the counter variable. different increment for the counter variable.

If you specify a If you specify a negativenegative number, the counter number, the counter variable variable decreasesdecreases by the specified value each by the specified value each time through the loop.time through the loop.

Page 24: “Going loopy with Visual Basic!” Presented by Robert Eadie.

5.6 For…Next5.6 For…Next

In the following In the following SubSub procedure, which replaces procedure, which replaces every other value in an array with 0 (zero), the every other value in an array with 0 (zero), the counter variable increases by 2 each time the counter variable increases by 2 each time the loop repeats. loop repeats.

Sub ClearArray(ByRef ArrayToClear())Sub ClearArray(ByRef ArrayToClear())

For i = LBound(ArrayToClear) To UBound(ArrayToClear) For i = LBound(ArrayToClear) To UBound(ArrayToClear) Step 2Step 2

ArrayToClear(i) = 0ArrayToClear(i) = 0

Next iNext i

End SubEnd Sub

Page 25: “Going loopy with Visual Basic!” Presented by Robert Eadie.

6. For Each…Next6. For Each…Next

A A For Each...NextFor Each...Next loop is similar to a loop is similar to a For...NextFor...Next loop, except that it repeats a group of statements loop, except that it repeats a group of statements for each element in a collection of objects or in an for each element in a collection of objects or in an array, instead of repeating the statements a array, instead of repeating the statements a specified number of times. specified number of times.

This is especially useful if you don't know how This is especially useful if you don't know how many elements are in a collection, or if the many elements are in a collection, or if the contents of the collection might change as your contents of the collection might change as your procedure runs.procedure runs.

Page 26: “Going loopy with Visual Basic!” Presented by Robert Eadie.

6.1 For Each…Next6.1 For Each…Next

The general format is:The general format is:

ForFor EachEach elementelement InIn groupgroup

statement-blockstatement-block

NextNext elementelement

Page 27: “Going loopy with Visual Basic!” Presented by Robert Eadie.

6.2 For Each…Next6.2 For Each…Next

When Visual Basic runs a For Each…Next loop, it When Visual Basic runs a For Each…Next loop, it follows these steps:follows these steps:

2. It runs through the 2. It runs through the statement-blockstatement-block..

3. It tests to see whether 3. It tests to see whether elementelement is the is the lastlast element in element in group. If so, Visual Basic group. If so, Visual Basic exitsexits the loop. the loop.

4. It defines 4. It defines elementelement as naming the as naming the nextnext elementelement in in groupgroup..

5. It repeats steps 2 through 4.5. It repeats steps 2 through 4.

1. It defines 1. It defines elementelement as naming the as naming the firstfirst elementelement in in groupgroup (provided that there’s at least one (provided that there’s at least one elementelement).).

Page 28: “Going loopy with Visual Basic!” Presented by Robert Eadie.

6.3 For Each…Next6.3 For Each…Next

The following Microsoft Excel example examines The following Microsoft Excel example examines each cell in the current region for cell A1 on the each cell in the current region for cell A1 on the worksheet named "Sheet3" and formats its worksheet named "Sheet3" and formats its contents as red if its value is less than  – 1. contents as red if its value is less than  – 1.

For Each c In For Each c In Worksheets("sheet3").Range("a1").CurrentRegion.CellsWorksheets("sheet3").Range("a1").CurrentRegion.Cells

If c.Value < -1 Then c.Font.ColorIndex = 3If c.Value < -1 Then c.Font.ColorIndex = 3

Next cNext c

Page 29: “Going loopy with Visual Basic!” Presented by Robert Eadie.

6.4 For Each…Next6.4 For Each…Next

Keep the following restrictions in mind when using Keep the following restrictions in mind when using the the For Each...NextFor Each...Next statement: statement:

1. For collections, 1. For collections, elementelement can only be a can only be a Variant variableVariant variable, , a a generic Object variablegeneric Object variable, or a , or a specific object typespecific object type in a referenced object library. For arrays, in a referenced object library. For arrays, elementelement can can only be a Variant variable. only be a Variant variable.

2. You cannot use the 2. You cannot use the For Each...NextFor Each...Next statement with statement with an array of userdefined types, because a Variant an array of userdefined types, because a Variant variable cannot contain a userdefined type.variable cannot contain a userdefined type.

Page 30: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Quick Quiz !!Quick Quiz !!

ToTo UseUse

Test a condition at the Test a condition at the startstart of the loop, run the of the loop, run the loop only if the condition is loop only if the condition is TrueTrue, and continue until , and continue until the condition becomes the condition becomes FalseFalse

Do While…Do While…LoopLoop

Page 31: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Quick Quiz !!Quick Quiz !!

ToTo UseUse

Test a condition at the Test a condition at the startstart of the loop, run the of the loop, run the loop only if the condition is loop only if the condition is FalseFalse, and continue until , and continue until the condition becomes the condition becomes TrueTrue

Do Until…LoopDo Until…Loop

Page 32: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Quick Quiz !!Quick Quiz !!

ToTo UseUse

Always run the loop once, Always run the loop once, test a condition at the test a condition at the endend of the loop, continue while of the loop, continue while the condition is the condition is TrueTrue, and , and stop when the condition stop when the condition becomes becomes FalseFalse

Do…Loop Do…Loop WhileWhile

Page 33: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Quick Quiz !!Quick Quiz !!

ToTo UseUse

Always run the loop once, Always run the loop once, test a condition at the test a condition at the endend of the loop, continue while of the loop, continue while the condition is the condition is FalseFalse, and , and stop when the condition stop when the condition becomes becomes TrueTrue

Do…Loop UntilDo…Loop Until

Page 34: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Quick Quiz !!Quick Quiz !!

ToTo UseUse

Run a loop a Run a loop a setset number of number of times, using a loop times, using a loop countercounter that that startsstarts and and endsends at specified values at specified values and that and that changeschanges value by value by a specified amount each a specified amount each time through the looptime through the loop

For…NextFor…Next

Page 35: “Going loopy with Visual Basic!” Presented by Robert Eadie.

Quick Quiz !!Quick Quiz !!

ToTo UseUse

Run a loop Run a loop onceonce for for eacheach object in a object in a collectioncollection

For Each…NextFor Each…Next