从vba模块创建和填充组合框

时间:2016-01-19 09:16:49

标签: excel vba excel-vba

在Excel 2010中,我尝试在我的vba代码中动态创建用户窗体。但是,运行代码后,打开下拉列表时不会显示列表。如果我在“.show”之前放置一个断点,我可以在设计窗口中检查表单,我看到列表已填充。 .show方法是否清除列表或发生了什么?我发现的解决方案专注于从单元格范围填充或将“.additem”放在userform的初始化代码中。我不想做任何需要我创建第二个文件的事情。如果可能的话,一切都应该在这个vba代码中。任何帮助赞赏。我的代码如下。

Sub make_combobox_form()
    ' Makes a form with only a simple combobox
    Dim myForm As Object
    Dim cb As MSForms.ComboBox

    'Create the User Form
    Set myForm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)

    With myForm
        .Properties("Width") = 400
        .Properties("Height") = 300
    End With

    Set cb = myForm.Designer.Controls.Add("Forms.ComboBox.1")
    With cb
        .Top = 100
        .Left = 100
        .Height = 20
        .Width = 200

        .AddItem "Item_1"
        .AddItem "Item_2"
        .AddItem "Item_3"
        .value = "Item_1"
    End With

    VBA.UserForms.Add(myForm.name).Show

    ThisWorkbook.VBProject.VBComponents.Remove myForm

End Sub

1 个答案:

答案 0 :(得分:2)

Sub make_combobox_form()

    'Create the User Form as component first
    Dim myFormComponent As VBComponent
    Set myFormComponent = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)

    ' Get reference to user form from the UserForms collection then
    Dim cb As MSForms.ComboBox
    Dim myForm As Variant
    Set myForm = VBA.UserForms.Add(myFormComponent.Name)

    With myForm
        .Width = 400
        .Height = 300
    End With

    Set cb = myForm.Controls.Add("Forms.ComboBox.1")
    With cb
        .Top = 100
        .Left = 100
        .Height = 20
        .Width = 200
        .AddItem "Item_1"
        .AddItem "Item_2"
        .AddItem "Item_3"
        .Value = "Item_1"
    End With

    myForm.Show

    ThisWorkbook.VBProject.VBComponents.Remove myFormComponent

End Sub