VBA/Excel/Access/Word/Language Basics/Do While

Материал из VB Эксперт
Перейти к: навигация, поиск

A counting variable I is initialized just prior to the loop and incremented inside the loop

 
Sub loopCounter()
    Dim I As Integer
    I = 1
    Do While Cells(I, "A").Value <> ""
           Cells(I, "B").Value = Cells(I, "A").Value
           I = I + 1
    Loop
End Sub



Do Loop While

 
Sub cmdDoLoopWhile()
   Dim intValue As Integer
   intValue = 10
    Do
        intValue = intValue + 1
    Loop While intValue < 35
End Sub



Do while loop

 
Sub cmdDoWhileLoop()
   Dim intValue As Integer
   intValue = 10
   Do While Nz(intValue) < 35
      intValue = intValue + 1
    Loop
End Sub



Execute the code block until the conditional statement is True.

 
Sub loopUntil()
    Dim I As Integer
    I = 1
    Do
           Cells(I, "B").Value = Cells(I, "A").Value
           I = I + 1
    Loop Until Cells(I, "A").Value = ""
End Sub



Put InputBox in a Do Loop

 
Sub ifTest7()
    Dim strMessage As String
    Dim intTest As Integer
    intTest = 1
    Do
        intNum = 4
        If intNum >= 1 And intNum <= 15 Then
            msgBox "the number is between 1 and 15"
            intTest = 2
        Else
            msgBox "Sorry, the number must be between 1 and 15"
            intTest = 3
        End If
    Loop While intTest = 1
End Sub



To ensure that the code block executes at least once, place the While keyword and conditional statement at the end of the Do/Loop

 
Sub WhileDemo()
    Dim I As Integer
    I = 1
    Do
           Cells(I, "B").Value = Cells(I, "A").Value
           I = I + 1
    Loop While Cells(I, "A").Value <> ""
End Sub



Use if statement in a do loop

 
   Sub SignIn2() 
       Dim secretCode As String 
       Do 
           secretCode = InputBox("Enter your secret code:") 
           If secretCode = "sp1045" Or secretCode = "" Then Exit Do 
       Loop While secretCode <> "sp1045" 
   End Sub



Use Integer variable as the loop control variable

 
Sub cmdEfficient()
       Dim intCounter As Integer
       intCounter = 12
       Do While intCounter < 35
          intCounter = intCounter + 1
       Loop
End Sub



Using the Do...While Loop

 
Sub AskForPassword()
    Dim pWord As String
    pWord = ""
    Do While pWord <> "PASS"
        pWord = InputBox("What is the Report password?")
    Loop
        MsgBox "You entered the correct Report password."
End Sub



Using the Do...While Loop with a Condition at the Bottom of the Loop

 
   Sub SignIn() 
       Dim secretCode As String 
       Do 
           secretCode = InputBox("Enter your secret code:") 
           If secretCode = "sp1045" Then Exit Do 
       Loop While secretCode <> "sp1045" 
   End Sub