【问题标题】:VBA connecting to local SQL ServerVBA 连接到本地 SQL Server
【发布时间】:2015-08-25 04:59:59
【问题描述】:

我的 PC 上安装了 SQL Server 2008,我正在编写 VBA 代码来填充该数据库上的表。我能够将来自各种在线资源的以下代码拼接在一起:

Sub connect()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim strConn As String
Dim strSRV As String
Dim strDB As String
Dim sql_login As String
Dim sql_pass As String

    'Create the connection string
    strSRV = ".\SQLEXPRESS"
    strDB = "backend"
    sql_login = "asd"
    sql_pass = "asd"

    strConn = "Provider=SQLNCLI10" & _
              "Server=" & strSRV & ";" & _
              "Database=" & strDB & ";" & _
              "Uid=" & sql_login & ";" & _
              "Pwd=" & sql_pass & ";"


    'Create the Connection and Recordset objects
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset

    ' Open the connection and execute
    conn.Open strConn
    Set rs = conn.Execute("SELECT * FROM *;")

    'Check we have data
    If Not rs.EOF Then
        'Transfer result
        Sheets(1).Range("A1").CopyFromRecordset rs

    'Close Recordset
    rs.Close

    Else
        MsgBox "Error: No records returned.", vbCritical
    End If

    'Clean up
    If CBool(conn.State And adStateopen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing
End Sub

目前我收到一个错误:

找不到提供者

从网上研究我发现这可能是由于 ODBC 配置,所以我去了 ODBC 数据源管理。定义了 3 个用户数据源:dBASE 文件、Excel 文件和 MS Access 数据库。我为 SQL Server Native Client 10.0 添加了第三个。

我无法在 connectionstrings.com 找到答案,这似乎是一个流行的参考。我收到错误的原因是什么?我该如何解决它?在某一时刻,我的 VBA 将指向远程服务器,因此我不希望解决方案成为本地解决方法。

【问题讨论】:

    标签: sql-server excel vba


    【解决方案1】:

    看起来你的 strConn 缺少分号...试试这个,看看有什么不同:-

     strConn = "Provider=SQLNCLI10;" & _
                  "Server=" & strSRV & ";" & _
                  "Database=" & strDB & ";" & _
                  "Uid=" & sql_login & ";" & _
                  "Pwd=" & sql_pass & ";"
    

    【讨论】:

    • 成功了!你知道一些我可以翻阅以更好地理解这一点的文档吗?例如,我不知道为什么我们使用 SQLNLCI0 而不是我遇到的其他几个。
    • 我也对连接字符串感到困惑。您只需要继续研究 - 如果您遇到困难,您可以随时提出更多关于 SO 的问题!很高兴它对你有用。
    • @newdimension SQLNCLI10 是随 SQL Server 一起安装的 OLE 提供程序。我通常避免在 VBA 中使用它,因为它必须单独安装。 SQLOLEDB 随 Windows 一起提供,它似乎也可以正常工作,但字符串其余部分的格式不同。 connectionstrings.com/…
    • 您也应该使用 Provider=SQLOLEDB.1 而不是 SQLOLEDB,如该链接中所建议的那样。我想我在不包括 .1(显然使用旧版本的驱动程序)时遇到了参数化查询的一些问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多