在MS Access列表框中循环显示数值

15

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

如何循环遍历列表框中可能存在的任何值?这需要使用 For Each 语句吗?


不要忘记,如果表单上的空间有限,您可以使用多选列表框并使用“Selected”属性。 - Fionnuala
3个回答

27

以下是如何遍历ListBox的代码:

Dim i as Integer

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

22

您可以使用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

请注意,我假设你想要从列表框中选择的项目。如果你想要 所有 项目,无论是否选择,你可以像 @DavidRelihan 建议 的那样使用 .ItemData。不过,在这种情况下,你可以从列表框的 .RowSource 中获取它们。


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
    Rst.MoveNext
Loop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接