问题
Is there a way to make this more efficient? I find it a bit ugly. I want to verity if there is a next "deck", if so, execute some for it, until deck8
here is my code:
If deckNum > 0 Then
'Execute code for deck 1
If deckNum > 1 Then
'Execute code for deck 2
If deckNum > 2 Then
'Execute code for deck 3
If deckNum > 3 Then
'Execute code for deck 4
If deckNum > 4 Then
'Execute code for deck 5
If deckNum > 5 Then
'Execute code for deck 6
If deckNum > 6 Then
'Execute code for deck 7
If deckNum > 7 Then
'Execute code for deck 8
End If
End If
End If
End If
End If
End If
End If
End If
回答1:
Use a Case Statement
Select Case deckNum
case 0
'execute code for deck 0
case 1
'execute code for deck 1
case 2
'execute code for deck 2
case 3
'execute code for deck 3
End Select
Here is an office VBA reference http://msdn.microsoft.com/en-us/library/office/gg278454.aspx
回答2:
Further to my comments, if your Execute code for..
is a one liner then see option 1
else see option 2
Second thing, you have to check in reverse else any number which is greater than 0
will fire the Deck 1
Code.
OPTION 1
Replace MsgBox...
with your one liner code.
Select Case deckNum
Case Is > 7: MsgBox "A"
Case Is > 6: MsgBox "B"
Case Is > 5: MsgBox "C"
Case Is > 4: MsgBox "D"
Case Is > 3: MsgBox "E"
Case Is > 2: MsgBox "F"
Case Is > 1: MsgBox "G"
Case Is > 0: MsgBox "H"
End Select
OPTION 2
Select Case deckNum
Case Is > 7: proc1
Case Is > 6: proc2
Case Is > 5: Proc3
Case Is > 4: Proc4
Case Is > 3: Proc5
Case Is > 2: Proc6
Case Is > 1: Proc7
Case Is > 0: Proc8
End Select
Sub proc1()
End Sub
Sub proc2()
End Sub
'
'~~> And So oN
'
来源:https://stackoverflow.com/questions/19455453/vba-replace-nested-if-statement