编写一长串 if 语句的速记方法

Posted

技术标签:

【中文标题】编写一长串 if 语句的速记方法【英文标题】:Shorthand approach to writing a long list of if statements 【发布时间】: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")

【问题讨论】:

【参考方案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 循环。

【讨论】:

太棒了 - 将参考这个以备将来使用。谢谢。

以上是关于编写一长串 if 语句的速记方法的主要内容,如果未能解决你的问题,请参考以下文章

验证一长串随机邮政编码的最佳方法

存储一长串值的最佳方法

在Java .replaceAll方法中转义一长串元字符

java:一长串条件,怎么办? [关闭]

如何为一长串整数创建优化的迭代器?

设计带有一长串查询参数的 RESTful 查询 API [关闭]