VBA Excel添加dynamic大小的范围到combobox列表

我在工作簿中有一个范围,我想从我的一个用户窗体设置到Combobox中的项目列表。 问题是Range可以是任何大小。 我目前通过退出Sub处理零案件,但是当范围中只有一个元素时。

当有一个元素,而不是返回一个数组元素,它只返回一个单一的String元素和列表框给我一个错误:运行时错误'381':无法设置List属性。 无效的属性数组索引'。 除了为只有一个元素的情况创build一个例外之外,有没有办法处理这个问题呢?

这里是代码:编辑:修正程序来准确表示问题。

 Private Sub UserForm_Activate() Dim formList As Variant Dim lastRow As Long lastRow = getLastRowInCol(Sheets("HiddenVariables"), "B") If lastRow = 0 Or lastRow = 1 Then Exit Sub formList = Sheets("HiddenVariables").Range("B2:B" & lastRow).value 'If lastRow =2 then run-time error 381 is thrown Me.ComboBox.list = formList End Sub 

与解决方案相同的问题

一种方法是使用ComboBox的命名范围和RowSource属性。

定义一个命名范围:

在这里输入图像说明

然后简单地设置行来源

 Option Explicit Private Sub UserForm_Activate() Me.ComboBox1.RowSource = "Sheet1!Combo_Source" End Sub 

按照你的方法,使用这个:

 If IsArray(formList) Then Me.ComboBox1.List = formList Else Me.ComboBox1.List = Split(formList, "") '/Converts str to arr on the fly. End If