2011-04-15 120 views
3

你好下面是我的代碼,我不能夠從我的SQL服務器, 其投擲誤差數據從SQL Server獲取在VBA

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 

謝謝

謝謝你的工作.... :)

+0

您好!如果你發現如何使它工作,你能接受幫助你的答案嗎? :)您可以通過點擊答案旁邊的複選標記來接受答案。 – hammythepig 2017-02-06 22:47:21

回答

4

缺少的 「設置」 ...

' Assign the Connection object. 
Set .ActiveConnection = SQLConn 
4

我正在寫這個查詢,當你想建立一個Excel之間的連接&使用OLEDBConnecion的VBA中的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 

謝謝!