简体   繁体   中英

VBA Excel Adding Range With Dynamic Size To Combobox List

I have a range within the workbook that I'd like to set to the list of items in a Combobox from one of my Userforms. The issue is the Range can be any size. I currently handle the zero case by exiting the Sub , but when there's only one element in the range.

When there's one element, instead of returning an array of elements, it only returns a single String element and the listbox gives me an error: `Run-time error '381': Could not set the List property. Invalid property array index'. Is there anyway to handle this besides creating an exception for the case where there's only one element?

Here's the code: Edit: Fixed program to accurately represent problem.

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

解决方案同样的问题

One approach is to use named range and RowSource property of combobox.

Define a named range :

在此处输入图片说明

Then simply set the rowsource

Option Explicit

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

Going by your approach, use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM