"Do While""Loop"和"While""Wend"Loop.有什么不同?

umL*_*mLu 19 excel vba loops excel-vba

在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
Run Code Online (Sandbox Code Playgroud)

Nee*_*eep 26

我提到的答案已不再可见,但这个答案仍然适用.虽然/ Wend是Basic的宿醉,Do/Loop应该是您首选的语法,因为:

  1. 它支持进入循环之前检查条件 Do While [condition] ... Loop(零个或多个循环执行)
  2. 它支持进入循环检查条件 Do ... Loop While [condition](一个或多个循环执行)
  3. 它不支持任何特定条件 Do ...(some logic) (Exit Do) ... Loop(一个或多个循环执行,可能无限)

  • "退出时"不存在&是的,我相信While/Wend是为了向后兼容而维护的.真的,它应该是你应该使用的Do/Loop. (2认同)

Veg*_*ard 7

我不认为除了不能执行的语法选项之外,它们的执行有很大差异While Wend:

Do
    someCode
While (someCondition)
Run Code Online (Sandbox Code Playgroud)

至于速度,我做了一个简单的测试:

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
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)