具有动态选择列表的 ActiveX 组合框

ActiveX combo box with dynamically-chosen list

我在看这个问题:How to create and populate ActiveX combo box

我想知道,当项目列表来自一个范围时如何实现以及如何指定列表应该放在哪个单元格中。

此外,如果有来自两个不同工作表的一系列值会更好。

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

我稍微调整了你的代码以清理它。避免使用 ActiveSheet,而是使用对您感兴趣的工作表的显式引用。您还应该将对象存储到变量中:

Option Explicit

Sub CreateComboBox1()

Dim sht As Worksheet
Dim cb As ComboBox
Dim sourceRange As Range
Set sht = ThisWorkbook.Worksheets("Name of your worksheet")
Set sourceRange = sht.Range("A1:A10") 'example source range

Set cb = sht.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, Height:=15).Object
cb.List = sourceRange.Value

End Sub

基本上你可以使用.List 属性来指定源范围。

另一种方法是使用 For-Each 循环,遍历要添加到列表中的项目。这样您就可以将来自不同工作表的两个不同范围的项目添加到列表中:

Option Explicit

Sub CreateComboBox1()
Dim cell As Range
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim cb As ComboBox
Dim sourceRange1 As Range
Dim sourceRange2 As Range

Set sht1 = ThisWorkbook.Worksheets("Name of your worksheet 1")
Set sht2 = ThisWorkbook.Worksheets("Name of your worksheet 2")
Set sourceRange1 = sht1.Range("A1:A10")
Set sourceRange2 = sht2.Range("A1:A10")

Set cb = sht1.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, DisplayAsIcon:=False, Left:=50, Top:=80, Width:=100, Height:=15).Object

For Each cell In sourceRange1
    cb.AddItem cell.Value
Next cell
For Each cell In sourceRange2
    cb.AddItem cell.Value
Next cell

End Sub