【发布时间】:2011-02-25 08:41:24
【问题描述】:
我有一个列表框,它根据用户选择填充不同的数据集。
如何循环浏览列表框中可能存在的任何给定值?这是For Each 声明还是什么?
【问题讨论】:
-
不要忘记,如果表单上的空间成为问题,您可以拥有一个多选列表框并使用 Selected 属性。
标签: vba ms-access ms-access-2007
我有一个列表框,它根据用户选择填充不同的数据集。
如何循环浏览列表框中可能存在的任何给定值?这是For Each 声明还是什么?
【问题讨论】:
标签: vba ms-access ms-access-2007
以下是您如何遍历 ListBox:
Dim i as Integer
For i = 0 to Me.ListBoxName.ListCount -1
'Access each item with
'Me.ListBoxName.ItemData(i)
Next i
【讨论】:
您可以执行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 中获取它们。
【讨论】:
如果在 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
【讨论】: