使用For循环填充Combobox

时间:2016-11-23 10:52:09

标签: excel vba excel-vba for-loop combobox

对于一个项目,我想用一个可变数量的选项填充Userform上的Combobox。期权金额取决于表格中先前给出的金额。用户将输入一个值并为所有这些值指定名称。可能只有2个名字,但也可能是例如10个。

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

  

编译错误:预期的函数或变量

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找到它。

2 个答案:

答案 0 :(得分:4)

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

.AddItem Sheet2.Cells(5, col)

答案 1 :(得分:1)

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

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

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