VBA 用 ADO 连接到 SQL Server(Windows 身份验证)

时间:2021-06-16 16:03:33

标签: sql sql-server windows-authentication ado

当我尝试使用 Windows 身份验证通过 VBA 连接到 SQL Server 时收到运行时错误 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 现在已经过时了吗?

1 个答案:

答案 0 :(得分:0)

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

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

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