【问题标题】:How to store all selected data from listbox in an array in VBA如何将列表框中的所有选定数据存储在VBA中的数组中
【发布时间】:2019-10-29 02:20:46
【问题描述】:

我想知道是否有一种简单的方法可以将 ListBox 中的所有选定项目存储到一个数组中。

我尝试使用以下代码执行此操作,但它没有工作除了例外。 FilterTest()什么都不给我。

Private Sub ListBox1_Change()

    Dim FilterTest() As Variant
    Dim myMsg As String
    Dim i As Long
    Dim Count As Integer


    Count = 1

    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(i) Then

            ReDim Preserve FilterTest(Count)
            FilterTest(Count) = ListBox1.List(i)
            Count = Count + 1


        End If
    Next i

End Sub

【问题讨论】:

    标签: arrays excel vba listbox


    【解决方案1】:

    你很亲密。数组是以 0 为基数的集合(除非另有说明),所以从 0 开始计数。您也可以在声明变量时去掉括号。接下来,第一次重新调整变量,然后在接下来的迭代中重新调整变量。

    Private Sub ListBox1_Change()
    
        Dim FilterTest As Variant
        Dim myMsg As String
        Dim i As Long
        Dim Count As Integer
    
        Count = 0
    
        For i = 0 To ListBox1.ListCount - 1
            If ListBox1.Selected(i) Then
                If Count = 0 Then
                    Redim FilterTest(Count)
                Else
                    Redim Preserve FilterTest(Count)
                End If
                FilterTest(Count) = ListBox1.List(i)
                Count = Count + 1
            End If
        Next i
    
    End Sub
    

    【讨论】:

    • @Dorian “这些价值观”是什么意思?请澄清
    • 谢谢@Tim Stack,你能解释一下为什么Count = 1 这不起作用吗? ;)。我刚刚找到了这样做的方法,这就是为什么我删除了 com 抱歉
    • 因为1实际上是数组的第二项。这是一个base 0的集合,所以0实际上是第一项
    • 如何使用存储在数组中的数据?当我尝试将选择的所有数据打印到 Sub 之外的消息框中时,我得到错误代码 9:超出范围。例如为什么这个命令行不起作用? MsgBox FilterTest(1) 我在想这会显示数组的第二个元素..
    • 不看代码恐怕帮不了你调试代码。我认为此时最好开始一个新问题,因为这些问题与主要问题无关。首先阅读数组here 会有所帮助
    猜你喜欢
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 2021-07-28
    • 2013-11-03
    • 2018-09-23
    相关资源
    最近更新 更多