在多选列表框中的每个项目上运行SQL查询,并在另一个列表框中显示结果?

时间:2012-07-31 14:17:14

标签: ms-access-2003

我正在多选列表框中选择的字段上运行“select distinct”查询(列表框中填充了表中的字段)。在我进行多选之前,代码工作正常,现在SQL查询无法运行。例如,当我从字段列表中选择字段“Gender”和“INTERFACE”时,第二个列表框中的结果为:

SELECT DISTINCT 性别 INTERFACE

理想情况下,我的结果将包括字段名称,然后是值,每个字段之间都有一行结果。

这是我的代码:

Dim strSQL As String
Dim strCriteria As String
Dim varItem As Variant

On Error GoTo Err_Command206_Click

For Each varItem In Me.ScrubbedList.ItemsSelected
strCriteria = strCriteria & ",[" & Me!ScrubbedList.ItemData(varItem) & "]"

Next varItem

strSQL = "SELECT DISTINCT " & Mid(strCriteria, 2) & " FROM Scrubbed"

'====== Testing
Debug.Print strSQL
'=====

Me.List316.RowSource = strSQL

Exit_Command206_Click:
    Exit Sub
Err_Command206_Click:
    MsgBox "Please select a field"

1 个答案:

答案 0 :(得分:0)

你似乎有一些错误的地方:

Dim strSQL As String
Dim strCriteria As String
Dim varItem As Variant

On Error GoTo Err_Command206_Click

For Each varItem In Me.ScrubbedList.ItemsSelected
    strCriteria = strCriteria & ",[" & Me!ScrubbedList.ItemData(varItem) & "]"

Next varItem


strSQL = "SELECT DISTINCT " & Mid(strCriteria,2) & " FROM Scrubbed"

'====== Testing
Debug.Print strSQL
'======

Me.List316.RowSource = strSQL


Exit_Command206_Click:
    Exit Sub
Err_Command206_Click:
    MsgBox "Please select a field"