在行中命名范围时,在 ComboBox 中使用命名范围作为 RowSource 失败

Using named range as RowSource in ComboBox failing when named range in row

我有在用户窗体中使用的组合框,它使用命名范围作为 RowSource。

我所有的命名范围都是从 Create names from selections in Excel of Selection.CreateNames in VBA.

代码如下:

Private Sub UserForm_Initialize()

Dim row As Integer 'In the example, row = 1, but in real life I'll want to create many named ranges from items listed as rows.
Dim lastCol As Integer 'Needed because my named ranges will vary in length
Dim ws As Worksheet 'Where my data is

Set ws = Worksheets("tests")

row = 1
lastCol = ws.Cells(row, Columns.Count).End(xlToLeft).Column

ws.Range(Cells(row, 1), Cells(row, lastCol)).Select

'Create the named range
Selection.CreateNames Left:=True

'Assign the named range (via its name, found in column 1) to the ComboBox RowSource
ComboBoxSampleForSO.RowSource = ws.Cells(row, 1).Value

End Sub

这是我的 Sheet "tests" 中的项目

Name manager 告诉我所有的名字都是正确的(即它们都列出了正确的元素):

问题:ComboBox 中只显示第一个元素。

在以下情况下不会出现此问题:

我可以解决这个问题吗?

您似乎 运行 进入了 Excel 功能。

执行此操作的唯一方法是使用 VBA - 使用工作表激活函数或按钮 - 使用列表 additem

更新行源

即便如此,除非组合框在用户窗体上,否则这将不起作用。

' Substitute your range name here
Const HORIZ_RANGE   As String = "Row1Range"

Dim varListVals As Variant
Dim intItem As Integer

' Returns two dimension array from your range of cells
varListVals = Application.Range(HORIZ_RANGE).Cells

ComboBox1.Clear

For intItem = LBound(varListVals, 2) To UBound(varListVals, 2)
    ComboBox1.AddItem varListVals(1, intItem)
Next intItem