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

时间:2016-06-18 18:46:35

标签: excel-vba combobox named-ranges vba excel

我有一个在UserForms中使用的ComboBox,它使用命名范围作为RowSource。

我的所有命名范围都来自VBA中Selection.CreateNames的Excel中的Create names from selections

以下是代码:

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

以下是我的工作表中的项目"测试" enter image description here

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

enter image description here

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

以下情况不会发生此问题:

  • 命名范围是根据列中的数据而不是行中的数据创建的
  • 我直接在工作表中创建下拉列表(使用Data validation)。

我能解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

您似乎遇到了Excel功能。

唯一的方法是使用VBA - 使用工作表激活功能或按钮 - 使用列表additem更新Rowsource

即使这样,除非在用户表单上使用了组合框,否则无效。

' 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
相关问题