写一长串if语句的简写方法

时间:2015-01-09 00:28:50

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

是否有编写这一大块代码的速记方法?

我现在所做的工作 - 但事实证明这是一种背后的痛苦。

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

1 个答案:

答案 0 :(得分:3)

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