我喜欢assylias的回答,但我会重构它如下:
Sub test()
Dim origNum As String
Dim creditOrDebit As String
origNum = "30062600006"
creditOrDebit = "D"
If creditOrDebit = "D" Then
If origNum = "006260006" Then
MsgBox "OK"
ElseIf origNum = "30062600006" Then
MsgBox "OK"
End If
End If
End Sub
creditOrDebit
这可能会为您节省一些 CPU 周期,因为如果<> "D"
检查origNum
.
更新:
我使用以下过程来测试我的理论,即我的过程更快:
Public Declare Function timeGetTime Lib "winmm.dll" () As Long
Sub DoTests2()
Dim startTime1 As Long
Dim endTime1 As Long
Dim startTime2 As Long
Dim endTime2 As Long
Dim i As Long
Dim msg As String
Const numberOfLoops As Long = 10000
Const origNum As String = "006260006"
Const creditOrDebit As String = "D"
startTime1 = timeGetTime
For i = 1 To numberOfLoops
If creditOrDebit = "D" Then
If origNum = "006260006" Then
' do something here
Debug.Print "OK"
ElseIf origNum = "30062600006" Then
' do something here
Debug.Print "OK"
End If
End If
Next i
endTime1 = timeGetTime
startTime2 = timeGetTime
For i = 1 To numberOfLoops
If (origNum = "006260006" Or origNum = "30062600006") And _
creditOrDebit = "D" Then
' do something here
Debug.Print "OK"
End If
Next i
endTime2 = timeGetTime
msg = "number of iterations: " & numberOfLoops & vbNewLine
msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
" ms" & vbNewLine
msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
" ms"
MsgBox msg
End Sub
我的计算机一定很慢,因为与assylias的测试相比,1,000,000 次迭代所花费的时间远不及 ~200 毫秒。我不得不将迭代次数限制在 10,000 次——嘿,我还有其他事情要做 :)
运行上述程序 10 次后,我的程序只快了 20% 的时间。然而,当它变慢时,它只是表面上变慢。然而,正如assylias指出的那样,creditOrDebit
我<>"D"
的过程至少快两倍。我能够在 1 亿次迭代中合理地测试它。
这就是我重构它的原因——将逻辑短路,这样origNum
就不需要在creditOrDebit <> "D"
.
此时,其余的取决于 OP 的电子表格。如果creditOrDebit
可能等于 D,则使用assylias程序,因为它通常会运行得更快。但是,如果creditOrDebit
具有广泛的可能值,并且D
不再可能是目标值,我的程序将利用它来防止不必要地评估其他变量。