微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决将列表框的选择存储在数组 VBA 中

我正在尝试从用户表单中的列表框中存储用户选择。我目前正在使用公共属性 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,.Expense,.Items()
   
   
CloseF: Unload NLTrans
        Exit Sub
    
    End With

End Sub

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

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

enter image description here

解决方法

这个属性将返回一个选定值的数组:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。