Michi
Michi

Reputation: 5471

Use value in Excel cell as condition for WHERE clause in SQL query

Sub Get_Data()

Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim dateVar As Date

    Set conn = New ADODB.Connection
    conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost; DATABASE=bi; UID=username; PWD=password; OPTION=3"
    conn.Open

                strSQL = " SELECT " & _
                            " Products " & _
                            " FROM Logistics " & _
                            " WHERE DATE(insert_timestamp) = ""2020-02-24"" " & _
                            " GROUP BY 1"

    Set rs = New ADODB.Recordset
    rs.Open strSQL, conn, adOpenStatic

    Sheet5.Range("A1").CopyFromRecordset rs

    rs.Close
    conn.Close

End Sub

I run the above VBA to extract values fom the database.
It works exactly how I need it.


Now, instead of having a pre-defined date within strSQL I want to use the data that is entered into Cell B1 in my Excel spreadsheet. Therefore, I changed the strSQL part in the VBA to:

        strSQL = " SELECT " & _
                    " Products " & _
                    " FROM Logistics " & _
                    " WHERE DATE(insert_timestamp) = " & Sheet1.Range("B1") & " " & _
                    " GROUP BY 1"

However, now I get runtime error -2147217887 (80040e21) on rs.Open strSQL, conn, adOpenStatic.

What do I need to change in my VBA to make it work?

Upvotes: 0

Views: 1022

Answers (2)

Parfait
Parfait

Reputation: 107577

Consider the industry best practice of SQL parameterization using the ADO Command object which can properly handle data types without string concatenation or various formatting:

Dim conn As ADODB.Connection      ' REMOVE New INITIALIZATION IN Dim LINES
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim dateVar As Date

Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 5.1 Driver}; ..."
conn.Open

' STRING STATEMENT WITH QMARK PLACEHOLDER
strSQL = " SELECT " & _
             "   Products " & _
             " FROM Logistics " & _
             " WHERE DATE(insert_timestamp) = ?" & _
             " GROUP BY Products"

' CONVERT CELL TO DATE TYPE (IF CELL FORMATTED AS STRING)
dateVar = CDate(Sheet1.Range("B1").Value)

Set cmd = New ADODB.Command

With cmd
   .ActiveConnection = conn
   .CommandText = strSQL
   .CommandType = adCmdText

   ' BIND PARAMS TO QMARK POSITIONAL PLACEHOLDER
   .Parameters.Append .CreateParameter("mydate", adDate, adParamInput, , dateVar)

   ' PASS RESULT TO RECORDSET
   Set rs = .Execute
End With

Sheet5.Range("A1").CopyFromRecordset rs

Upvotes: 3

CLR
CLR

Reputation: 12279

Try:

strSQL =    " SELECT " & _
            " Products " & _
            " FROM Logistics " & _
            " WHERE DATE(insert_timestamp) = '" & Format(Sheet1.Range("B1").Value, "YYYY-MM-DD") & "' " & _
            " GROUP BY 1"

Just be aware, if insert_timestamp does indeed contain a time other than midnight, you might not get the results you're after without converting to just a date or altering your SQL.

Upvotes: 1

Related Questions