简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM