Search code examples
excelvbauserform

Excel VBA Userform Combobox - Load Multiple Columns Values


I am using this code to load values of used range in column C. This works fine, however I need to also load values in columns E and G inside the combobox separated by a "-" so for example each combobox entry will read "Row 1 Col C value - Row 1 Col E value - Row 1 Col G value".

 Private Sub UserForm_Initialize()
    Dim lastrow As Long
    Dim ws As Worksheet
    ws = mysheet
        lastrow = ws.Columns("C").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        tag_combo.List = ws.Range("C" & ws.Range("start_row_pu").Row + 1 & ":" & "C" & lastrow).Value2
    End If

    End Sub

Solution

  • Example call joining column values

    As close as possible to your original post you can read all values into a 1-based 2-dim temporary array, join 1st, 3rd and 5th column values by & and assign them back to the comboboxe's .List property:

    Private Sub UserForm_Initialize()
        Dim ws As Worksheet
        Set ws = Worksheets("Tabelle1")
        Dim lastrow As Long, i As Long
            lastrow = ws.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
        Dim v       As Variant
            v = ws.Range("C" & ws.Range("start_row_pu").Row + 1 & ":" & "G" & lastrow).Value2
    
            For i = LBound(v) To UBound(v)            ' join column values C, E, G
                v(i, 1) = v(i, 1) & " - " & v(i, 3) & " - " & v(i, 5)
            Next i
            ReDim Preserve v(1 to Ubound(v), 1 to 1)   ' redimension temporary array to 1 column 
            ComboBox1.List = v                         ' assign array back to .List property
    End Sub
    

    Further notes due to question in comment

    After having assigned range data (e.g. C2:G4711) to a 2-dimensioned 1-based variant array v you have to loop through the 1-based array data now, where

    • LBound(v) always starts from "row" 1 in a 1-based array (so callede lower boundary) and
    • UBound(v) returns the upper boundary, e.g. 4710 (=4711 - 2 + 1 as starting from the second row) "rows";

    now you refer to column C data in the original range via "column" index 1 of the variant array, i.e. v(i, 1), to E via index 3: v(i, 3), to G via index 5: v(i, 5). The above example joins the 1st, the 3rd and the 5th value in the array column items via the & connector and assigns the resulting string back to the first array column thus (over)writing the already read in data of range column C.

    Eventually you have to redimension the original 5 array columns to only one in order to represent your wanted data row connected now by " - ".