excel-vba 用户表单中的列表框被设置为 Null
Listbox is being set to Null somehow in excel-vba user form
上下文:我正在编写一个用户表单,该表单将包含一些过滤器以 运行 一个过程并使用 return 值填充工作表。
我的一个过滤器有问题。我能够以简化版本重现我的问题。此过滤器应根据选定的组合框选项将数据加载到列表框中:
我没有重命名任何东西,组件是:UserForm1
、ListBox1
和ComboBox1
。
我的损坏的代码(已评论):
Option Explicit
'sub that fill data in the list box columns
Sub loadList(list As ListBox, id As Integer)
list.Clear
If (id > 0) Then
list.AddItem
list.Column(0, 0) = "Item 1"
list.AddItem
list.Column(0, 1) = "Item 2"
End If
End Sub
'event that will trigger the loadList sub
Private Sub ComboBox1_Change()
Dim id As Integer
id = ComboBox1.ListIndex
loadList ListBox1, id
End Sub
'the combo options is auto initialized
Private Sub UserForm_Initialize()
ComboBox1.AddItem
ComboBox1.Column(0, 0) = "Option 1"
ComboBox1.AddItem
ComboBox1.Column(0, 1) = "Option 2"
End Sub
当我设置断点时,我可以看到问题所在。 ListBox1
被设置为 Null
,但我不知道如何解决它:
错误说:
Run-time error '13': Type mismatch
但这很明显,因为 ListBox1
不知何故被设置为 Null
。
有没有人经历过这种行为?如何解决它?提前致谢。
看起来很奇怪,有两个类来自不同的库,名为ListBox
,VBA混淆了它们(实际上所有控件都一样)。这取决于您使用的是 MSForms
控件还是 ActiveX
控件。
在你的情况下,你应该用 MSForms.ListBox
来消除歧义,这是你的列表框的实际类型。
Sub loadList(list As MSForms.ListBox, id As Integer)
' ^^^^^^^
为避免此类疑虑,您还可以使用 list As Object
,(只要您仅使用常用方法,就会使您的子处理两种类型)。
上下文:我正在编写一个用户表单,该表单将包含一些过滤器以 运行 一个过程并使用 return 值填充工作表。
我的一个过滤器有问题。我能够以简化版本重现我的问题。此过滤器应根据选定的组合框选项将数据加载到列表框中:
我没有重命名任何东西,组件是:UserForm1
、ListBox1
和ComboBox1
。
我的损坏的代码(已评论):
Option Explicit
'sub that fill data in the list box columns
Sub loadList(list As ListBox, id As Integer)
list.Clear
If (id > 0) Then
list.AddItem
list.Column(0, 0) = "Item 1"
list.AddItem
list.Column(0, 1) = "Item 2"
End If
End Sub
'event that will trigger the loadList sub
Private Sub ComboBox1_Change()
Dim id As Integer
id = ComboBox1.ListIndex
loadList ListBox1, id
End Sub
'the combo options is auto initialized
Private Sub UserForm_Initialize()
ComboBox1.AddItem
ComboBox1.Column(0, 0) = "Option 1"
ComboBox1.AddItem
ComboBox1.Column(0, 1) = "Option 2"
End Sub
当我设置断点时,我可以看到问题所在。 ListBox1
被设置为 Null
,但我不知道如何解决它:
错误说:
Run-time error '13': Type mismatch
但这很明显,因为 ListBox1
不知何故被设置为 Null
。
有没有人经历过这种行为?如何解决它?提前致谢。
看起来很奇怪,有两个类来自不同的库,名为ListBox
,VBA混淆了它们(实际上所有控件都一样)。这取决于您使用的是 MSForms
控件还是 ActiveX
控件。
在你的情况下,你应该用 MSForms.ListBox
来消除歧义,这是你的列表框的实际类型。
Sub loadList(list As MSForms.ListBox, id As Integer)
' ^^^^^^^
为避免此类疑虑,您还可以使用 list As Object
,(只要您仅使用常用方法,就会使您的子处理两种类型)。