我已经在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 Sub2)这会产生类型不匹配运行时错误#13,并且调试器使用"Or“逻辑突出显示行-
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它们之间唯一的显著区别是“或”逻辑。对于如何编写“或”逻辑并使其工作,有什么想法吗?
发布于 2018-10-27 13:09:55
您需要编写完整的or语句,如下所示:
If [ProductType] <> "IFL" Or [ProductType] <> "3-TIER IPRN" Or [ProductType] <> "CD IPRN" Then ...发布于 2018-10-27 19:21:35
由于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]等于"3-TIER IPRN",那么Or语句将为[ProductType] <> "IFL"返回True,并且将验证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语句,即:
Private Sub ProductDue_BeforeUpdate(Cancel As Integer)
If [ProductDue] <> IsNotNull And (Not ([ProductType] = "IFL" Or [ProductType] = "3-TIER IPRN" Or [ProductType] = "CD IPRN")) Then
MsgBox ("ProductDue only valid for ProductType = IFL, 3-TIER IPRN, and CD IPRN")
End If
End Subhttps://stackoverflow.com/questions/53017952
复制相似问题