我正在尝试将模块中的预定义数组传递给用户表单列表框。
我已将数组分配为用户窗体中的公共变量,并尝试从模块中分配它。
这是模块的代码
Sub TestList()
Dim ArrTest As Variant
'Code to populate the array would go here in real application
ArrTest = Array("A", "B", "C")
UserForm1.ListArray = ArrTest
UserForm1.Show
End Sub
这是用户窗体的代码
Public ListArray As Variant
Private Sub UserForm_Initialize()
ListBox1.List = ListArray
End Sub
当我单步执行代码时,用户窗体在到达模块中的 ListArray 分配时打开,但是在用户窗体中,数组被分配为空,并且在到达列表框生成时遇到并遇到运行时错误"381"。
一旦您创建了 UserForm1 的实例,就会调用 Initialize(在这种情况下,您只需引用它即可自动创建该实例(。 因此,当 Initialize 方法运行时,您的列表分配尚未发生。
最好将这样的东西放入窗体上的 Public 方法中并显式调用它。
'userform
Public Sub SetList(lst)
Me.ListBox1.List = lst
End Sub
'regular module
Sub TestList()
Dim ArrTest As Variant
Dim frm As UserForm1
ArrTest = Array("A", "B", "C")
Set frm = New UserForm1
frm.SetList ArrTest
frm.Show
End Sub
另请参阅:https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/
Tim 解释了为什么你的代码不能与可能的解决方案一起工作
保留代码的可能解决方案是在用户窗体Activate
事件中设置数组,该数组在Show
方法处触发,因此在用户窗体初始化后:
Private Sub UserForm_Activate() ' <- use 'Activate' event instead of 'Initialize'
ListBox1.List = ListArray
End Sub
此外,建议显式实例化用户表单对象
蒂姆已经向你展示了一种方法,这是另一种方法:
With New UserForm1 ' instantiate and reference a new object of your Userfom1 class
.ListArray = ArrTest
.Show
End With ' here the new instance gets disposed