ms-access - VBA连接到 protected 数据库,错误处理

标签 ms-access error-handling vba runtime-error

我正在做一个包含两个字段的表单,一个可以浏览数据库的路径,另一个可以浏览数据库的密码。

设置正确的密码和数据库文件的路径后,一切正常。

我的问题是,如果我没有正确的密码或文件不是数据库,则错误停止程序。我无法在不崩溃的情况下测试连接。

如何在不使整个系统崩溃的情况下测试路径和密码。这是我到目前为止所做的事情(非常简单):

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim canConnect As Boolean

Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Jet OLEDB:Database Password=" & Me.txt2   & ";   Data Source=" & Me.txt1 & ";"
Set rs = New ADODB.Recordset

If cn.State = adStateOpen Then
  canConnect = True
  cn.Close
End If

MsgBox canConnect

如您所见,txt1和txt2是我的两个文本区域,就像我说的那样,在消息框提示之前,所有内容都崩溃了。

最佳答案

我认为您可能需要做的就是添加一个错误处理程序。我删除了ADODB.Recordset,因为您只需要.Connection

Public Sub test17()
    Dim cn As ADODB.Connection
    Dim canConnect As Boolean
    Dim strConnect As String
    Dim strMsg As String

On Error GoTo ErrorHandler

    canConnect = False ' make it explicit, but not really needed
    Set cn = New ADODB.Connection
    strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Jet OLEDB:Database Password=" & Me.txt2 & _
        ";Data Source=" & Me.txt1 & ";"
    Debug.Print strConnect
    cn.Open strConnect

    ' if we got to this point, there was no error ...
    ' which means the connection succeeded
    canConnect = True
    cn.Close

ExitHere:
    MsgBox canConnect
    Set cn = Nothing
    Exit Sub

ErrorHandler:
    strMsg = "Error " & Err.Number & " (" & Err.Description _
        & ") in procedure test17"
    'MsgBox strMsg or Debug.Print strMsg, if desired
    GoTo ExitHere
End Sub

关于ms-access - VBA连接到 protected 数据库,错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18858881/

相关文章:

python - 通过 Excel VBA 运行 Python 脚本

database - 检索 Access 数据库中的索引列表

sql - 是否可以监视和记录针对 Access MDB 进行的实际查询?

ms-access - 打开事件表单的VBA代码

java - 打印ABC…的问题以及Java中的数字

error-handling - Makefile中的自定义错误处理

c# - 如何在我的 C# 程序中断开 Access ?

c++ - C++中程序显示的意外输出

vba - 为什么 .Font.Reset 在查找/替换 VBA 宏中不起作用?

excel - 使用 VBA 动态隐藏行