Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Fill listbox from combobox selected worksheets

0
  1. Good afternoon. I need to fill the listbox with the list on the worksheet when the worksheet is selected. My combobox works perfectly but I can't figure out my code why the list is not filling in the list box. This is the code I have.
  2. I added a second file which is the right file "Online Teach Excel  Help File.xlsm". I think it's to big so I'm going to only send the userform and code.
Option Explicit
Const Root As String = "PT-"

Private Sub Cb_Submit_Click()

Dim Picked As String, x As Long

' loop through lstSELpart

With Me.lstSELpart '1st listbox to fill
    For x = 0 To .ListCount - 1
        ' get Item# and Parts name (e.g.) from List
        If .Selected(x) = True Then
           Picked = Picked & .List(x, 0) & " " & .List(x, 1) & vbCrLf
        End If
    Next x
End With

' tell user
MsgBox "For Customer No. " & txtCustupdate.Text & ", you picked:" & vbCrLf & vbCrLf & Picked & vbCrLf & " parts for model " & cmbGunSel.Text
Unload Me


End Sub

Private Sub cmbGunSel_Change()

Dim Index As Long, Col As Long, Val As Variant, CT As Object

' do nothing if no model was picked
If Me.cmbGunSel.Value = "" Then Exit Sub

' clear previous list
Me.lstSELpart.Clear '1st listbox to fill

'do nothing if an invalid name was typed in
On Error Resume Next
If ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value).Name <> Root & Me.cmbGunSel.Value Then Exit Sub

' with chosen source
With ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value)

    ' populate  first list box with checked items only
    For Each CT In .Shapes
        If InStr(CT.Name, "Check Box") = 1 And CT.OLEFormat.Object.Value = 1 Then
            ' populate columns of lstGunOrder
            Me.lstSELpart.AddItem .Range(CT.TopLeftCell.Address).Offset(0, 1).Text
            Index = 1
            ' loop through columns of checked item
            For Col = 2 To 4
                Val = .Range(CT.TopLeftCell.Address).Offset(0, Col).Value
                ' format the currency column
                If Col = 4 Then Val = Format(Val, "$#,##0.00")
                Me.lstSELpart.List(Me.lstSELpart.ListCount - 1, Index) = Val
                ' increase the column index
                Index = Index + 1
            Next Col
        End If
    Next CT
    ' set up LB2 columns
    Me.lstSELpart.ColumnCount = 4
    Me.lstSELpart.ColumnWidths = "40;200;40;40"

End With

End Sub

Private Sub UserForm_Initialize()

Dim ws As Worksheet, CT As Shape

'populate Customer No.
frmGunParts.txtCustupdate.Text = frmForm.cboCustNo.Text

' loop through sheets and set data sources
For Each ws In ThisWorkbook.Worksheets
    ' check sheet name starts with root
    If InStr(ws.Name, Root) = 1 Then
        ' add name (less Root) to ComboBox list
        Me.cmbGunSel.AddItem Split(ws.Name, Root)(1)
    End If

Next ws

End Sub
Answer
Discuss

Discussion

DivineDar

Please see the second revision to (and thrid file with) my Answer below- it populates lists as seen on the PT- sheets and it gives you the option to show all parts or just those checked.
John_Ru (rep: 6142) Feb 15, '23 at 9:22 am
Add to Discussion

Answers

0
Selected Answer

Hi again Divinedar

Revised Answer 11 Feb 2023

The reason your listbox was not populating is that my original answer populated them only with pre-checked items on the "PT-" sheets (at your request I believe)- if nothing is ticked, the list will be empty. That's started with the bold bits in this :

Private Sub cmbGunSel_Change()

<< omitted code>>
' with chosen source
With ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value)

    ' populate  first list box with checked items only
    For Each CT In .Shapes
        If InStr(CT.Name, "Check Box") = 1 And CT.OLEFormat.Object.Value = 1 Then
<< omitted code>>

To demonstrate this, in the first revised attached file I've checked some items on sheet "PT-Colt_Gov_Model_MK_IV_80",  added your frmForm and other modules. Now if you click the button "ENTER/EDIT..." on the Main Database sheet, pick a Customer No. on the first form and click pale green button Select Products..., the second form will display. Select Colt_Gov_Model_MK_IV_80 from the dropdown ComboBox and the checked items on that sheet will be listed. 

If however you want all items to be listed (and check them in your form), the second file below (Online-Teach-Excel-Help-File listing all items v0_c.xlsm) does that. The (full) code has just the minor chnages in bold below:

Private Sub cmbGunSel_Change()

Dim Index As Long, Col As Long, Val As Variant, CT As Object

' do nothing if no model was picked
If Me.cmbGunSel.Value = "" Then Exit Sub

' clear previous list
Me.lstSELpart.Clear '1st listbox to fill

'do nothing if an invalid name was typed in
On Error Resume Next
If ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value).Name <> Root & Me.cmbGunSel.Value Then Exit Sub

' with chosen source
With ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value)

    ' populate  first list box with ALL checkbox items
    For Each CT In .Shapes
        If InStr(CT.Name, "Check Box") = 1 Then ' And CT.OLEFormat.Object.Value = 1 Then
            ' populate columns of lstGunOrder
            Me.lstSELpart.AddItem .Range(CT.TopLeftCell.Address).Offset(0, 1).Text
            Index = 1
            ' loop through columns of checked item
            For Col = 2 To 4
                Val = .Range(CT.TopLeftCell.Address).Offset(0, Col).Value
                ' format the currency column
                If Col = 4 Then Val = Format(Val, "$#,##0.00")
                Me.lstSELpart.List(Me.lstSELpart.ListCount - 1, Index) = Val
                ' increase the column index
                Index = Index + 1
            Next Col
        End If
    Next CT
    ' set up LB2 columns
    Me.lstSELpart.ColumnCount = 4
    Me.lstSELpart.ColumnWidths = "40;200;40;40"

End With

End Sub

Now you'll get a list of all parts for whatever item you choose.

Note: After a comment from you, I should point out that the checkboxes are in a Collection- the order they are added to the list is determined by their name/position in the Collection (not by their positions on the sheet. This means the 001 item will alswatys appear first etc. To show this, on the second and third "PT-" sheets, I sorted the item names in column C- now you will notice that the items appear in the same number order but with the "correct" item name. Now, when you change the model, the list will change.

I noticed that your ListBox lstSELpart has a label note saying "This will fill from the gun list worksheet and only select one part item at a time ..." so I set the MultiSelect property to 0 - fmMultiSelectSingle (and you get radio buttons against items).

Also I noticed that the Customer Number was not coming over from the first form so restored the line in bold (for the second form):

Private Sub UserForm_Initialize()

Dim ws As Worksheet, CT As Shape
'populate Customer No.
frmGunParts.txtCustupdate.Text = frmForm.cboCustNo.Text

<<existing code>>

Revision 13 February 2023

Given I'm not clear which way you are going with your lists, I've added a third file below which:

  1. creates lists based on how they appear on the "PT-" sheets
  2. allow the user to choose to list all items or only those checked for the item.

The latter is done using a new checkbox (named "CB_lstSELpart" and shown as "List only checked items" above the listbox on the second form. When then is clciked (to change state): if just acts as if the model had changed: 

Private Sub OptlstSELpart_Click()

Call cmbGunSel_Change

End Sub()

Call cmbGunSel_Change

End Sub

where that code is below and checks the state of that option button (with some significant changes shown in bold):

Private Sub cmbGunSel_Change()

Dim Index As Long, Col As Long, Val As Variant, CT As Object
Dim lRw As Long, Rw As Long


' do nothing if no model was picked
If Me.cmbGunSel.Value = "" Then Exit Sub

' clear previous list
Me.lstSELpart.Clear

'do nothing if an invalid name was typed in
On Error Resume Next
If ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value).Name <> Root & Me.cmbGunSel.Value Then Exit Sub

' with chosen source
With ThisWorkbook.Worksheets(Root & Me.cmbGunSel.Value)
    'determine last used row in B
    lRw = .Cells(.Rows.Count, 2).End(xlUp).Row
    ' loop down rows
    For Rw = 3 To lRw
        If IsEmpty(.Cells(Rw, 2)) = False Then
            Index = 0
            With .Cells(Rw, 1)
                ' populate the list based on the option
                If CB_lstSELpart.Value = False Then
                    ' add an item to the lstGunOrder list
                    Me.lstSELpart.AddItem .Offset(0, 1).Text
                    Index = 1

                    Else
                    ' loop through shapes to see if a checked one in on column A or the row
                    For Each CT In .Parent.Shapes
                        ' find if there's a checked box in this cell
                        If Not Intersect(.Range(CT.TopLeftCell.Address), .Cells(Rw, 1)) Is Nothing _
                            And InStr(CT.Name, "Check Box") = 1 _
                            And CT.OLEFormat.Object.Value = 1 _
                            Then
                                ' if checked add an item to the lstGunOrder list
                                Debug.Print CT.TopLeftCell.Address
                                Me.lstSELpart.AddItem .Offset(0, 1).Text
                                Index = 1
                        End If
                     Next CT
                End If

                ' only if an item was added, populate first four columns of list
                If Index = 1 Then
                    ' loop through next 3 columns and add to liost row
                    For Col = 2 To 4
                        Val = .Offset(0, Col).Value
                        ' format the currency column
                        If Col = 4 Then Val = Format(Val, "$#,##0.00")
                        'add to column
                        Me.lstSELpart.List(Me.lstSELpart.ListCount - 1, Index) = Val
                        ' increase the column index
                        Index = Index + 1
                    Next Col
                End If
            End With
        End If
    Next Rw
End With

' set up LB2 columns
Me.lstSELpart.ColumnCount = 4
Me.lstSELpart.ColumnWidths = "40;200;40;40"

End Sub

Note that it still polulates the list with values from columns B,C, D and E (even though the latter two aren't populated on your sheets and E might not hold a currency)

Hope this fixes things for you and gives you a good start to transferring the selections to other sheets or whatever.

Discuss

Discussion

Thanks for the help. If you take a look at the "frmGunParts" userform I changed it and it has 2 listboxes.  I replaced my code with the codes that you just sent me and it's still not working.  Can you open the file I sent you and go through the same process you just sent me and see if it fills the first listbox on the right side of the combobox. I checked the code and did 2 words files and did a comparison and it has the same codes. Do I need to  clear the 2nd listbox before it fills the first listbox?
Divinedar (rep: 20) Feb 10, '23 at 12:50 pm
Divinedar. Firstly, did you get my file working? (it worked fine for me).

Secondly, attaching the Helpfile (with screenshots).was no real help to me I'm afraid- for some reason I could not launch the forms ("... could not be found").

Please edit your original question and attach the working macro file with the revised forms and I'll try to fix your forms/my macros. It won't be today but hopefully I'll find time over the weekend.
John_Ru (rep: 6142) Feb 10, '23 at 1:15 pm
I added the correct excel file. No urgency
Divinedar (rep: 20) Feb 10, '23 at 6:11 pm
Thanks. Please see my revised Answer (particulary the second file). Hope this explains, is what you want and means to can move on (but not without selecting my Answer, please!).
John_Ru (rep: 6142) Feb 11, '23 at 7:07 am
Question:  I reorganized each worksheet to start with different items so to see when I select a worksheet I can tell which worksheet I've selected. Now when I select a worksheet it brings up the same list in the listbox.  Is this alphanumeric based on the ITEM column in each worksheet or is it no changing in the listbox?
Divinedar (rep: 20) Feb 11, '23 at 2:02 pm
Hi. I'm not near my PC but will check shortly. I assume you're referring to the second file 
John_Ru (rep: 6142) Feb 11, '23 at 2:23 pm
Darlene, please see the (explanatory) Note added to my Answer (and the renamed, revised second file).

If the limitation of adding to the list by checkbox is an issue (which I don;t think was in the original pre-checked version) then another method could be used.
John_Ru (rep: 6142) Feb 11, '23 at 3:31 pm
Sorry to be such a bother but now the file that you sent me "Online-Teach-Excel-Help-File corrected v0 a" it shows different items when you select a worksheet and then it shows nothing at time when you select a worksheet and it doesn't show the list as it is on the worksheet you select. Not urgent take your time and answer when you can. It's like it's not clearing the listbox and replacing it when another sheet is selected.
Divinedar (rep: 20) Feb 11, '23 at 4:42 pm
As I said, the first file (.. v0_a. xlsm) will list only items checked already on a given sheet. If no checkboxes are ticked, the list will be empty. I just reattached that file (to my Answer) with different checkboxes ticked on the three sheets (so the list will change as you change the ComboBox entry).

Perhaps I'm not explaining it well enough (and you don't answer my simple questions!) but to be honest I'm not sure if you understand or which approach you want to follow and I feel I'm wasting my time.
John_Ru (rep: 6142) Feb 11, '23 at 5:17 pm
Divinedar. I relented and have just revised my Answer to attach a third file which gives the option to turn on or off listing checked (or all) items. See text after "Revision 13 February 2023" and the third file.
John_Ru (rep: 6142) Feb 13, '23 at 8:40 am
Perfect thank you.
Divinedar (rep: 20) Feb 19, '23 at 9:31 am
Great! Thanks for selecting my Answer, Divinedar. 
John_Ru (rep: 6142) Feb 19, '23 at 1:07 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login