vba 循环浏览 MS Access 列表框中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2933113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:29:20  来源:igfitidea点击:

cycling through values in a MS Access list box

ms-accessvbams-access-2007access-vba

提问by Justin

I have a list box that populates with different sets of data based on user selections.

我有一个列表框,它根据用户的选择填充不同的数据集。

How can I cycle through any given values that may be in the list box? Is this a For Eachstatement, or what?

如何循环浏览列表框中可能存在的任何给定值?这是For Each声明还是什么?

回答by Robben_Ford_Fan_boy

Here is how you iterate through the ListBox:

以下是遍历 ListBox 的方法:

Dim i as Integer

For i = 0 to Me.ListBoxName.ListCount -1
   'Access each item with 
   'Me.ListBoxName.ItemData(i)
Next i

回答by HansUp

You can do a Forloop to examine each row in the listbox, and do whateverwith the rows which are selected. In this example, I display the second column from selected items in the lstLocationslistbox. (Column numbering starts with zero.)

您可以For循环检查列表框中的每一行,并对选定的行执行任何操作。在此示例中,我显示了lstLocations列表框中所选项目的第二列。(列编号从零开始。)

Private Sub cmdShowSelections_Click()
    Dim lngRow As Long
    Dim strMsg As String

    With Me.lstLocations
        For lngRow = 0 To .ListCount - 1
            If .Selected(lngRow) Then
                strMsg = strMsg & ", " & .Column(1, lngRow)
            End If
        Next lngRow
    End With

    ' strip off leading comma and space
    If Len(strMsg) > 2 Then
        strMsg = Mid(strMsg, 3)
    End If
    MsgBox strMsg
End Sub

Note I assumed you want the selected items from the list box. If you want allitems, selected or not, you could use .ItemDataas @DavidRelihan suggested. However, in that case, you could get them from the listbox .RowSourceinstead.

注意我假设您想要从列表框中选择的项目。如果您想要所有项目,无论是否选中,您都可以.ItemData按照@DavidRelihan 的建议使用。但是,在这种情况下,您可以.RowSource改为从列表框中获取它们。

回答by Marco Pérez

If working with a listbox in Access I like to capture the listbox recordset and loop through it. Perhaps because I find DAO recordset objects easy to work with.

如果在 Access 中使用列表框,我喜欢捕获列表框记录集并循环遍历它。也许是因为我发现 DAO 记录集对象易于使用。

I'd do something like:

我会做这样的事情:

Dim Rst as DAO.Recordset
Set Rst = lbxYourListboxObj.Recordset
'test to assure that there are records
If Rst.EOF then
     'some error handling
end if
'I'm just paranoid so I always do this
Rst.MoveFirst
'iterate through list
Do Until Rst.EOF
    'do something for each record
    'it is nice and convenient to be able to reference the field names directly too!
    debug.print Rst!Field1.name,Rst!Field1.value
Loop