将表单过滤器转换为Where子句

时间:2016-09-26 11:35:33

标签: access-vba

尝试将me.filter的内容追加到查询的末尾。

在参数子句'中获取'语法错误然而,当我获取?qdf.sql的结果并将它们放在常规查询中时,它可以工作。

PARAMETERS par_car_id Long; SELECT tool_tran.car_id,tool_tran.d008g,tool_tran.d046d INTO tmp_tbl_tool_export FROM tool_tran;

On Error GoTo ErrTrap

Dim dbs As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Dim strNewWHERE As String
Dim strSQL As String
Dim i As Integer

If fnTableExists("tmp_tbl_tool_export") = True Then
    DoCmd.DeleteObject acTable, "tmp_tbl_tool_export"
Else
End If

Set dbs = CurrentDb

Set qdf = dbs.QueryDefs("qry_tmp_tbl_tool_export")

If Me.Filter <> "" Then
    strNewWHERE = " WHERE ((tool_tran.car_id)=[forms]![frm_select_car_universal]![txt_car_id]) AND " & Me.Filter
    strNewWHERE = Replace(strNewWHERE, "[", "")
    strNewWHERE = Replace(strNewWHERE, "]", "")
    strNewWHERE = Replace(strNewWHERE, "qry_tool_tran_expanded", "tool_tran")
Else
End If

'looks to append converted filter to end of query def

If strNewWHERE <> "" Then
    qdf.sql = Left(qdf.sql, InStr(qdf.sql, ";") - 1) & strNewWHERE & ";"
Else
    qdf.sql = Left(qdf.sql, InStr(qdf.sql, ";") - 1)
End If

qdf.Parameters("par_car_id") = [Forms]![frm_select_car_universal]![txt_car_id]

qdf.Execute
qdf.Close

Set qdf = Nothing
Set dbs = Nothing

1 个答案:

答案 0 :(得分:1)

VBA 运行的

SQL 不知道打开的表单,因此您必须从表单中包含值本身:

strNewWHERE = " WHERE ((tool_tran.car_id)=" & [forms]![frm_select_car_universal]![txt_car_id].Value & ") AND " & Me.Filter