单击事件创建组合框时在组合框中添加项目

时间:2018-10-25 15:31:35

标签: excel vba combobox userform

我正在尝试在comboBox中添加项目。我知道如何使用myBox.AddItem "words"来执行此操作,但是当我在click事件上创建comboBox时,在将其实现到我的代码时遇到了一个问题:

Private Sub CommandButton2_Click()
    Dim editBox As MSForms.Control
    Dim testBox As ComboBox
    Static i
    Set editBox = Me.Controls.Add("Forms.ComboBox.1")
    i = i + 1
    With editBox
        .Name = "cmBox" & i
        .Top = i * editBox.Height + 10
        .Left = 130
    End With
End Sub

您有什么建议吗? 谢谢

1 个答案:

答案 0 :(得分:2)

假设在创建控件时这些项是已知的,则...您可以直接在处理程序中进行操作。只需将testBox设置为您的editBox参考:

Set testBox = editBox 'basically cast from MSForms.Control to MSForms.ComboBox
testBox.Add "test1"
testBox.Add "test2"

另一方面,如果在创建控件时不知道这些项目,则您有问题:

Dim testBox As ComboBox

该对象是本地作用域的,并且在单击处理程序退出后就超出范围。

您需要坚持下去。将该声明移到模块级别(并保证其一致性,以确保一致性):

Private testBox As MSForms.ComboBox

然后您可以调用testBox.Add ....问题是您将要添加多个控件,因此不能只拥有一个这样的字段。改用Collection

Private dynamicControls As Collection

Private Sub UserForm_Initialize()
    Set dynamicControls = New Collection
End Sub

现在,当您创建动态控件时,请通过以下键将其添加到集合中:

Set editBox = Me.Controls.Add("Forms.ComboBox.1")
'...
dynamicControls.Add editBox, editBox.Name

如果需要处理这些动态控件的事件,则需要进行其他设置,并为每个动态控件提供一个自定义类的实例:

'Class1
Option Explicit
Private WithEvents box As MSForms.ComboBox

Private Sub box_Change()
    '...
End Sub

Public Property Get Control() As MSForms.ComboBox
    Set Control = box
End Property

Public Property Set Control(ByVal value As MSForms.ComboBox)
    Set box = value
End Property

然后,当您创建动态控件时,请将其添加到该类的新实例中:

Set editBox = Me.Controls.Add("Forms.ComboBox.1")
'...
Dim dynamicHandler As Class1
Set dynamicHandler = New Class1 'todo rename that class
Set dynamicHandler.Control = editBox
dynamicControls.Add dynamicHandler, editBox.Name

现在,当您准备将项目添加到给定框中时,请从dynamicControls集合中检索控件:

With dynamicControls("cmBox1")
    .Add "test1"
    .Add "test2"
End With