MS Access VBA 在 SQL 中动态连接变量

MS Access VBA concatenate variables dynamically in SQL

我有一个包含 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 不正确,那么整个陈述都是错误的。那么如何使它动态地 assemble 只有 where 中的标准(可以选择或取消选择任何复选框)?

改编自此答案的第二部分:

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。您的代码无法编译。

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

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