从表格填充组合框

时间:2019-06-08 07:16:14

标签: excel vba combobox

我正在尝试填充一个两列组合框,该组合框是我在用户表单中使用的,它从表中获取数据。组合列表必须是动态的,因此当其他项目添加到表中时,它们将被馈送到组合框中。

我正在使用事件之前双击来初始化代码,但是表单尚未初始化。表格已使用更简单的方法进行了初始化,该方法从固定范围内获取数据-表格让我失望。

我已经分别运行代码,并且可以看到组合列表数组已填充。

我已经尝试过重新组合列表数组,但是出现一个错误,表明它已经变暗了。

我怀疑我使代码过于复杂,无法从表中填充组合框。

Private Sub UserForm_Initialize()

'Populate Combo list values

ComboBox1.ColumnCount = 2

Dim myTable As ListObject
Dim myArray As Variant
Dim x As Long, NumItems As Long

Set myTable = Worksheets("RefTable").ListObjects("AccountTable")

myArray = myTable.DataBodyRange
NumItems = UBound(myArray)

Dim ComboList(1 To 20, 1 To 2) As String

Dim i As Integer, j As Integer

For i = 1 To 20
    For j = 1 To 2
       ComboList(i, j) = myArray(i, j)
    Next j
Next i

ComboBox1.List = ComboList

End Sub

该表单完全不显示!

1 个答案:

答案 0 :(得分:1)

您与您的代码非常接近,我刚刚对数组进行了更改:

Private Sub UserForm_Initialize()

'Populate Combo list values

ComboBox1.ColumnCount = 2

Dim myTable As ListObject
Dim myArray As Variant
Dim i As Long, j As Long

Set myTable = Worksheets("RefTable").ListObjects("AccountTable")

myArray = myTable.DataBodyRange

Dim ComboList() As String: ReDim ComboList(1 To UBound(myArray), 1 To UBound(myArray, 2))

For i = LBound(ComboList) To UBound(ComboList)
    For j = LBound(ComboList, 2) To UBound(ComboList, 2)
       ComboList(i, j) = myArray(i, j)
    Next j
Next i

ComboBox1.List = ComboList

End Sub

或者,您可以只使用第一个数组:

Private Sub UserForm_Initialize()

'Populate Combo list values

ComboBox1.ColumnCount = 2

Dim myTable As ListObject
Dim myArray As Variant

Set myTable = Worksheets("RefTable").ListObjects("AccountTable")

myArray = myTable.DataBodyRange

ComboBox1.List = myArray

End Sub