在MS Access列表框中循环浏览值

问题描述 投票:11回答:3

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

如何循环显示列表框中的任何给定值?这是For Each语句,还是什么?

ms-access vba ms-access-2007 access-vba
3个回答
19
投票

您可以进行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

注意我假设您要从列表框中选择项目。如果要选择全部项目,则可以将.ItemData用作@DavidRelihan suggested。但是,在这种情况下,您可以从列表框.RowSource中获取它们。


24
投票

这是您遍历列表框的方式:

Dim i as Integer

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

2
投票

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

我会做类似的事情:

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
© www.soinside.com 2019 - 2024. All rights reserved.