使用For循环来填充combobox

对于一个项目,我想用一个可变数量的选项填充用户窗体上的combobox。 选项的数量取决于表单中前面给出的数量。 用户将input一个值并为所有这些值分配名称。 可能只有2个名字,但也可能有10个名字。

我希望Combobox使用给定的值(名称数量)来填充存储在不同位置的名称。 我目前的代码如下,但它给了我下面的编译错误,然后select.AddItem部分作为错误的来源..

编译错误:期望的函数或variables

 Private Sub UserForm_Initialize() 'Sheet1.Range("A1") contains the value for the amount of names If Sheet1.Range("A1") = 0 Or Sheet1.Range("A1") = "" Then 'Do Nothing Else With ComboBox1 For n = 1 To Sheet1.Range("A1") 'col determines the column in which the names are found 'The first name is in column 2, the next in column 10, etc. col = 2 + 8 * (n - 1) .AddItem = Sheet2.Cells(5, col) Next End With End If End Sub 

希望我的问题很清楚。 我有这样的感觉,我已经非常接近答案,但我无法使用Google在任何地方find它。

.Additem是一种方法,而不是您可以设置的属性。 你必须提供该项目作为参数,即

 .AddItem Sheet2.Cells(5, col) 

作为替代方法,您可以使用ComboBox对象的List属性,并通过如下的数组填充它:

 Private Sub UserForm_Initialize() With Sheet1.Range("A1") 'reference the cell that contains the value for the amount of names If .Value > 0 Then Me.ComboBox1.List = GetValues(.Value) '<--| fill ComboBox via its 'List' property passing it the array returned by GetValues() function End With End Sub Function GetValues(nCols As Long) As Variant Dim n As Long ReDim vals(1 To nCols) As Variant '<--| size the array to match the amount of names passed in For n = 1 To nCols vals(n) = Sheet2.Cells(5, 2 + 8 * (n - 1)) '<--| fill the array: the first name is in column 2, the next in column 10, etc. Next GetValues = vals '<--| return the filled array End Function 

这也将使你的代码更“模块化”