使用:Access 2013与ADO连接到SQL Server后端数据库
我的Access数据库中的表单在运行时动态绑定到SQL Server的SELECT存储过程的结果,并允许用户对记录进行更改。
它有2个按钮:保存和取消。
它显示为弹出式,模态,对话框形式,右上角有一个(Windows)关闭按钮。
我已经使用VBA代码询问用户是否要保存,忽略或取消关闭操作。
但是有问题,如果单击取消,则会出现上述错误。还有其他问题,例如,在错误发生一次之后,然后任何进一步的命令(保存或取消或关闭表单)都不起作用 - 我认为这是因为VBA解释器由于先前的错误而停止。另一个复杂因素是 - 我现在需要从Windows任务管理器结束MS-Access进程,执行此操作然后重新启动数据库,然后打开此表单将出错并且表单将不会加载。当在设计模式下打开表单时,我可以看到表单的连接字符串保存在Form的Record Source属性中(这有时只发生),看起来像这样:
{? = call dbo.tbBeneficiary_S(?)}。
这是我的代码:
Dim CancelCloseFlag As Boolean
Dim SavePrompt As Boolean
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim a As Integer
If SavePrompt Then
a = MsgBox("Do you want to save changes?", vbQuestion + vbYesNoCancel, "Changes made")
Select Case a
Case vbNo:
Me.Undo
CancelCloseFlag = False
Case vbYes:
'do nothing; it will save the changes
CancelCloseFlag = False
Case vbCancel:
Cancel = True
CancelCloseFlag = True
End Select
End If
End Sub
Private Sub Form_Dirty(Cancel As Integer)
SavePrompt = True
End Sub
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
End If
End Sub
Private Sub Form_Load()
LoadBeneficiaryDetails
End Sub
Private Sub Form_Unload(Cancel As Integer)
If CancelCloseFlag Then
Cancel = True
End If
End Sub
Private Sub btCancel_Click()
If Me.Dirty Then
SavePrompt = True
End If
DoCmd.Close
End Sub
Private Sub btSave_Click()
SavePrompt = False
DoCmd.Close
End Sub
我被困住了,想知道其他人如何解决这个问题?基本上我想在用户尝试使用“取消”按钮或(Windows)关闭按钮关闭表单时为用户提供“保存”,“忽略”,“取消”选项。如果用户选择取消,那么它应该只返回到表单而不更改或撤消对数据的任何更改。解决方案可能很简单,但它避免了我过度劳累的思想。
提前致谢!
答案 0 :(得分:1)
请尝试以下代码 - 我针对所有六种情况进行了测试,并采取了适当的措施。
Option Compare Database
Option Explicit
Dim blnAction As Integer
Dim blnBeenThereDoneThat As Boolean
Private Sub Form_BeforeUpdate(Cancel As Integer)
If blnBeenThereDoneThat = True Then Exit Sub
blnBeenThereDoneThat = True
blnAction = MsgBox("Do you want to save changes?", vbQuestion + vbYesNoCancel, "Changes made")
Select Case blnAction
Case vbNo:
Me.Undo
Case vbYes:
'do nothing; it will save the changes
Case vbCancel:
Cancel = True
End Select
End Sub
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 2169 Then
Response = acDataErrContinue
End If
End Sub
Private Sub Form_Load()
LoadBeneficiaryDetails
End Sub
Private Sub Form_Unload(Cancel As Integer)
If blnAction = vbCancel Then
blnBeenThereDoneThat = False
Cancel = True
End If
End Sub
Private Sub btCancel_Click()
If Me.Dirty Then
Form_BeforeUpdate (0)
End If
If blnAction = vbCancel Then
blnBeenThereDoneThat = False
Exit Sub
ElseIf blnAction = vbYes Then
DoCmd.Close
Else
DoCmd.Close
End If
End Sub
Private Sub btSave_Click()
If Me.Dirty Then
Form_BeforeUpdate (0)
End If
If blnAction = vbCancel Then
Exit Sub
Else
DoCmd.Close
End If
End Sub