【问题标题】:Shorthand approach to writing a long list of if statements编写一长串 if 语句的速记方法
【发布时间】:2015-01-09 00:28:50
【问题描述】:

有没有一种速记方法来编写这么一大段代码?

我目前的工作 - 但事实证明,要维护它是一种痛苦。

If cboOption1 = "bp" And cboOption5 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption1 = "bp" And cboOption6 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs"))

ElseIf cboOption1 = "bp" And cboOption7 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption1 = "bp" And cboOption8 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption2 = "bp" And cboOption5 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption2 = "bp" And cboOption6 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption2 = "bp" And cboOption7 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption2 = "bp" And cboOption8 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption3 = "bp" And cboOption5 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption3 = "bp" And cboOption6 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption3 = "bp" And cboOption7 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption3 = "bp" And cboOption8 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption4 = "bp" And cboOption5 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption4 = "bp" And cboOption6 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption4 = "bp" And cboOption7 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

ElseIf cboOption4 = "bp" And cboOption8 = "cs" Then
    Valid = False
    MsgBox ("You can not select bp and cs")

【问题讨论】:

    标签: ms-access combobox vba ms-access-2010


    【解决方案1】:

    首先使用一个常量来保存MsgBox 文本……每次都一样。

    然后您可以使用嵌套的For ... Next 循环来循环浏览您的目标组合框对。

    Const cstrPrompt As String = "You can not select bp and cs"
    Dim i As Long
    Dim j As Long
    
    For i = 1 To 4
        For j = 5 To 8
            If Me.Controls("cboOption" & i).Value = "bp" _
                    And Me.Controls("cboOption" & j).Value = "cs" Then
                 Valid = False
                 MsgBox cstrPrompt
            End If
        Next
    Next
    

    请注意,将为每对无效值显示一个MsgBox。如果您只想显示第一个无效对的通知然后停止,则您将跳出For 循环。

    【讨论】:

    • 太棒了 - 将参考这个以备将来使用。谢谢。
    猜你喜欢
    • 2014-10-21
    • 2012-06-22
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 2018-08-01
    • 2015-07-19
    相关资源
    最近更新 更多