首页 > 解决方案 > 如何将列表框中的项目写入数组 VBA

问题描述

在用户表单中,我希望CommandButton1_Click基本上将列表框中的任何内容放入我设置的数组中As VariantComandButton2_Click获取用户在 ComboBox 中选择的任何内容并将其插入 ListBox。但是我正在用我想要带走的最后一个数组来做这个SelectedTitles

Public SelectedTitles As Variant, ArrCount As Long, EnableEvents As Boolean

Private Sub CommandButton1_Click()
    Dim Size As Integer
    Size = ListBox1.ListCount - 1
    ReDim SelectedTitles(0 To Size) As Variant
    Dim x As Integer
    
    For x = 0 To Size
        SelectedTitles(x) = ListBox1.Value(x)
    Next x
    
    'Done Button
    Me.Hide
End Sub

Private Sub CommandButton2_Click()
    'User has indicated they want to add the currently selected item to the list
    If Not EnableEvents Then Exit Sub
    If ArrCount = 0 Then 'First item, create the array
        SelectedTitles = Array("")
    Else
        ReDim Preserve SelectedTitles(UBound(SelectedTitles) + 1) 'Next items, add one more space in the array
    End If
    
    ListBox1.AddItem (ComboBox1.Value)
    
    'Increment the counter
    ArrCount = ArrCount + 1
    
    'Reset the checkbox and the combobox
    EnableEvents = False
    CommandButton2.Value = False
    ComboBox1.Value = ""
    EnableEvents = True
End Sub

我收到错误“类型不匹配”

SelectedTitles(x) = ListBox1.Value(x)

标签: arraysexcelvba

解决方案


推荐阅读