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

时间:2020-03-06 15:46:28

标签: sql excel vba multiple-conditions

我对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

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

谢谢

1 个答案:

答案 0 :(得分:0)

我可以在这里给出一个一般性的答案,这可能需要一些按摩才能在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子句中的过滤。