Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Do While" "Loop" and "While" "Wend" Loop. What's the difference?

Tags:

loops

excel

vba

I've encountered a a while...wend loop. I'm used to the Do While loop, so I was wondering what the differences were between these two loops.

I did some testing (code below) and both seem to give me the same results:

Sub test_loop_1()
Dim i As Integer
i = 1
Do While i < 10
    Cells(i, 1) = i
    i = i + 1
Loop

End Sub

Sub test_loop_2()
Dim i As Integer
i = 1
While i < 10
    Cells(i, 1) = i
    i = i + 1
Wend

End Sub
like image 229
umLu Avatar asked Sep 22 '15 22:09

umLu


People also ask

DO loops while wend?

The Microsoft Excel WHILE... WEND statement is used to create a WHILE loop in VBA. You use a WHILE loop when you are not sure how many times you want to execute the VBA code within the loop body. With a WHILE loop, the loop body may not execute even once.


2 Answers

An answer I referred to is no longer visible, but this answer still holds true. While/Wend is a hangover from Basic and Do/Loop should be your preferred syntax because:

  1. It supports checking the condition before entering the loop Do While [condition] ... Loop (zero or more loop executions)
  2. It supports checking the condition after entering the loop Do ... Loop While [condition] (one or more loop executions)
  3. It supports no specific condition Do ...(some logic) (Exit Do) ... Loop (one or more loop executions, potentially infinite)
like image 57
NeepNeepNeep Avatar answered Sep 20 '22 15:09

NeepNeepNeep


I don't think there is much of a difference in their execution other than the syntactical options that While Wendis not capable of:

Do
    someCode
While (someCondition)

As for speed, I did a simple test:

Sub whileLoopTest()
Dim i As Long, j As Long
Dim StartTime As Variant

i = 1
StartTime = Timer

While (i < 500000000)
    j = i + 2
    i = i + 1
Wend

Debug.Print "While execution time: " & Timer - StartTime
End Sub


Sub doWhileTest()
Dim i As Long, j As Long
Dim StartTime As Variant

i = 1
StartTime = Timer

Do While (i < 500000000)
    j = i + 2
    i = i + 1
Loop

Debug.Print "Do While execution time: " & Timer - StartTime
End Sub

Results:

While execution time: 6,429688  
While execution time: 6,429688
While execution time: 6,441406
Do While execution time: 6,429688
Do While execution time: 6,449219
Do While execution time: 6,4375
like image 32
Vegard Avatar answered Sep 20 '22 15:09

Vegard