以编程方式在 VBA (Excel) 中添加 ComboBox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17675761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Programmatically add ComboBox in VBA (Excel)
提问by Kr?lleb?lle
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 nothave MSForms
in my API (i.e. I cannot write Dim someComboBox As MSForms.ComboBox
as it fails. Is it possible to import it somehow? Can someone point me in the right direction?
我正在尝试在 VBA 中创建、放置和填充 ComboBox 的元素。我不明白我错过了什么,但我无法弄清楚如何去做。我不有MSForms
我的API(即我不能写Dim someComboBox As MSForms.ComboBox
,因为它失败。是否有可能以某种方式进口吗?可有人点我的方向是正确的?
What I want to achieve is that when the user clicks a button a new form is created with various items (ComboBoxes, RadioButtons, etc.) and thus I want to do this programmatically.
我想要实现的是,当用户单击按钮时,会创建一个包含各种项目(组合框、单选按钮等)的新表单,因此我想以编程方式执行此操作。
回答by varocarbas
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
回答by Andy G
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.
您需要对 Microsoft Forms 2.0 对象库的引用。一个简单的方法是在你的项目中插入一个用户窗体。
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.
您可以通过编程方式创建用户窗体、组合框等,但插入用户窗体并将其隐藏直到需要时会更容易。如果需要,您仍然可以以编程方式向其添加新控件。
AddedThe Forms Object Library won't enable you to create entirely new forms and controls. You need the Microsoft Visual Basic for Applications Extensibilitylibrary. This linkis old, but still relevant.
添加了Forms 对象库不会使您能够创建全新的表单和控件。您需要Microsoft Visual Basic for Applications 扩展库。这个链接是旧的,但仍然相关。