Excel VBA 类型不匹配从 ListBox_Click 调用 Private Sub

问题描述 投票:0回答:3

我有一张表,上面放了一个 ActiveX 列表框,还有一个函数可以更新某个列表框(它的 listfillrange 是一个具有动态大小的命名范围) 以下所有代码都在 Microsoft Excel 对象 - Sheet1

更新ListBox的功能

Private Sub update(lst As ListBox)
    lst.ListIndex = -1
    lst.ListFillRange = lst.ListFillRange
End Sub

我想在两种场景下调用这个函数:

  1. 当工作表改变时:
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Application.Intersect("{some ranges}") Is Nothing Then update Me.ListBox
End Sub
  1. 当点击不同的列表框时:
Private Sub OtherListBox_Click()
    update Me.ListBox
End Sub

然而,当代码尝试调用更新子时,它在更新行上给我一个类型不匹配错误 这是我第一次使用列表框,所以我的理解非常有限,我不明白为什么这两种情况都行不通

excel vba listbox
3个回答
0
投票

为了访问您的 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

0
投票

有点混乱:如果您使用的是ActiveX-Controls,则需要将参数声明为

MSForms.Listbox
.

Private Sub update(lst As MSForms.ListBox)
    lst.ListIndex = -1
    lst.ListFillRange = lst.ListFillRange 
End Sub

ListBox
(没有
MSForms.
)将引用“旧”列表框类型(所谓的Form Controls)。


0
投票

如果你希望你的代码是通用的,这可以工作,无需指定控件类型(测试工作):

Private Sub update(lst As Object)
    lst.ListIndex = -1
    lst.ListFillRange = lst.ListFillRange
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.