VBA - 创建一个基于条件的 SQL 查询

VBA - create a condition based SQL query

我是 VBA 的新手,我想找到一种更简单的方法来创建 SQL 查询。 我有 4 个组合框,查询取决于它们是否已填充。组合框之一链接到具有多个复选框的用户表单,这些复选框将添加到查询中。

这是我目前的代码,我想增加用户表单条件:

If Sheets("Home Page").opecbbx.Value <> "" And Sheets("Home Page").wellchk.Value = False Then 'contractor only
        op = Sheets("Home Page").opecbbx.Value

                If Sheets("Home Page").sizcbbx.Value <> "" Then 'contractor and size
                    'Create SQL statement for filtering.
                    siz = Sheets("Home Page").sizcbbx.Value
                    SQL = "SELECT * FROM Filter Where contractor Like '%" & op & "%' And size_sec Like '%" & siz & "%';"

                Else

                    SQL = "SELECT * FROM Filter Where contractor Like '%" & op & "%';"

                End If

    ElseIf Sheets("Home Page").wellchk.Value = True And Sheets("Home Page").opecbbx.Value <> "" Then 'contractor and well
    op = Sheets("Home Page").opecbbx.Value

                If Sheets("Home Page").sizcbbx.Value <> "" Then 'contractor, size and well

                            siz = Sheets("Home Page").sizcbbx.Value
                            SQL = "SELECT * FROM Filter Where contractor Like '%" & op & "%' And size_sec Like '%" & siz & "%' And ID_NOC = '" & well & "';"

                Else

                    SQL = "SELECT * FROM Filter Where contractor Like '%" & op & "%' and ID_NOC='" & well & "';"

                End If

    ElseIf Sheets("Home Page").wellchk.Value = True Then

                If Sheets("Home Page").sizcbbx.Value <> "" Then 'size and well

                    siz = Sheets("Home Page").sizcbbx.Value
                    SQL = "SELECT * FROM Filter Where size_sec Like '%" & siz & "%' And ID_NOC = '" & well & "';"

                Else

                     SQL = "SELECT * FROM Filter Where ID_NOC='" & well & "';"

                End If

    ElseIf Sheets("Home Page").sizcbbx.Value <> "" And Sheets("Home Page").wellchk.Value = False And Sheets("Home Page").opecbbx.Value = "" Then 'size only

                siz = Sheets("Home Page").sizcbbx.Value
                SQL = "SELECT * FROM Filter Where size_sec Like '%" & siz & "%';"

    'Formation only
    ElseIf Sheets("Home Page").wellchk.Value = False And Sheets("Home Page").opecbbx.Value = "" And Sheets("Home Page").sizcbbx.Value = "" Then

                SQL = "SELECT * FROM Filter"

    End If

如何在不添加大量新条件的情况下做到这一点?

谢谢

我可以在这里给出一个一般的答案,可能需要一些按摩才能在 VBA 中工作。您可以像这样使用灵活的准备语句:

SELECT *
FROM Filter
WHERE
    (contractor LIKE ? OR contractor IS NULL) AND
    (size_sec LIKE ? OR size_sec IS NULL) AND
    (ID_NOC = ? OR ID_NOC IS NULL);

对于每个占位符 ?,您可以绑定来自组合框的值(如果已定义),或者只绑定 NULL 否则。例如,对于 contractor 占位符,如果已定义,您将绑定 op,否则绑定 NULL。这种方法的工作方式是,如果给定的标准是 NULL,那么它就会被忽略。因此,如果您只有组合框中可用的三个值之一,那么只有它会用于在 WHERE 子句中进行过滤。