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

Posted

技术标签:

【中文标题】将列表框的选择存储在数组 VBA 中【英文标题】:Storing selection of a ListBox in an Array VBA 【发布时间】:2021-09-24 06:28:03 【问题描述】:

我正在尝试从用户表单中的列表框中存储用户选择。我目前正在使用公共属性 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

然后链接到这个子类:

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)

然后当我尝试从另一个模块调用它时,我得到一个错误:

【问题讨论】:

【参考方案1】:

此属性将返回一个包含所选值的数组:

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

【讨论】:

你绝对的上帝!

以上是关于将列表框的选择存储在数组 VBA 中的主要内容,如果未能解决你的问题,请参考以下文章

listbox的值怎么获取vba

通过在列表下拉组合框中选择它来访问 VBA 代码以转到另一个表单上的特定记录

ms excel vba 填充具有不同列要求的列表框

在 Excel VBA 中动态调整组合框的宽度

VB列表框属性的问题

将文件名导入列表框,无需路径访问 2007 vba-