如果您不介意使用 Form Control ComboBox 代替 ActiveX,这里是我刚刚编写的一个示例。我使用月份而不是名称,因为我不知道您要使用的名称。概念是一样的。
它在代码中添加月份作为列表项,尽管您可以使用一组值和一个循环来代替。为了简单地演示以编程方式将组合框添加到单元格,我只是硬编码了 12 个月。
另外,为了示例,我只填充了第 2 到 20 行。
测试:
Sub addComboBoxes()
Dim sheet As String
Dim newName As String
Dim lRow As Long
'Dim lastRow As Long 'Not using for this example. Worth keeping in mind the option.
sheet = "Sheet1" 'Set Sheet Name
'lastRow = Sheets(sheet).Range("A" & Rows.Count).End(xlUp).row
For lRow = 2 To 20 'Choose Row Limitations, perhaps 2 To lastRow
newName = "cmbAuto" & lRow
Set cmbMonthRow = Sheets(sheet).Shapes.AddFormControl _
(xlDropDown, Left:=Cells(1, 1).Left, Top:=Cells(lRow, 1).Top, Width:=60, Height:=15)
With cmbMonthRow
.ControlFormat.LinkedCell = "A" & lRow
.ControlFormat.AddItem "January", 1
.ControlFormat.AddItem "February", 2
.ControlFormat.AddItem "March", 3
.ControlFormat.AddItem "April", 4
.ControlFormat.AddItem "May", 5
.ControlFormat.AddItem "June", 6
.ControlFormat.AddItem "July", 7
.ControlFormat.AddItem "August", 8
.ControlFormat.AddItem "September", 9
.ControlFormat.AddItem "October", 10
.ControlFormat.AddItem "November", 11
.ControlFormat.AddItem "December", 12
.ControlFormat.DropDownLines = 12
.Name = newName
End With
Next lRow
End Sub
注意:
链接的单元格返回选择的索引号。您可以在值更改时设置一个事件,但在提供的示例中,linkedCell 属性很好。
在这个例子中,我使用了几个月,因为它返回索引,所以我将值放在组合框后面。我包含了一个屏幕截图来演示这一点,并让列宽足够宽以查看对象后面单元格的值。您当然可以将列宽结束在组合框的末尾。
在 E 列的一个单元格中,我有一个使用链接单元格值的公式:
=IF(A2="","",TEXT(A2*29,"mmmm"))
这将返回下拉菜单的月份名称。没有它,工作表上将没有任何内容真正代表下拉菜单所做的选择。
链接:
Office Support: Add a ListBox or ComboBox control to a Worksheet.
Here is an example of a question 我最近回答了 使用 UserForm 来做几乎相同的事情,而不是工作表中的对象,或者在这种情况下工作表中的许多对象。这就是为什么我更喜欢使用 UserForms。您将有一个下拉列表,当更改时,代码会找到要操作的适当单元格,而不是每一行一个。