Microsoft Office Tutorials and References
In Depth Information
Controlling Execution
The following example is the RowOfLargest function presented in the previous section,
rewritten to use a Do While loop (using the first syntax):
Function RowOfLargest2(c)
NumRows = Rows.Count
MaxVal = Application.Max(Columns(c))
r = 1
Do While Cells(r, c) <> MaxVal
r = r + 1
Loop
RowOfLargest2 = r
End Function
The variable r starts out with a value of 1 and increments within the Do While loop. The looping
continues as long as the cell being evaluated is not equal to MaxVal . When the cell is equal to
MaxVal , the loop ends, and the function is assigned the value of r . Notice that if the maximum
value is in row 1, the looping does not occur.
The following procedure uses the second Do While loop syntax. The loop always executes at
least once.
Function RowOfLargest(c)
MaxVal = Application.Max(Columns(c))
r = 0
Do
r = r + 1
Loop While Cells(r, c) <> MaxVal
RowOfLargest = r
End Function
Do While loops can also contain one or more Exit Do statements. When an Exit Do
statement is encountered, the loop ends immediately.
Do Until loops
The Do Until loop structure closely resembles 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:
Do [Until condition]
[instructions]
[Exit Do]
[instructions]
Loop
 
Search JabSto ::




Custom Search