在VBA中从SQL Server提取数据

| 您好,下面是我的代码,我无法从SQL服务器中获取数据,  其投掷错误为
Compiler error :  object required.
连接没有问题,连接成功。 请更正我的代码,帮我解决这个问题
Private Sub CommandButton1_Click()
Set SQLConn = CreateObject(\"ADODB.Connection\")

SQLConn.Open \"provider =sqloledb; Data Source = xxxx; Initial Catalog = jjjj; User Id = yyyy; Password = zzzz\"

       MsgBox \"Connection Succesful\"

Set SQLData = CreateObject(\"ADODB.Recordset\")
With SQLData

    \' Assign the Connection object.
    .ActiveConnection = SQLConn

    \' Extract the required records.
    .Open \"select invoice_num, invoice_date, invoice_amount from im_invoice where billing_account = \'HS0076A\' and invoice_date =\'01-apr-2011\'\"

    \' Copy the records into cell A1 on Sheet1.
    Sheet1.Range(\"A1\").CopyFromRecordset SQLData

    \' Tidy up
     .Close

End With

SQLConn.Close
Set SQLData = Nothing
Set SQLConn = Nothing

End Sub
谢谢 谢谢你的工作.... :)     
已邀请:
缺少“设置” ...
\' Assign the Connection object. 
Set .ActiveConnection = SQLConn 
    
当您要使用OLEDBConnecion在VBA中的Excel和SQL Server之间建立连接时,我正在编写此查询。是的,它用于Windows身份验证。解决方案在下面提到。您需要添加\'Microsoft.ActiveX对象库2.8 \'。
Sub GetDataFromADO()

    \'Declare variables\'
        Set objMyconn = New ADODB.Connection
        Set objMyCmd = New ADODB.Command
        Set objMyRecordset = New ADODB.Recordset
        Dim rc As Long

    \'Open Connection\'
        objMyconn.ConnectionString = \"Provider=SQLOLEDB;Data Source=SAXAM\\SQLEXPRESS;Initial Catalog=AdventureWorks2012; Integrated Security=SSPI;\"

        objMyconn.Open

    \'Set and Excecute SQL Command\'
        Set objMyCmd.ActiveConnection = objMyconn
        objMyCmd.CommandText = \"select * from [Person].[BusinessEntity] \"
        objMyCmd.CommandType = adCmdText
        objMyCmd.Execute

    \'Open Recordset\'
        Set objMyRecordset.ActiveConnection = objMyconn
        objMyRecordset.Open objMyCmd

    \'Copy Data to Excel\'
        \'ActiveSheet.Range(\"A1\").CopyFromRecordset (objMyRecordset)
        Application.ActiveCell.CopyFromRecordset (objMyRecordset)
        rc = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
        ActiveSheet.Cells(rc + 1, 1).Select
        \'Worksheets(\"Sheet1\").Cells(Rows.Count, 1).End(xlUp).Value
        objMyconn.Close

End Sub
谢谢!     

要回复问题请先登录注册