我想知道是否有办法将选定的多个组合框值添加到动态数组中。到目前为止,这是我下面的代码,目前我只能将一个选定的 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
我希望能够从组合框中选择一个值,然后该值在 0 位置传递给我的数组,然后如果从组合框中选择另一个值,则将该值传递给我的数组1个职位等...
最佳答案
这应该这样做:
For Each Item In ComboBox1.List
If Not Item Then
MsgBox Item
End If
Next
编辑:我在这里错过了你的观点,还是你改变了你的问题?根据我现在阅读的内容,每次点击命令按钮时,您都希望在数组末尾附加组合框值。您应该执行以下操作:
在您的 sub 之外定义您的数组(在最顶部):
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
关于arrays - Excel VBA将多个组合框值传递给动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621942/