将列表框的选择存储在数组中 VBA

Storing selection of a ListBox in an Array VBA

我正在尝试存储用户从用户表单中的列表框中选择的内容。我目前正在使用 public 属性 get 从另一个模块的用户表单中检索我的值。

这是我的用户表单:

Public Property Get DateFrom() As String
    DateFrom = TextBox1.Text
End Property
Public Property Get DateTo() As String
    DateTo = TextBox2.Text
End Property
Public Property Get Cost() As String
    Cost = TextBox3.Text
End Property
Public Property Get Expense() As String
    Expense = TextBox4.Text
End Property

从另一个模块调用时有效

Sub FormNLReport()

    With New NLTrans
    
    .Show vbModal
    
    On Error GoTo CloseF
    NLReport .DateFrom, .DateTo, .Cost, .Expense
   
   
  CloseF: Unload NLTrans
        Exit Sub
    
    End With

End Sub

然后链接到这个子 class:

Sub NLReport(DateFrom As String, DateTo As String, Cost As String, Expense As String)

但是,我现在想添加一个多选列表框,但对如何将其从用户窗体传递到模块感到困惑。目前我已经这样做了:

Public Property Get Items(ByRef i As Long) As String

For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) = True Then
    Items(i) = ListBox1.List(i)
    MsgBox (Items(i))
    End If
Next i
End Property

我的其他模块:

Sub FormNLReport()

    With New NLTrans
    
    .Show vbModal
    
    On Error GoTo CloseF
    NLReport .DateFrom, .DateTo, .Cost, .Expense, .Items()
   
   
CloseF: Unload NLTrans
        Exit Sub
    
    End With

End Sub

Sub NLReport(DateFrom As String, DateTo As String, Cost As String, Expense As String, Items() As String)

然后当我尝试从另一个模块调用它时出现错误:

这 属性 将 return 所选值的数组:

Public Property Get Items() As String()
    Dim i As Long, selected As Long
    Dim selectedItems() As String
    
    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.selected(i) = True Then
            ReDim Preserve selectedItems(selected)
            selectedItems(selected) = ListBox1.List(i)
            selected = selected + 1
        End If
    Next i
    
    items = selectedItems
End Property

你可以这样传递:

NLReport Me.DateFrom, Me.Items

并像这样访问它:

Sub NLReport(DateFrom As String, ArrayItems() As String)
    MsgBox ArrayItems(0) '// assumes at lease 1 selected item
End Sub