VBA,Excel ODBC驱动程序 - 使用带有来自单元格的参数的sql查询时键入不匹配错误

时间:2015-02-25 14:44:51

标签: sql excel vba excel-vba ado

我在使用excels cell获取参数时选择Type Mismatch error时遇到问题。我像数据库一样使用excel。 我的代码是:

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

问题在于从RPJ = ('" & Range("U12") & "') "子句中获取参数:WHERE

1 个答案:

答案 0 :(得分:0)

您可能遭受了太多的复制和粘贴。看起来你在数学计算中使用它时,在刻度线中包含`Range(" U17")值。

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

我还删除了实际文本WHERE条件中的一些包围。只有在使用多个文本值时才需要它们,

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