Page 107 - Microsoft Office Excel 2003 Programming Inside Out
P. 107

VBA Programming Starter Kit

                             Do
                             [statement]
                             [Exit Do]
                             [statement]
                             Loop While condition
                             and

                             Do
                             [statement]
                             [Exit Do]
                             [statement]
                             Loop Until condition
                               ●  condition  Required expression that must evaluate to True or False
                               ●  statement  One or more optional statement lines that are executed during the loop
                               ●  Exit Do  Optional statement to exit the loop prematurely
                               ● Loop  Required statement to mark the end of the Do While or Do Until statement
                                  block
                             The following example increments a counter during each pass through the loop and uses a
                             message box to ask the user if they wish to continue:

                             Sub PermissionLoop()
                             Dim intCounter As Integer, strPrompt As String
                             Dim intResult As Integer
                             intCounter = 0
                             Do
                                 intCounter = intCounter + 1                                                 Chapter 4
                                 strPrompt = "You have looped" & Str$(intCounter) & " times." _
                                    & vbCrLf & "Do you wish to continue?"
                                 intResult = MsgBox(strPrompt, vbYesNo + vbExclamation)
                             Loop While intResult = vbYes
                             End Sub
                             And here is the same example, using the Do…Loop Until statement:

                             Sub PermissionLoop2()
                             Dim intCounter As Integer, strPrompt As String
                             Dim intResult As Integer
                             intCounter = 0
                             Do
                                 intCounter = intCounter + 1
                                 strPrompt = "You have looped" & Str$(intCounter) & " times." _
                                    & vbCrLf & "Do you wish to continue?"
                                 intResult = MsgBox(strPrompt, vbYesNo + vbExclamation)
                             Loop Until intResult = vbNo
                             End Sub



                                                                                                        81
                                                                                        Part 2:  Visual Basic for Applications
   102   103   104   105   106   107   108   109   110   111   112