我已经离开VBA几年了,我正在尝试在VBA代码中构建多个组合框。
我可以让代码适用于单个组合框,但我在添加第二个组合时遇到了问题。
以下是我的最新代码。此代码添加了组合框,但它不会填充下拉列表,它还会生成一个"对象不支持此属性或方法"错误。
任何想法或意见都将受到高度赞赏。
Sub CreateComboBoxes()
Dim cbox1 As OLEObject
Dim cbox2 As OLEObject
Set cbox1 = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
Left:=20, Top:=30, Width:=100, Height:=20)
Set cbox2 = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
Left:=150, Top:=30, Width:=100, Height:=20)
Sheets("Dashboard").cbox1.Clear
Sheets("Dashboard").cbox1.AddItem "NYC"
Sheets("Dashboard").cbox1.AddItem "London"
Sheets("Dashboard").cbox1.AddItem "Tokyo"
Sheets("Dashboard").cbox2.Clear
Sheets("Dashboard").cbox2.AddItem "One"
Sheets("Dashboard").cbox2.AddItem "Two"
Sheets("Dashboard").cbox2.AddItem "Three"
End Sub
编辑:链接的存档问题仅适用于单个组合框,我尝试添加多个组合框。我可以让它适用于单个组合框,但是在创建代码时遇到问题。
答案 0 :(得分:2)
如果将cbox1和cbox2定义为Object,则可以操作其下拉值。您的代码应如下所示:
Sub CreateComboBoxes()
Dim cbox1 As Object
Dim cbox2 As Object
Set cbox1 = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
Left:=20, Top:=30, Width:=100, Height:=20).Object
Set cbox2 = ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, _
Left:=150, Top:=30, Width:=100, Height:=20).Object
cbox1.Clear
cbox1.AddItem "NYC"
cbox1.AddItem "London"
cbox1.AddItem "Tokyo"
cbox2.Clear
cbox2.AddItem "One"
cbox2.AddItem "Two"
cbox2.AddItem "Three"
End Sub