我已经在MS Access中创建了两个简单的VBA代码模块。
1)这个很好用-
Private Sub IFLType_BeforeUpdate(Cancel As Integer)
If [ProductType] <> "IFL" Then
If [IFLType] <> IsNotNull Then
MsgBox ("IFLType only valid for ProductType = IFL")
End If
End If
End Sub
2)这会产生Type Mismatch Runtime错误#13,调试器使用“或”逻辑突出显示该行-
Private Sub ProductDue_BeforeUpdate(Cancel As Integer)
If [ProductType] <> "IFL" Or "3-TIER IPRN" Or "CD IPRN" Then
If [ProductDue] <> IsNotNull Then
MsgBox ("ProductDue only valid for ProductType = IFL, 3-TIER IPRN, and CD IPRN")
End If
End If
End Sub
这两个之间的唯一显着区别是“或”逻辑。关于如何编写“或”逻辑并使之工作的任何想法吗?
答案 0 :(得分:2)
您需要这样写complete或statement:
If [ProductType] <> "IFL" Or [ProductType] <> "3-TIER IPRN" Or [ProductType] <> "CD IPRN" Then ...
答案 1 :(得分:0)
由于VBA中的operator precedence,比较运算符(例如<>
)将在逻辑运算符(例如Or
)之前进行评估;因此,您需要在每个逻辑运算符之间包括一个比较运算符,即:
Private Sub ProductDue_BeforeUpdate(Cancel As Integer)
If [ProductType] <> "IFL" Or [ProductType] <> "3-TIER IPRN" Or [ProductType] <> "CD IPRN" Then
If [ProductDue] <> IsNotNull Then
MsgBox ("ProductDue only valid for ProductType = IFL, 3-TIER IPRN, and CD IPRN")
End If
End If
End Sub
但是,根据您要向用户报告的消息,我相信您实际上将需要And
运算符来代替Or
运算符,因为如果[ProductType]
等于{ {1}},然后"3-TIER IPRN"
语句将为Or
返回True
,并且[ProductType] <> "IFL"
语句的测试表达式将得到验证。
因此,我相信您的测试应该是:
If
或者(也可能更具可读性):
Private Sub ProductDue_BeforeUpdate(Cancel As Integer)
If [ProductType] <> "IFL" And [ProductType] <> "3-TIER IPRN" And [ProductType] <> "CD IPRN" Then
If [ProductDue] <> IsNotNull Then
MsgBox ("ProductDue only valid for ProductType = IFL, 3-TIER IPRN, and CD IPRN")
End If
End If
End Sub
您还可以将第二个测试表达式与第一个测试表达式结合使用,以避免嵌套Private Sub ProductDue_BeforeUpdate(Cancel As Integer)
If Not ([ProductType] = "IFL" Or [ProductType] = "3-TIER IPRN" Or [ProductType] = "CD IPRN") Then
If [ProductDue] <> IsNotNull Then
MsgBox ("ProductDue only valid for ProductType = IFL, 3-TIER IPRN, and CD IPRN")
End If
End If
End Sub
语句,即:
If