Microsoft Visual Basic 运行-时间错误
Microsoft Visual Basic Run-time error
我正在使用 MS Access 2007 和 VBA。我有一段代码,当数量大于库存或库存为零时触发。
Private Sub Quantity_BeforeUpdate(Cancel As Integer)
If Me.Quantity > Me.Stock Or Me.Stock = 0 Then
MsgBox "Not enough stocks left."
Me.Quantity = ""
End If
End Sub
出现消息框,但随后出现错误消息:
Run-time error '2147352567 (80020009)':
The macro or function set to BeforeUpdate or ValidationRule property for this field is preventing Microsoft Office Access from saving the data in the field.
如何停止这个错误?
在 MS Access 中,您无法在 "BeforeUpdate" 事件中设置控件值。所以这一行:
Me.Quantity = ""
导致您的错误消息。所以你需要寻找一种替代方法来做你想做的事情。我认为 "AfterUpdate" 事件将满足您的需求。
控件的 Before Update 事件不允许您将其更改为任何值。此时你有 2 个选择:
- 调用
Cancel
然后调用 Undo
将其值恢复为尝试更新之前的值
- 仅调用
Cancel
,保留新的(不可接受的)值,但在继续之前强制用户将其替换为可接受的值
这是第一个选项的测试示例代码。如果您更喜欢第二个选项,请丢弃 Me.Quantity.Undo
行。
Private Sub Quantity_BeforeUpdate(Cancel As Integer)
If Me.Quantity > Me.Stock Or Me.Stock = 0 Then
MsgBox "Not enough stocks left."
'Me.Quantity = "" ' <-- NOT ALLOWED
Cancel = True
Me.Quantity.Undo
End If
End Sub
当Me.Quantity
和Me.Stock
是包含数字的文本值时,情况比较复杂。如果是我,我宁愿将他们的数据类型更改为数字。但如果该更改不切实际,您可以使用 Val()
将文本值转换为实际数字以供比较。
Private Sub Quantity_BeforeUpdate(Cancel As Integer)
If Val(Me.Quantity) > Val(Me.Stock) Or Val(Me.Stock) = 0 Then
MsgBox "Not enough stocks left."
'Me.Quantity = "" ' <-- NOT ALLOWED
Cancel = True
Me.Quantity.Undo
End If
End Sub
我正在使用 MS Access 2007 和 VBA。我有一段代码,当数量大于库存或库存为零时触发。
Private Sub Quantity_BeforeUpdate(Cancel As Integer)
If Me.Quantity > Me.Stock Or Me.Stock = 0 Then
MsgBox "Not enough stocks left."
Me.Quantity = ""
End If
End Sub
出现消息框,但随后出现错误消息:
Run-time error '2147352567 (80020009)':
The macro or function set to BeforeUpdate or ValidationRule property for this field is preventing Microsoft Office Access from saving the data in the field.
如何停止这个错误?
在 MS Access 中,您无法在 "BeforeUpdate" 事件中设置控件值。所以这一行:
Me.Quantity = ""
导致您的错误消息。所以你需要寻找一种替代方法来做你想做的事情。我认为 "AfterUpdate" 事件将满足您的需求。
控件的 Before Update 事件不允许您将其更改为任何值。此时你有 2 个选择:
- 调用
Cancel
然后调用Undo
将其值恢复为尝试更新之前的值 - 仅调用
Cancel
,保留新的(不可接受的)值,但在继续之前强制用户将其替换为可接受的值
这是第一个选项的测试示例代码。如果您更喜欢第二个选项,请丢弃 Me.Quantity.Undo
行。
Private Sub Quantity_BeforeUpdate(Cancel As Integer)
If Me.Quantity > Me.Stock Or Me.Stock = 0 Then
MsgBox "Not enough stocks left."
'Me.Quantity = "" ' <-- NOT ALLOWED
Cancel = True
Me.Quantity.Undo
End If
End Sub
当Me.Quantity
和Me.Stock
是包含数字的文本值时,情况比较复杂。如果是我,我宁愿将他们的数据类型更改为数字。但如果该更改不切实际,您可以使用 Val()
将文本值转换为实际数字以供比较。
Private Sub Quantity_BeforeUpdate(Cancel As Integer)
If Val(Me.Quantity) > Val(Me.Stock) Or Val(Me.Stock) = 0 Then
MsgBox "Not enough stocks left."
'Me.Quantity = "" ' <-- NOT ALLOWED
Cancel = True
Me.Quantity.Undo
End If
End Sub