VBA/Excel/Access/Word/Language Basics/Do While
Версия от 16:33, 26 мая 2010; (обсуждение)
Содержание
- 1 A counting variable I is initialized just prior to the loop and incremented inside the loop
- 2 Do Loop While
- 3 Do while loop
- 4 Execute the code block until the conditional statement is True.
- 5 Put InputBox in a Do Loop
- 6 To ensure that the code block executes at least once, place the While keyword and conditional statement at the end of the Do/Loop
- 7 Use if statement in a do loop
- 8 Use Integer variable as the loop control variable
- 9 Using the Do...While Loop
- 10 Using the Do...While Loop with a Condition at the Bottom of the Loop
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