I am trying to figure out the proper code for populating a listbox based on a selection from a second listbox. I will explain my question the best I can. I have one worksheet with two columns populated like this.
(COLUMN A) (COLUMN B) PART NUMBER: LOCATION: PART A LOC1,LOC7,LOC12,LOC21 PART B LOC2,LOC8,LOC13,LOC22 PART C LOC6,LOC9,LOC18,LOC20
I want to be able to populate ListBox1 with the “PART NUMBER” column and when I click on “PART A” I get just a list of items for location from (Column B) in ListBox2. I hope this makes sense and someone can help me out. Thank you in advance.
To populate my ListBox:
Dim rngName As Range Dim ws As Worksheet Dim i As Integer Set ws = Worksheets("Sheet2") For i = 1 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row Step 1 If ws.Cells(i, 1).Value <> vbNullString Then Me.LstPartNum.AddItem ws.Cells(i, 1).Value Next i
To Test populate and split by commas:
UserForm1.LstPartNum.List = Split("LOC1,LOC7,LOC12,LOC21", ",")
In the change event of the part number combobox do something like this.
Dim ws As Excel.Worksheet Dim lRow As Long Set ws = Worksheets("Sheet2") lRow = 1 'Loop through the rows Do While lRow <= ws.UsedRange.Rows.count 'Check if Column A has the value of the selected part number. If ws.Range("A" & lRow).Value = LstPartNum.Text Then UserForm1.LstLocation.Clear 'Load the locations UserForm1.LstLocation.List = Split(ws.Range("B" & lRow).Value, ",") Exit Do End If lRow = lRow + 1 Loop
If your UserForm1.LstPartNum.List = Split() does not work to load the list, here is code to loop the split array.
Dim szLocs() As String Dim i as integer szLocs= Split(ws.Range("B" & lRow).Value, ",") i = 0 'Loop though each token Do While i <= UBound(szPieces) UserForm1.LstPartNum.Additem szPieces(i) i = i + 1 Loop