VBA如何通过名称excel-2010访问列表框

时间:2018-08-09 16:13:18

标签: vba excel-2010

下面是我的VBA代码,用于从列表框中获取选定的项目。我想将列表框的名称作为字符串发送,然后以这种方式访问​​列表框,因为我无法直接访问列表框,因为此代码与工作表源代码位于单独的模块中。

所以我要问的是如何通过字符串访问列表框。 例如,代替

Worksheets("sheet1").ListBox1

我想要类似

Worksheets("sheet1")."ListBox1"

因此,只要我具有列表框的名称,我就可以重用此功能

下面的代码

Public Function getListBoxSelection(listBox As MSForms.listBox) As String
    Dim colCount As Integer
    Dim I As Long
    Dim selectedItem As String

    If listBox.ListIndex <> -1 Then
        For I = 0 To (listBox.ColumnCount - 1)
             selectedItem = selectedItem & listBox.column(I)
        Next I
    End If
    getListBoxSelection = selectedItem
End Function

提前谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用Worksheets(“ sheet1”)。OLEObjects(“ ListBox1”)。Object