【问题标题】:MS Access VBA concatenate variables dynamically in SQLMS Access VBA 在 SQL 中动态连接变量
【发布时间】:2015-11-27 07:25:02
【问题描述】:

我有一个包含 7 个复选框的表单,每个复选框都是一个状态:打开、关闭、拒绝、推迟、工作、复制和测试

复选框的值可以是True或False。

现在我想在 VBA 的 SQL 语句中连接复选框的值:

Dim Status As String
If (Open.value = True) Then Status = " status = 'Open'" End If
If (Postponed.value = True) Then Status = " or status = 'Postponed'" End If
If (Closed.value = True) Then Status = " or status = 'Closed'" End If
If (Rejected.value = True) Then Status = " or status = 'Rejected'" End If
If (Working.value = True) Then Status = " or status = 'Working'" End If
If (Duplicated.value = True) Then Status = " or status = 'Duplicated'" End If
If (Testing.value = True) Then Status = " or status = 'Testing'" End If
sqlstatement = "select * from cr where " & status

上面代码的问题是它有点硬编码。这意味着如果 open.value 不正确,那么整个语句都是错误的。那么如何使其动态地仅在 where 中组合标准(可以选择或取消选择任何复选框)?

【问题讨论】:

    标签: ms-access vba ms-access-2010


    【解决方案1】:

    改编自此答案的第二部分:https://stackoverflow.com/a/33630318/3820271

    Status = ""
    If (Open.value = True) Then Status = Status & " OR status = 'Open'" 
    If (Postponed.value = True) Then Status = Status & " OR status = 'Postponed'"
    If (Closed.value = True) Then Status = Status & " OR status = 'Closed'"
    ' ...
    sqlstatement = "select * from cr where 1=0 " & status
    

    它是如何工作的?

    每个标准都添加了OR。该语句的默认 WHERE 子句为 False。如果没有选中复选框,则不会返回任何记录(我假设这是您想要的)。

    注意:如果您在一行中有If ... Then ...,则不得使用End If。您的代码无法编译。

    【讨论】:

    • 谢谢,我接受了你的回答,因为它是一个更简单的解决方案。
    【解决方案2】:

    由于您在复选框和字段之间匹配了名称,并且假设没有其他复选框:

    Dim status As String
    Dim ctl As Control
    status = ""
    For Each ctl In Me.Controls
        If ctl.ControlType = acCheckBox Then
            status = status & " or status = '" & ctl.Name & "'"
        End If
    Next
    if not status = "" then
        sqlstatement = "select * from cr where " & Mid(status, 5)
    End if
    

    【讨论】:

    • 谢谢,我在同一页面上有更多复选框,所以我想知道这是否适用于场景。
    • 如果您有其他不想包含的复选框,那么您可以尝试将标签添加到您想要的复选框中,并使用控件类型的检查添加对该标签的检查。
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多