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

Michi :
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?

CLR :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194413&siteId=1