ADODB Connection.Open 上的 VBA 错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5389634/
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-08 11:16:00  来源:igfitidea点击:

VBA Error handling on ADODB Connection.Open

vbaadodb

提问by PKeno

I have an ADODB connection in VBA for connecting to an SQLServer database. I want to catch the error that is raised when connection.Open is called and the given database is unreachable.

我在 VBA 中有一个 ADODB 连接,用于连接到 SQLServer 数据库。我想捕获在调用 connection.Open 并且无法访问给定数据库时引发的错误。

My code looks like this:

我的代码如下所示:

Public Function Connect() As Boolean

On Error GoTo DBError

    Dim dbServer As String
    Dim dbName As String
    Dim dbUser As String
    Dim dbPwd As String

    dbServer = DatabaseSettings.dbServer
    dbName = DatabaseSettings.dbName
    dbUser = DatabaseSettings.dbUser
    dbPwd = DatabaseSettings.dbPwd

    Dim connectionString As String
    connectionString = "Server=" & dbServer & ";Database=" & dbName & ";User Id=" & dbUser & ";Password=" & dbPwd

    Set conn = New ADODB.Connection
    conn.Provider = "sqloledb"
    With conn
        .ConnectionTimeout = 2
        .CursorLocation = adUseClient
        .Open connectionString
        .CommandTimeout = 0
    End With

Connect = True
Exit Function

DBError:
    Connect = False
End Function

My problem is that when i try to run this code with an incorrect connectionString an error is raised and shown in a MsgBox and not caught by the "On Error GoTo DBError".

我的问题是,当我尝试使用不正确的 connectionString 运行此代码时,会引发错误并显示在 MsgBox 中,而不会被“On Error GoTo DBError”捕获。

Is there something wrong in my error handling code or do i need to find another way of catching this error?

我的错误处理代码是否有问题,或者我是否需要找到另一种捕获此错误的方法?

Thank you for your help. Any suggestions are welcome.

感谢您的帮助。欢迎任何建议。

回答by tpascale

Not sure if this is it, but in the VBE window make sure the Tools...Options...General...Error Trapping option is set to "Break on Unhandled Errors". If it were set to "Break on All Errors" this may bypass your handlers.

不确定是否是这样,但在 VBE 窗口中确保工具...选项...常规...错误捕获选项设置为“中断未处理的错误”。如果它被设置为“Break on All Errors”,这可能会绕过你的处理程序。

回答by Tiago Cardoso

Try to use the below, worked here:

尝试使用以下内容,在这里工作:

With conn
    .ConnectionTimeout = 2
    .CursorLocation = adUseClient
    .ConnectionString = connectionString
    .Open 
    .CommandTimeout = 0
End With