Programmatically add ComboBox in VBA (Excel)

前端 未结 2 1368
感动是毒
感动是毒 2020-12-06 14:44

I am trying to create, place and fill in elements of a ComboBox in VBA. I don\'t understand what I am missing, but I cannot possibly figure out how to do it. I do not

相关标签:
2条回答
  • 2020-12-06 15:12

    You need a reference to Microsoft Forms 2.0 Object Library. An easy way to do this is to just insert a UserForm in your project.

    Alternatively, find this reference in the Tools/ References dialog.

    You can programmatically create a UserForm, a ComboBox, etc., but it would be easier to just insert a UserForm and leave it hidden until needed. You can programmatically add new controls to it still, if needed.

    Added The Forms Object Library won't enable you to create entirely new forms and controls. You need the Microsoft Visual Basic for Applications Extensibility library. This link is old, but still relevant.

    0 讨论(0)
  • 2020-12-06 15:24

    You can rely on the following code:

     Set curCombo = ActiveSheet.Shapes.AddFormControl(xlDropDown, Left:=Cells(1, 1).Left, Top:=Cells(2, 1).Top, Width:=100, Height:=20)
     With curCombo
            .ControlFormat.DropDownLines = 2
            .ControlFormat.AddItem "Item 1", 1
            .ControlFormat.AddItem "item 2", 2
            .Name = "myCombo"
            .OnAction = "myCombo_Change"
     End With
    
    0 讨论(0)
提交回复
热议问题