Do-While Construct

Do-While Loops


Basic Construct

Here’s the basic format for a Do-While Loop
[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Do [While condition]
[instructions]
[Exit Do]
[instructions]
Loop
[/sourcecode]

or

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]</span>
<pre>Do
[instructions]
[Exit Do]
[instructions]
Loop [While condition]
[/sourcecode]


Condition at the Beginning

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Sub EnterDates1()
‘Do While, with test at the beginning
Dim TheDate As Date
TheDate = DateSerial(Year(Date), Month(Date), 1)
Do While Month(TheDate) = Month(Date)
ActiveCell = TheDate
TheDate = TheDate + 1
ActiveCell.Offset(1, 0).Activate
Loop
End Sub
[/sourcecode]


Condition at the End

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Sub EnterDates2()
‘Do While, with test at the end
Dim TheDate As Date
TheDate = DateSerial(Year(Date), Month(Date), 1)
Do
ActiveCell = TheDate
TheDate = TheDate + 1
ActiveCell.Offset(1, 0).Activate
Loop While Month(TheDate) = Month(Date)
End Sub
[/sourcecode]


Do-While Sample Code

This procedure opens a text file, reads each line, converts the text to uppercase, and then stores it in the active sheet, beginning with cell A1 and continuing down the column. The procedure uses the VBA EOF function, which returns True when the end of the file has been reached. The final statement closes the text file. This code comes from John Walkenbach’s “Excel® 2007 Power Programming Excel® 2007 Power Programming with VBA” book.

[sourcecode language=”vb” light=”true” wraplines=”false” gutter=”false”]
Sub DoWhileDemo1()
Dim LineCt As Long
Dim LineOfText As String
Open "c:\data\textfile.txt" For Input As #1
LineCt = 0
Do While Not EOF(1)
Line Input #1, LineOfText
Range(“A1”).Offset(LineCt, 0) = UCase(LineOfText)
LineCt = LineCt + 1
Loop
Close #1
End Sub
[/sourcecode]