简体   繁体   中英

VBA, Excel ODBC driver - Type Mismatch error while using sql query with parameter from cell

I have problem with Type Mismatch error while I do a select with getting parameter from excels cell. I am using excel like a database. My code is:

Sub maxlg()

    Dim sSQLQry As String
    Dim ReturnArray

    Dim Conn As New ADODB.Connection
    Dim mrs As New ADODB.Recordset

    Dim DBPath As String, sconnect As String



    DBPath = ThisWorkbook.FullName

    sconnect = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

    Conn.Open sconnect
        sSQLSting = "SELECT SUM(Sicherkoef*LG/KFM/'" & Range("U17") & "') AS MAXLG From [DATABASE$] WHERE Platzierung =('" & Range("S11") & "') AND RPJ = ('" & Range("U12") & "') "        
        mrs.Open sSQLSting, Conn
            '=>Load the Data into an array
            'ReturnArray = mrs.GetRows
                    ''OR''
            '=>Paste the data into a sheet
            ActiveSheet.Range("V12").CopyFromRecordset mrs
            'Close Recordset
        mrs.Close


    Conn.Close

End Sub

Problem is in getting parameter from here: RPJ = ('" & Range("U12") & "') " in the WHERE clause.

You may have suffered from a little too much copy and paste. It seems that you are wrapping the `Range("U17") value in ticks while using it within a mathematical calculation.

sSQLSting = "SELECT SUM(Sicherkoef*LG/KFM/" & Range("U17").value & ") AS MAXLG From [DATABASE$] WHERE Platzierung ='" & Range("S11").value & "' AND RPJ = '" & Range("U12").value & "';" 

I've also removed some bracketing in the actual text WHERE conditions. They are really only necessary when multiple text values are used with,

 ... WHERE [fld1] IN ('abc', 'def')

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