vba 关闭打开的记录集会产生运行时错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15966738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:34:35  来源:igfitidea点击:

Closing an open recordset produces a run-time error

vbaexcel-vbadatabase-connectionexcel

提问by Excel Developers

I have an ADO recordset variable that is declared in the class module of a userform. The recordset is opened in the form's Activate event, and I am trying to close it in the form's Terminate event with code like this:

我有一个在用户窗体的类模块中声明的 ADO 记录集变量。记录集在表单的 Activate 事件中打开,我试图在表单的 Terminate 事件中使用如下代码关闭它:

Private Sub UserForm_Terminate()

If VersionIsReleased Then
    ThisWorkbook.Parent.Quit
Else

    If Not m_rs Is Nothing Then

        If m_rs.State = adStateOpen Then
            m_rs.Close
        End If

        Set m_rs = Nothing
    End If

    Close_CN g_cn
    ThisWorkbook.Application.Visible = True
End If

End Sub

The line m_rs.Closeproduces a run-time error: "Operation is not allowed in this context.". Any ideas why this happens?

该行m_rs.Close产生一个运行时错误:“在此上下文中不允许操作。”。任何想法为什么会发生这种情况?

回答by Dick Kusleika

That error can occur if the recordset is being edited when you try to close it. Make sure that if you use AddNewor change any Fields().Valuethat you use Updateto save the edits before closing. You can inspect the EditModeproperty to see what state the recordset is in.

如果在您尝试关闭记录集时正在编辑它,则可能会发生该错误。确保如果你使用AddNew或更改任何Fields().Value您使用Update关闭之前保存的编辑。您可以检查该EditMode属性以查看记录集处于什么状态。