MS查询与各种多个值参数

我有以下问题:

我在Excel中有5个多select列表框。 每个列表框的选定内容都写在一个单元格中,用逗号分隔。 例如在单元格A1中,所有选中的名字:Tim,Miranda,Laura

这些单元格是访问查询(where子句)的标准。

我打开MS Query并将下面的where子句添加到查询并定义参数:

Where (Instr(?, [name])>0 And Instr(?, [number])>0 And Instr(?, [city])>0 And Instr(?, [phone])>0 And Instr(?, [email])>0) 

它工作得很好,但是如果其中一个参数字段是空的 (例如用户没有select任何城市), 则查询将返回所有的行 ,其中城市是空的,而不是在这种情况下忽略该子句。

你可以帮我吗? 我不知道如何解决这个问题…也许有另一种解决scheme使用VBA和dynamicSQL。 不幸的是,我不知道如何实现这个…

注意:我必须使用Excel作为列表框而不是访问公式,因为工具也应该被没有访问数据库的人使用。

非常感谢!

伊丽莎白

根据我的经验,在某些情况下可能会返回null,影响您在条款中的比较。

当你尝试len函数时会发生什么:

  Where Instr(?, [name])>0 And Instr(?, [number])>0 And (Instr(?, [number])>0 and NOT ISNULL([CITY])) And Instr(?, [phone])>0 And Instr(?, [email])>0)** 

看到上面的代码更改。 对不起,看到你的更新,我只需要抓住这个问题。 你想要包括那些有“空”城市的所有logging吗? 但我以为你想要跳过这些? 我search这个的另一个方法是 – 不是ISNULL([CITY])。 我在一个很多Access数据库的环境下工作,他们很古怪!

我通过在VBA中使用dynamicSQL解决了这个问题。 如果没有select,我将列表框中的所有行链接到一个string。 这是一个包含名称的列表框(代码不包含与数据库的必要连接)的示例:

 Dim string1 As String Dim rngParams As Range, rngCell As Range Dim i As Long 'String name With Worksheets("Table1") For i = 0 to .ListBox1.ListCount - 1 If .ListBox1.Selected(i) Then If string1 = "" Then string1 = "(" string1 = string1 & "'" & .ListBox1.List(i) & "'," End If Next i End With If string1 <> "" Then string1 = Left(string1, Len(string1) - 1) string1 = string1 & ")" End If 'If nothing is selected, use all names and write them into one string If string1 = "" Then string1 = "(" With Worksheets("table2") Set rngParams = .Range("allNames") For Each rngCell In rngParams.Cells string1 = string1 & "'" & rngCell.Value & "'," Next rngCell string1 = Left(string1, Len(string1) - 1) string1 = string1 & ")" End With End If strSQL = "SELECT Name FROM accesstable WHERE Name IN " & string1