在stackoverflow中阅读一些答案我看到了一个while
wend
循环。我习惯了do while
loop
,所以我想知道这两个循环之间会有什么区别。
我做了一些测试(下面的代码),两者似乎都给了我相同的结果。
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
答案 0 :(得分:24)
我提到的答案已不再可见,但这个答案仍然适用。虽然/ Wend是Basic的宿醉,Do / Loop应该是您首选的语法,因为:
Do While [condition] ... Loop
之前检查条件(零个或多个循环执行)
Do ... Loop While [condition]
后检查条件(一个或多个循环执行)
Do ...(some logic) (Exit Do) ... Loop
(一个或多个循环执行,可能是无限的)答案 1 :(得分:6)
除了While Wend
无法提供的语法选项之外,我认为他们的执行情况有很大不同:
Do
someCode
While (someCondition)
至于速度,我做了一个简单的测试:
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
结果:
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
答案 2 :(得分:-1)
事实上,你不需要“DO WHILE”因为你可以在没有“While”的情况下“DO-LOOP”。
如果我需要在没有隐含条件的情况下至少执行一次(或多次)动作,我会使用“DO LOOP”,如WHILE-WEND强制。
只是一个例子,一种闹钟:
Do
Display Time at screen
Sounds a buzz
if user confirm
exit do
end if
Loop