在 VBA 中设置与访问数据库的连接会崩溃 excel

Setting a connection to an access database in VBA crashes excel

这是我用来从 excel 打开到访问数据库的连接的代码。曾经用了一年多。

Set dbname = New ADODB.Connection
theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open theconnection
End With

通过试错,我得出的结论是这条线导致了问题。

Set dbname= New ADODB.Connection

我的电脑自动更新后出现问题 我的 Excel 版本 2016 MSO (16.0.7726.1036) 32 位

如果您 运行 也遇到这个问题,请告诉我,如果您知道任何修复或解决方法。

可能

Dim dbname As Object
Set dbname = CreateObject("ADODB.Connection")

theconnection = "//xxx.sharepoint.com/sites" & Application.PathSeparator & TARGET_DB
With dbname
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .Open theconnection
End With

我是这样用的,所有代码

Dim Rs As Object
Dim strConn As String
Dim i As Integer
Dim strSQL As String

strSQL = "select * from [table] "
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=" & ThisWorkbook.FullName & ";" & _
        "Extended Properties=Excel 12.0;"


Set Rs = CreateObject("ADODB.Recordset")
Rs.Open strSQL, strConn

If Not Rs.EOF Then
     With Ws
        .Range("a1").CurrentRegion.ClearContents
        For i = 0 To Rs.Fields.Count - 1
           .Cells(1, i + 1).Value = Rs.Fields(i).Name
        Next
        .Range("a" & 2).CopyFromRecordset Rs
    End With
End If
Rs.Close
Set Rs = Nothing
  • 尝试取消选中您的 'ActiveX Data Objects' 引用并将它们添加回去:

工具 - 参考资料

  • 使用对象定义数据库:

     Dim dbname As Object
     Set dbname = CreateObject("ADODB.Connection")
    

如果您像这样创建连接变量:

Dim con as New ADODB.Connection

改为:

Dim con as ADODB.Connection
Set con = New ADODB.Connection