2016-11-23 35 views
0

プロジェクトのために、さまざまなオプションのオプションを持つUserformでComboboxを埋めたいと思います。オプションの額は、シートの前に記載された金額に依存します。ユーザーは値を入力し、これらの値すべてに名前を割り当てます。名前は2つしかないかもしれませんが、例えば10があるかもしれません。Forループを使用してComboboxを埋めてください

私は、コンボボックスが与えられた値(名前の量)を使用して、別の場所に保存されている名前で自分自身を埋めるようにしたいと思います。私の現在のコードを以下に示すが、それは私に、次のコンパイルエラーを与えるし、エラーの原因として.AddItem部分を選択します。..

Compile error: Expected Function or variable

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を使って見つけることができませんでした。

答えて

4

.Additemは設定可能なプロパティではなく、メソッドです。あなたはすなわち

.AddItem Sheet2.Cells(5, col) 
+0

ありがとうございました! – Peleus

1

あなたが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 

あなたのコードはもっと「モジュラー」

関連する問題