我有一张表,上面放了一个 ActiveX 列表框,还有一个函数可以更新某个列表框(它的 listfillrange 是一个具有动态大小的命名范围) 以下所有代码都在 Microsoft Excel 对象 - Sheet1
中更新ListBox的功能
Private Sub update(lst As ListBox)
lst.ListIndex = -1
lst.ListFillRange = lst.ListFillRange
End Sub
我想在两种场景下调用这个函数:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Application.Intersect("{some ranges}") Is Nothing Then update Me.ListBox
End Sub
Private Sub OtherListBox_Click()
update Me.ListBox
End Sub
然而,当代码尝试调用更新子时,它在更新行上给我一个类型不匹配错误 这是我第一次使用列表框,所以我的理解非常有限,我不明白为什么这两种情况都行不通
为了访问您的 ActiveX 列表框,首先设置它会更容易。这是它变得有点棘手的地方,我们需要设置为
OLEObject
然后访问OLEObject.Object
的属性。
查看下面修改后的代码,其中包含注释(tested):
Option Explicit
' --- List of Variable on top of your module, so all sub-modules within your module can access them ---
Dim MySht As Worksheet
Dim MyListBox As OLEObject
'================================================================
Sub Init()
' Set up Worksheet object and OLEObject to your ActiveX List-Box
Set MySht = ThisWorkbook.Sheets("Sheet1") ' < -- rename to the worksheet's name you have
With MySht
Set MyListBox = .OLEObjects("ListBox1") ' <-- Use the ListBox name you have
End With
End Sub
'================================================================
Private Sub Worksheet_Change(ByVal Target As Range)
' If Not Application.Intersect("{some ranges}") Is Nothing Then update Me.ListBox
If Not Application.Intersect(Target, Range("A1:H100")) Is Nothing Then
' ~~~Call Sub the initializes Objects ~~~
Init
' ~~~ Call Sub that updates 'MyListBox' ~~~
update MyListBox
End If
End Sub
'================================================================
Private Sub update(lst As OLEObject) ' < -- Use OLEObject and not ListBox
lst.Object.ListIndex = -1
lst.Object.ListFillRange = lst.ListFillRange
End Sub
有点混乱:如果您使用的是ActiveX-Controls,则需要将参数声明为
MSForms.Listbox
.
Private Sub update(lst As MSForms.ListBox)
lst.ListIndex = -1
lst.ListFillRange = lst.ListFillRange
End Sub
ListBox
(没有MSForms.
)将引用“旧”列表框类型(所谓的Form Controls)。
如果你希望你的代码是通用的,这可以工作,无需指定控件类型(测试工作):
Private Sub update(lst As Object)
lst.ListIndex = -1
lst.ListFillRange = lst.ListFillRange
End Sub