VBA 使用 ADO 连接到 SQL 服务器(Windows 已验证)

VBA connect with ADO to SQL Server (Windows authenticated)

我在尝试使用 Windows 身份验证通过 VBA 连接到 SQL 服务器时收到运行时错误 3709。

问题出现在这一行:

.ActiveConnection = conn

这里是用于连接的完整代码:

Dim strConn As String
Dim wsReport As Worksheet
Dim col As Integer

strConn = "Provider=SQLOLEDB;"
strConn = strConn & "Server=" & Server_Name & ";"
strConn = strConn & "Database=" & Database_Name & ";"
strConn = strConn & "Trusted_Connection=yes;"
strConn = strConn & "Integrated Security=True;"

Set conn = New ADODB.Connection

With conn
    .ConnectionString = strConn
    .CursorLocation = adUseClient
End With

Set rst = New ADODB.Recordset

With rst

    .ActiveConnection = conn
    .Open Source:=SQL_Statement
End With

Set wsReport = ThisWorkbook.Worksheets.Add

With wsReport
    For col = 0 To rst.Fields.Count - 1
        .Cells(1, col + 1) = rst.Fields(col).Name
    
    Next col
End With

或者 ADO 现在已经过时了吗?

解决方案是“Provider=MSOLEDBSQL;Server=XX;Database=XXXX;Trusted_Connection=yes;”

这个网站根据具体情况给出了所有不同的组合,显示了与 SQL-服务器连接的复杂性:

https://www.connectionstrings.com/ole-db-driver-for-sql-server/