在VBA中的if-then语句

时间:2012-10-24 18:17:50

标签: excel vba

我目前正在编写两组非常相似的if-else语句。它们基本上比较了三个下拉菜单,并确保用户没有放下两个匹配的首选项。例如:

cbo_fac1 - Kitchen    
cbo_fac2 - Kitchen   
cbo_fac3 - Lounge

这会返回错误消息,因为 cbo_fac1 cbo_fac2 匹配。但是有一个特殊的情况我正在努力实施。其中一个下拉案例是无偏好

cbo_fac1 - Kitchen    
cbo_fac2 - No preference
cbo_fac3 - No preference

cbo_fac1 - No preference    
cbo_fac2 - No preference
cbo_fac3 - No preference

使用任何方案不允许选择选项匹配。我该如何实现呢?这是我到目前为止使用的代码:

If cbo_fac1.Value = cbo_fac2.Value Then
    MsgBox ("Facilities preference 1 and facilities preference 2 cannot be the same. Please select another option for facilities preference 2, if you have none then select 'No preference'")
    Exit Sub
End If

If cbo_fac1.Value = cbo_fac3.Value Then
    MsgBox ("Facilities preference 1 and facilities preference 3 cannot be the same. Please select another option for facilities preference 3, if you have none then select 'No preference'")
    Exit Sub
End If

If cbo_fac2.Value = cbo_fac3.Value Then
    MsgBox ("Facilities preference 2 and facilities preference 3 cannot be the same. Please select another option for facilities preference 3, if you have none then select 'No preference'")
    Exit Sub
End If

2 个答案:

答案 0 :(得分:3)

如果你想把它写成一个巨大的if语句,那应该这样做:

If (cbo_fac1.Value <> cbo_fac2.Value Or cbo_fac1.Value = "No Preference") And _
   (cbo_fac2.Value <> cbo_fac3.Value Or cbo_fac2.Value = "No Preference") And _
   (cbo_fac1.Value <> cbo_fac3.Value Or cbo_fac3.Value = "No Preference") Then
     'Input is fine
else
     exit sub

End If

编辑:

只是因为这是相反的方式,有一个可能的msgbox:

If (cbo_fac1.value = cbo_fac2.value AND cbo_fac1.value <> "No Preference") OR _
   (cbo_fac2.value = cbo_fac3.value AND cbo_fac2.value <> "No Preference") OR _
   (cbo_fac1.value = cbo_fac3.value AND cbo_fac3.value <> "No Preference") then

   Msgbox "No two facilities can be the same. Please select another option " & _
          "for facilities preference, if you have none then select 'No preference'"
   exit sub
else
   'input is fine
end if

答案 1 :(得分:0)

检查

之类的内容
If cbo_fac1.Value = cbo_fac2.Value and cbo_fac1.Value <> "No Preference" and cbo_fac2.Value <> "No Preference" Then
    MsgBox ("Facilities preference 1 and facilities preference 2 cannot be the same. Please select another option for facilities preference 2, if you have none then select 'No preference'")
    Exit Sub
End If

对其他2个IF条件进行相同的检查。

UPDATE:

通过编写函数

还有另一种方法

以下是示例函数。

Sub PreferenceCheck(var1 As String, var2 As String)
    If var1 = "No Preference" Or var2 = "No Preference" Then
        tempVar = true
    End If
    If Not tempVar Then
        If var1=var2 Then
            MsgBox ("Facilities "&var1&" and facilities "&var2&" cannot be the same. Please select another option for facilities preference, if you have none then select 'No preference'")
        End If
    End If
End Sub

为3种组合调用此功能

PreferenceCheck(cbo_fac1.Value, cbo_fac2.Value)
PreferenceCheck(cbo_fac2.Value, cbo_fac3.Value)
PreferenceCheck(cbo_fac1.Value, cbo_fac3.Value)