Excel VBA:为多列列表框创建数组

时间:2017-07-20 12:51:03

标签: arrays excel vba excel-vba listbox

Yesterday,我问过如何为列创建数组。早些时候我只需要一个,但现在我有一个多列列表框。使用给我的三个代码,我试图编辑它以查看它是否有效,但我认为我必须做错了。如果我做得正确,它可以告诉我,它只是我程序的另一部分,或者我只是需要修复它。另外它给了我

  

下标超出范围

这是我认为需要检查的部分:

Private Sub CommandButton1_Click()

Dim listboxarr()
Dim i As Long, j As Long
Dim found As Boolean

With Me.selecteditems
    For i = 0 To .ListCount - 1
        For h = 1 To 2
        If .Selected(i) Then
            found = True
            j = j + 1
            k = k + 1
            ReDim Preserve listboxarr(1 To j)
            listboxarr(j, k) = .List(i, h)
        End If
    Next i
End With

End Sub

如果您想知道这是我使用它的地方。这将获取项目并建立格式,稍后将使用该格式在列表框selecteditems中添加和删除项目项。然后将其发送到上述任务,该任务选择所选对象并将其放入数组中,以便稍后将其用于打印到电子邮件中

Private Sub UserForm_Initialize()

For Each itemname In itemsheet.Range("A2:A3400")
    With Me.allitems
        .ColumnCount = 2
        .ColumnWidths = "60;60"
        .AddItem itemname.Value
        .List(i, 0) = itemnum
        .List(i, 1) = Description
        i = i + 1
    End With
Next itemname

For Each itemname In itemsheet.Range("A2:A3400")
    With Me.selecteditems
        .ColumnCount = 2
        .ColumnWidths = "60;60"
        .List(i, 0) = itemnum
        .List(i, 1) = Description
        i = i + 1
    End With
Next itemname

End Sub


Private Sub addcb_Click()
    Dim iCtr As Long

    For iCtr = 0 To Me.allitems.ListCount - 1
        If Me.allitems.Selected(iCtr) = True Then
            Me.selecteditems.AddItem Me.allitems.List(iCtr)
        End If
    Next iCtr

    For iCtr = Me.allitems.ListCount - 1 To 0 Step -1
        If Me.allitems.Selected(iCtr) = True Then
            Me.allitems.RemoveItem iCtr
        End If
    Next iCtr


End Sub


Private Sub removecb_Click()
    Dim iCtr As Long

    For iCtr = 0 To Me.selecteditems.ListCount - 1
        If Me.selecteditems.Selected(iCtr) = True Then
            Me.allitems.AddItem Me.selecteditems.List(iCtr)
        End If
    Next iCtr

    For iCtr = Me.selecteditems.ListCount - 1 To 0 Step -1
        If Me.selecteditems.Selected(iCtr) = True Then
            Me.selecteditems.RemoveItem iCtr
        End If
    Next iCtr
End Sub

编辑:我试图删除我添加的内容甚至是selecteditems。没有变化。

0 个答案:

没有答案