开发者

Data fetching from SQL Server in VBA

Hi Below is my code, i am not able to fetch the data from my SQL server, its throwing error as

Compiler error :  object required.

There is no problem with the connection, connection is sucessful.

please correct my code, help me with this thing

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 S开发者_开发百科QLConn = Nothing

End Sub

Thank you

thank you its working .... :)


Missing "Set"...

' Assign the Connection object. 
Set .ActiveConnection = SQLConn 


I am writing this query when you want to establish a connection between Excel & SQL Server in VBA using OLEDBConnecion. And yes it's for Windows authentication. Solution is mentioned below. You need to add 'Microsoft.ActiveX Object Library 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

Thanks!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜