Shorthand 编写一长串 if 语句的方法

Shorthand approach to writing a long list of if statements

是否有shorthand方法来编写这么大的代码块?

我目前使用的是有效的 - 但事实证明,维护起来很麻烦。

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")

首先用一个常量来保存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 循环。