Sat*_*ish 2 excel vba if-statement excel-vba
我正在为VBA中的MS Excel编写一个宏.在子程序中,我有一组条件要满足要执行的特定任务.从运行时间和内存的角度来看,下列哪种方法最佳?
方法1:
If condition_1 then
If condition_2 then
If condition_3 then
....
End If
End If
End If
Run Code Online (Sandbox Code Playgroud)
要么
方法2:
If condition_1 And condition_2 And ..... then
....
End If
Run Code Online (Sandbox Code Playgroud)
如果我有任何条件的Else语句,我必须去方法1来实现它.但是我没有任何条件的Else声明,因此两种方法在完成任务时都处于相同的水平.我只是想知道哪一个在运行时和内存方面会更好?
小智 7
即使你没有Else陈述,你的第一种方法也是更好的方法.
后者将评估每个,condition_X而第一个将在其中一个条件失败后跳过进一步检查.
你可以自己测试一下
Sub Main()
If Check1 And Check2 Then
End If
End Sub
Function Check1()
Debug.Print "exec Check1"
Check1 = False
End Function
Function Check2()
Debug.Print "exec Check2"
Check2 = True
End Function
Run Code Online (Sandbox Code Playgroud)
您应该看到即使Check1返回false,Check2也正在评估....这证明了重点.