我有一个在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
Name manager
告诉我我的所有名字都是正确的(即他们都列出了正确的元素):
问题:只有第一个元素显示在ComboBox中。
以下情况不会发生此问题:
Data validation
)。 我能解决这个问题吗?
答案 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