Search code examples
excelvba

Userform ComboBox dropdown list from multiple ranges


I have a userform where a ComboBox should already be populated with values from three different excel worksheets. I have no trouble creating a dropdown list using the .List property of the combobox when it is one range, but this has me completely stumped. A few of my various attempts below:

Private Sub Userform_Initialize 
Dim A as Variant
Dim B as Variant
A = Worksheets("SheetA").Range("A:A")
B = Worksheets("SheetB").Range("A:A")
With ComboBox1
ComboBox1.List = A + B
End With
End Sub

This generates a type mismatch error

ComboBox1.List = Array(A, B)

This generates an empty dropdown list

I have also tried defining A and B as ranges to try to use Union on them, but it seems they need to be variants for the

A = Worksheets("SheetA").Range("A:A")
B = Worksheets("SheetB").Range("A:A")

lines to work


Solution

  • This code will list the columns A in SheetA and SheetB in ComboBox1

    Sample data as shown below;

    Column "A" in SheetA Column "A" in SheetB
    a1 b1
    a2 b2
    a3 b3
    a4 b4
    a5 b5
    a6 b6
    a7 b7
    a8 b8
    a9 b9
    a10 b10
    a11 b11
    a12 b12
    a13 b13
    a14
    a15
    a16
    a17

    .

    Private Sub UserForm_Initialize()
        Dim arr1, arr2, arr3
        
        arr1 = Application.Transpose(Sheets("SheetA").Range("A1:A" & Sheets("SheetA").Range("A" & Rows.Count).End(xlUp).Row))
        arr2 = Application.Transpose(Sheets("SheetB").Range("A1:A" & Sheets("SheetB").Range("A" & Rows.Count).End(xlUp).Row))
        
        arr3 = Split(Join(arr1, ",") & "," & Join(arr2, ","), ",")
        
        ComboBox1.List = arr3
    End Sub
    

    .

    enter image description here