我有一个多选列表框,我希望它成为SQL查询的来源,结果显示在列表框中。目前我将结果转到记录集,当只选择一个1字段时,该记录集显示得很漂亮。例如,如果用户选择Gender,则不打开记录集数据表,List20显示字段名称,下划线,其下方有不同的值 - 完美!!当我尝试选择多个项目时,事情就会出错。例如,选择的2个项目(性别,接口)将导致性别(带下划线),但其下方有2个F和2个M,并且没有接口字段值。如何遍历每个选项并将它们显示在列表框中?这是我的代码。另外,奇怪的是,List13在运行查询时没有显示结果,但是当我拿走这行时: 设置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
答案 0 :(得分: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