VBA将列表框传递给函数

tee*_*pee 1 excel vba excel-vba

我试图通过将我的列表框对象传递给子函数来填充列表框,但每当我运行它时,我都会遇到类型不匹配错误.我将对象MAIN.BoxY1传递给函数FillListBox,其中MAIN是列表框所在的工作表的代号,BoxY1是我的列表框名称(ActiveX).当我改变FillListBox函数以包含MAIN.BoxY1而不是每个实例的MyBox时,它将正常工作.将列表框传递给另一个函数的正确方法是什么?

Sub FillListBox(MyBox As ListBox, DataList As Variant)
    MyBox.MultiSelect = 1
    For j = 1 To NumOutputs
        MyBox.AddItem DataList(j)
    Next j
End Sub

Sub BoxY1_Fill()
    FillListBox MAIN.BoxY1, TheData
End Sub
Run Code Online (Sandbox Code Playgroud)

 

Tim*_*ams 7

Excel中有两种类型的列表框:"内置"类型和ActiveX版本.根据您要处理的类型,您需要以不同方式设置函数参数:

Sub Testing()
    test1 Sheet1.ListBox1                            ' <<ActiveX Listbox
    test2 Sheet1.ListBoxes("ListBox2")               ' <<Forms Listbox
    test2 Sheet1.Shapes("ListBox2").OLEFormat.Object ' <<Forms Listbox (avoiding 
                                                     '   deprecated 'Listboxes')
End Sub

'ActiveX listbox
Function test1(lb As msforms.ListBox)
    Debug.Print lb.ListCount
End Function

'Forms listbox
Function test2(lb As ListBox)
    Debug.Print lb.ListCount
End Function
Run Code Online (Sandbox Code Playgroud)