列表框索引的数据类型

data type of Listbox Index

当我搜索有关Listbox的资料时,我看到大多数人使用Variant作为列表索引号的数据类型。 示例:

Dim varItm As Variant
If Me.myListBox.ItemData.Selected(varItm) = True 

使用 Variant 或 Integer 作为数据类型更好吗?

你混淆了两件事。当您有一个多选列表框时,用户将使用以下代码,因为 .SelectedItems 集合必须是变体:

Dim varItm as Variant
For Each varItm in myListBox.SelectedItems
    'Do Something
Next varItm

但是,有further documentation on myListBox.Sected(x) where x is supposed to be Long but really could be any number containing variable. Variant allows for numbers to be stored, so it would work, but better to define x as explicitly containing a number (Integer or Long) More on Integer vs. Long

Dim x As Integer
For x = 0 to myListBox.ListCount - 1
    If myListBox.Selected(x) Then
        'Do Something
    End If
Next x