使用多选项按Listbox排序查询?

时间:2015-10-22 17:43:36

标签: vb.net ms-access ms-access-2007

我的任务是创建一个查询,该查询通过多选的列表框结果进行过滤。我有一个名为contacts的表,其中有一个名为' Sources'的字段。这是我的列表视图中显示的字段。我按照来源'排序。值

从这里,我可以多选选项,然后点击提交按钮。当我这样做时,我得到一个查询,但它似乎只是显示所有值。

因此,我的问题是,如何创建按“来源”选项卡排序的查询?我知道我需要一个onclick函数,但我对VB非常不熟悉。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以修改以下内容以使用控件名称。您没有提到查询的创建位置和方式,但您可以将此代码合并到您的...

Private Sub cmdBuildWhere_Click()
Dim varItem     As Variant
Dim strWhere    As String

If Me.lstHierarchy.ListIndex < 1 And Me.lstHierarchy.ItemsSelected.Count = 0 Then   ' No items selected
    MsgBox "You did not select any sources. ", vbOKOnly, "Select Sources"
    Exit Sub
End If

strWhere = "WHERE "

For Each varItem In Me.lstHierarchy.ItemsSelected
    strWhere = strWhere & "[Sources] = '" & Me.lstHierarchy.Column(0, varItem) & "' Or "
Next varItem

' remove final ' or ' and add Sort
strWhere = Trim(left(strWhere, Len(strWhere) - 4)) & " Order By Sources;"

Debug.Print strWhere

End Sub