使用VBA将数据从SQL Server移至Excel的并发症

问题描述 投票:0回答:1

我正在尝试将数据从SQL Server提取到Excel中,以填充先前存在的工作表,因此我为此编写了一个测试代码。虽然这不是很完美,但是我主要测试的是建立与服务器的连接,但是当我打开连接时遇到了自动化错误Error 440。我在那部分代码中做错了什么。

到目前为止,我还没有进行任何修改,请检查以确保编译正确。

Sub GetPhysicalCount()
    Dim squery As String
    Dim cnLogs As New ADODB.Connection
    Dim rsData As New ADODB.Recordset
    Dim rsHeaders As New ADODB.Recordset
    Dim x As Long
    Dim y As Long
    Dim dbpath As String
    Dim dbname As String
    Dim AppExcel As Excel.Application
    Dim Workbook As Object
    Dim Worksheet As Object
    Dim strConn As String
    Dim Count As Long


    pUser = "AllenBroady"
    pPsw = "Cthulu90"
    pServer = "IMCPU_TEST"
    pCatalog = "MasterMFG"




    strConn = "Provider = SQLOLEDB;"
    strConn = strConn & "Initial Catalog= & pCatalog; & Data Source= & pServer;"
    strConn = strConn & "Integrated Security=sspi;& User ID= & pUser; & Password= & pPsw;"

    cnLogs.Open strConn

        With rsHeaders

            .ActiveConnection = cnLogs

                    .Open "SELECT * FROM MasterMFG WHERE Dept_Code = 001"

                 Do While Not rsHeaders.EOF

                    Cells(1, l_counter + 1) = rsHeaders(0)

                    l_counter = l_counter + 1

                    rsHeaders.MoveNext

                  Loop

            .Close

            End With

            With rsCount
                  .ActiveConnection = cnLogs
                    .Open "SELECT COUNT(Dept_Code)FROM MasterMFG WHERE Total <> 0"
                      Count = rsCount
                  .Close
            End With



            With rsData

            .ActiveConnection = cnLogs
                .Open "SELECT  Dept_Code, Total FROM MasterMFG WHERE Total <> 0"


               For i = 1 To Count

                    Sheet1.Range("A" & i + 1) = rsData.Fields(i)
                    rsData.MoveNext
                    Sheet1.Range("B" & i + 1) = rsData.Fields(i)
               Next i

            .Close

            End With

        cnLogs.Close

        Set cnLogs = Nothing

        Set rsHeaders = Nothing

        Set rsData = Nothing

    Sheets(1).UsedRange.EntireColumn.AutoFit

End Sub

我一直收到“自动化”错误(错误440)

sql excel vba sql-server-2017
1个回答
0
投票

您的strConn = strConn字符串未正确连接。

您的变量不求值,它们的名称直接放在字符串中。

例如,更改

 strConn = strConn & "Initial Catalog= & pCatalog; & Data Source= & pServer;"
 strConn = strConn & "Integrated Security=sspi;& UserID= & pUser; & Password= & pPsw;"

to

 strConn = strConn & "Initial Catalog=" & pCatalog & ";Data Source=" & pServer & ";"
 strConn = strConn & "Integrated Security=sspi;User ID= "& pUser; & "Password= " & pPsw & ";"
© www.soinside.com 2019 - 2024. All rights reserved.