Excel VBA将多个Combobox值传递给dynamic数组

我想知道是否有一种方法将选定的多个combobox值添加到dynamic数组。 到目前为止,这是我的代码下面,目前我只能提交一个选定的Combobox值到数组列表。

Private Sub UserForm_Initialize() ComboBox1.AddItem "1" ComboBox1.AddItem "2" ComboBox1.AddItem "3" End Sub Private Sub CommandButton1_Click() Dim cmbbox(10) As String Dim i As Integer For i = LBound(cmbbox) To UBound(cmbbox) cmbbox(i) = ComboBox1.Value MsgBox cmbbox(i) Next i End Sub 

我想能够从combobox中select一个值,然后将该值传递到我的数组在0位置,然后如果从combobox中select另一个值,那么该值传递给我的数组1个职位等

这应该做的:

 For Each Item In ComboBox1.List If Not Item Then MsgBox Item End If Next 

编辑:我在这里错过了你的观点,还是你改变了你的问题? 根据我现在阅读的内容,每次按下commandbutton时,您都希望在数组的末尾添加combobox的值。 你应该这样做:

定义你的数组之外的数组(在最上面):

 Dim cmbbox() As Variant 

代码应该如下所示:

 Private Sub CommandButton1_Click() If Len(Join(cmbbox, "")) = 0 Then 'if your array is empty add the first value from combobox ReDim cmbbox(0) cmbbox(0) = ComboBox1.Value Else 'if your array is not empty redim your array and add value from combobox ReDim Preserve cmbbox(UBound(cmbbox) + 1) cmbbox(UBound(cmbbox)) = ComboBox1.Value End If MsgBox "Last Added Item : " & cmbbox(UBound(cmbbox)) End Sub 

正如@Tehscript所指出的那样,你之后的属性是.List ,它返回一个二维的,从零开始的数组:第一个维度是'行',第二个'列'。

从你的问题,似乎你想要一个特定的索引(或指数)从行维度。 如果你的ComboBox只有一列,那么第二维可以被硬编码为零。

一个For Each循环会没事的,但问题是它会遍历数组中的每一项而不是每一行。 因此,运行For [index]循环可能会更高效。 假设您需要ComboBox的第一个和第三个项目,那么代码片段将是:

 Dim i As Long Dim v As Variant v = ComboBox1.List For i = 0 To UBound(v, 1) If i = 0 Or i = 2 Then MsgBox v(i, 0) End If Next