0

What I'm trying to do is use a pull information from SQL server into an excel spreadsheet using a query with parameters.

I've been able to query the database from excel but have not been able to figure out how to add parameters.

I need the parameter to be taken from a cell in the sheet.

Sub DataExtract()

Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
Dim strConn As String
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE= MyServer ;INITIAL CATALOG = MyDatabase ;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"
cnPubs.Open strConn
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs

.ActiveConnection = cnPubs

.Open "SELECT * FROM [MyTable] WHERE ColA = ?"

Sheet1.Range("B12").CopyFromRecordset rsPubs

.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub

any help on how I could simply have the question mark in the query reference a cell in the sheet would be greatly appreciated. Thanks

1 Answer 1

1

Untested:

Sub DataExtract()

Dim cmd as ADODB.Command, param as Object, val
Dim cnPubs As ADODB.Connection
Dim rsPubs As ADODB.Recordset
Dim strConn As String

    Set cnPubs = New ADODB.Connection

    strConn = "PROVIDER=SQLOLEDB;"
    strConn = strConn & "DATA SOURCE= MyServer ;INITIAL CATALOG = MyDatabase ;"
    strConn = strConn & " INTEGRATED SECURITY=sspi;"
    cnPubs.Open strConn

    Set cmd = New ADODB.Command
    cmd.CommandText = "SELECT * FROM [MyTable] WHERE ColA = ?"
    cmd.CommandType = adCmdText


    val = Sheet1.Range("A1").Value 'query value to be used
    'create and add the parameter
    Set param = cmd.CreateParameter("", adVariant, adParamInput, 0, val)
    cmd.parameters.Append param

    Set cmd.ActiveConnection = cnPubs

    Set rsPubs = cmd.Execute()

    Sheet1.Range("B12").CopyFromRecordset rsPubs

End Sub
Sign up to request clarification or add additional context in comments.

4 Comments

I use that successfully with Oracle (not an Access user) - not familiar with SQL server. I do see plenty of examples using ? with SQL Server though.
yeah, I guess the ADO driver figures it out. The naming comes in if you want to define your parameters in any order. I'm surprised you haven't used Access though
@Brad - I wouldn't say I've "never" used Access, but we're more of an Oracle shop here.
Works perfectly! I realise how simple a question it is but i just could not wrap my head around it until now. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.