Search code examples
excelexcel-2013vba

Fill combobox based on filtered table data


In Excel 2013 I have a sheet containing a formatted table - Table1. The table has two columns, [Product Group] and [Product Name] :

enter image description here

Using VBA I have created a simple form containing two comboboxes, cbProductGroup and cbProductName.

cpProductGroup is filled using the RowSource property and an named ranged (=ProductGroupName). What I need is cbProductName only to be filled with product names matching the product group from cbProductGroup, for instance choosing "Laptop" in cbProductGroup should only produce a dropdown list containing the two Lenovo laptops.

Is this achievable somehow?

EDIT 17-04-2015 SOLVED:

I solved the problem using the change event of the cbProductGroup and adding the following code:

Private Sub cbProductGroup_Change()

    Me.cbProductName.Clear

    Dim lastRow As Long
    Dim shtInventory As Worksheet
    Set shtInventory = Sheets("Inventory")

    With shtInventory

        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        For i = 6 To lastRow
            If Me.cbProductGroup = .Cells(i, "A") Then
                Me.cbProductName.AddItem .Cells(i, "C")
            End If
        Next
    End With

Thank you all for providing valuable input and suggestions.


Solution

  • Yes, you want to empty then reload the CBProductName triggered by the onChange event of the cbProductGroup control. Google the code for using the combobox.add method to assign the values from the second column. You can also load the column 2 list to a collection to prevent loading duplicates.