0

我有一个多选列表框,我希望它成为 sql 查询的来源,结果显示在列表框中。目前,我将结果转到一个记录集,当只选择一个 1 字段时,该记录集显示得很漂亮。例如,如果用户选择 Gender,则不会打开任何记录集数据表,并且 List20 会显示字段名称,下划线,其下方带有不同的值——完美!!当我尝试选择多个项目时,事情就会出错。例如,选择 2 个项目(性别、界面)将导致性别(下划线),但其下方有 2 个 F 和 2 个 M,并且没有任何界面字段值。如何遍历每个选择并让它们显示在列表框中?这是我的代码。另外,奇怪的是,当我运行查询时,List13 没有显示任何结果,但是当我删除该行时:Set Me.List13。Recordset = rs 将打开一个记录集数据表,并且所需的结果不再出现在 List20 中。请帮忙!

Private Sub Command19_Click()
Dim strSQL As String
Dim strCriteria As String
Dim varItem As Variant
Dim dbs As Database
Set dbs = CurrentDb()
Dim qdf As QueryDef
Dim rs As Recordset

On Error GoTo Err_Command19_Click

For Each varItem In Me!List101.ItemsSelected
strCriteria = strCriteria & ",'" & Me!List101.ItemData(varItem) & "'"
Next varItem

strCriteria = Right(strCriteria, Len(strCriteria) - 1)

strSQL = "SELECT DISTINCT " & strCriteria & " FROM Scrubbed"
strSQL = Replace(strSQL, "'", "")

Set rs = dbs.OpenRecordset(strSQL)
Do Until rs.EOF
Set Me.List20.Recordset = rs
Set Me.List13.Recordset = rs
Loop

With dbs
Set qdf = .CreateQueryDef("TmpDistinctValues", strSQL)
DoCmd.OpenQuery "TmpDistinctValues"
.QueryDefs.Delete "TmpDistinctValues"
End With
dbs.Close
qdf.Close

Exit_Command19_Click:
   Exit Sub
Err_Command19_Click:
    MsgBox "Please select a field"

End Sub
4

1 回答 1

0

你的意思肯定是:

For Each varItem In Me!List101.ItemsSelected
   strCriteria = strCriteria & "," & Me!List101.ItemData(varItem) 
   colcount = colcount + 1
   colwidths = colwidths & ";" & "1134"
Next varItem

strCriteria = Right(strCriteria, Len(strCriteria) - 1)

strSQL = "SELECT DISTINCT " & strCriteria & " FROM Scrubbed"
''strSQL = Replace(strSQL, "'", "")

''Set rs = dbs.OpenRecordset(strSQL)
''Do Until rs.EOF
Me.List20.RowSource = strSQL
Me.List20.ColumnCount = colcount
Me.List20.ColumnWidths = Mid(colwidths, 2)

''Set Me.List13.Recordset = rs
''Loop
于 2012-08-01T20:40:18.363 回答