我有一个列表框,根据用户的选择会填充不同的数据集。
如何循环遍历列表框中可能存在的任何值?这需要使用 For Each
语句吗?
我有一个列表框,根据用户的选择会填充不同的数据集。
如何循环遍历列表框中可能存在的任何值?这需要使用 For Each
语句吗?
以下是如何遍历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
请注意,我假设你想要从列表框中选择的项目。如果你想要 所有 项目,无论是否选择,你可以像 @DavidRelihan 建议 的那样使用 .ItemData
。不过,在这种情况下,你可以从列表框的 .RowSource
中获取它们。
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