vba替换嵌套的if语句

时间:2013-10-18 17:17:52

标签: excel-vba if-statement nested performance vba

有没有办法让这更有效率?我发现它有点难看。 我想要确认是否有下一个“套牌”,如果有,请执行一些,直到deck8

这是我的代码:

         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

2 个答案:

答案 0 :(得分:3)

使用案例陈述

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

这是办公室VBA参考http://msdn.microsoft.com/en-us/library/office/gg278454.aspx

答案 1 :(得分:0)

根据我的评论,如果您的Execute code for..是单行,请参阅option 1,否则请参阅option 2

第二件事,您必须反过来检查其他任何大于0的号码都会触发Deck 1代码。

选项1

MsgBox...替换为您的单行代码。

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

选项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
'