【问题标题】:vba replace nested if statementvba替换嵌套if语句
【发布时间】:2013-10-27 15:20:18
【问题描述】:

有没有办法提高效率?我觉得有点丑。 我想验证是否有下一个“甲板”,如果有,执行一些,直到甲板8

这是我的代码:

         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

【问题讨论】:

  • 'Execute code for deck 1 是 1 行代码还是多行代码?你的 if 也不应该反过来吗?即从 7 到 0 而不是 0 到 7?
  • 另外,请注意,是基于甲板编号的代码变量(即甲板 2 执行 x 2 次,甲板 3 执行 3 次等)。任何有模式的东西,我想我都懂了。

标签: excel if-statement nested performance vba


【解决方案1】:

使用案例陈述

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 用于选择案例。尽管您的选择条件+顺序不正确:)
  • 是的,这不是一个完整的解决方案,只是嵌套 if 的替代方案
【解决方案2】:

进一步了解我的 cmets,如果您的 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
'

【讨论】:

  • 事情是(例如使用 OPTION 2),proc8 适用于所有,proc7 适用于 Case Is>1 等。例如,在 Case Is>7 中,我需要 Proc8+Proc7+Proc6...+Proc1 我应该坚持使用嵌套的 If 语句吗?我不认为 switch ca 是最好的选择,因为我必须重复代码。
  • 您仍然可以使用他的选项 2,只需将运算符更改为 = 并且如果它的 = 8 则执行 procs 1-8,= 7 执行 procs 1-7 唯一重复的代码就是调用子程序,而不是子程序中的代码。我认为这比嵌套的 ifs 更干净
猜你喜欢
  • 2016-11-20
  • 1970-01-01
  • 2016-04-23
  • 2017-03-06
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
相关资源
最近更新 更多