Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 200

Do Until loops

Оглавление

The Do Until loop structure is similar to the Do While structure. The difference is evident only when the condition is tested. In a Do While loop, the loop executes while the condition is True; in a Do Until loop, the loop executes until the condition is True.

Do Until also has two syntaxes. Here's the first way:

Do [Until condition] [instructions] [Exit Do] [instructions] Loop

Here's the second way:

Do [instructions] [Exit Do] [instructions] Loop [Until condition]

The two examples that follow perform the same action as the Do While date entry examples in the previous section. The difference in these two procedures is where the condition is evaluated (at the beginning or the end of the loop). Here is the first example:

Sub EnterDates3() ' Do Until, with test at beginning Dim TheDate As Date TheDate = DateSerial(Year(Date), Month(Date), 1) Do Until Month(TheDate) <> Month(Date) ActiveCell = TheDate TheDate = TheDate + 1 ActiveCell.Offset(1, 0).Activate Loop End Sub

Here is the second example:

Sub EnterDates4() ' Do Until, with test at end Dim TheDate As Date TheDate = DateSerial(Year(Date), Month(Date), 1) Do ActiveCell = TheDate TheDate = TheDate + 1s ActiveCell.Offset(1, 0).Activate Loop Until Month(TheDate) <> Month(Date) End Sub

The following example was originally presented for the Do While loop but has been rewritten to use a Do Until loop. The only difference is the line with the Do statement. This example makes the code a bit clearer because it avoids the negative required in the Do While example.

Sub DoUntilDemo1() Dim LineCt As Long Dim LineOfText As String Open "c:\data\textfile.txt" For Input As #1 LineCt = 0 Do Until EOF(1) Line Input #1, LineOfText Range("A1").Offset(LineCt, 0) = UCase(LineOfText) LineCt = LineCt + 1 Loop Close #1 End Sub

Excel 2019 Power Programming with VBA

Подняться наверх