如何在 Excel 中使用 vba 创建和填充 activex 组合框。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11692816/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:39:51  来源:igfitidea点击:

How to create and populate an activex combobox using vba in excel.

excel-vbacomboboxvbaexcel

提问by James Watts

I am having a problem when trying to create and then populate a activex combobox in vba for excel. The code below works when run as two seperate macros but when I try to put the two together an empty combobox is created. Can anybody tell me why this is and how to overcome this problem?

我在尝试在 vba 中为 excel 创建然后填充 activex 组合框时遇到问题。下面的代码在作为两个单独的宏运行时有效,但是当我尝试将两者放在一起时,会创建一个空的组合框。谁能告诉我这是为什么以及如何克服这个问题?

Thanks in advance, JW

提前致谢,JW

 Sub CreateComboBox1()
    'Creating ComboBox1:
    ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", _
                Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, _
                Height:=15).Select
    End Sub

    Sub PopulateComboBox1()
    'Populating ComboBox1
    Sheet1.ComboBox1.AddItem "Date", 0
    Sheet1.ComboBox1.AddItem "Player", 1
    Sheet1.ComboBox1.AddItem "Team", 2
    Sheet1.ComboBox1.AddItem "Goals", 3
    Sheet1.ComboBox1.AddItem "Number", 4
    End 

回答by Siddharth Rout

Try this

尝试这个

Sub CreateComboBox1()
    With ActiveSheet.OLEObjects.Add(ClassType:="Forms.ComboBox.1", _
                Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, _
                Height:=15)
        With .Object
            .AddItem "Date"
            .AddItem "Player"
            .AddItem "Team"
            .AddItem "Goals"
            .AddItem "Number"
        End With
    End With
End Sub