last day (14 days later) » 

4:25 PM
0
Q: Excel VBA Add Items to Dynamically Created ComboBox

SanyaI'm dynamically creating comboboxes in my userform and I want to add the same items to every combobox on the form. I created a collection of the items (queried from sql statement from and Access DB). Then after I create the combobox object, I performed a for each statement in every item inside t...

 
I just tested your code in a new userform and a customized collection. Your code works for me.
 
Hmm...let me add a little more code (i thought it wasn't affecting it).
 
Where are you running the code from?
 
That sub is being run from a different form. I just added the rest of my code that calls the new form to be shown. Is that why the comboboxes aren't populating?
 
Nope. It still works for me :)
 
4:25 PM
...weird...I'm lost now :)
 
Put a breakpoint on the line xSel.AddItem sItem and see if the code reaches there?
 
Yes it did reach there. And it reached afterwards. The Form shows, and it shows the comboboxes, but they are empty...
 
Hi. Open a new excel file and add two userforms to it. In userform1, add a command button and put this code there. run it. Do you see combobox populated in the 2nd form?
Private Sub CommandButton1_Click()
    Dim col As New Collection, itm As Variant
    Dim xSel As Object

    col.Add "1"
    col.Add "2"
    col.Add "3"
    col.Add "4"

    Set xSel = UserForm2.Controls.Add("Forms.ComboBox.1", "Sid", True)

    With xSel
        .Width = 120
        .Left = 384
        .Height = 18
        .Top = 44

        For Each itm In col
            .AddItem itm
        Next itm
    End With

    UserForm2.Show
    Set xSel = Nothing
End Sub
 
So right underneath the For Each sItem - i added a MsgBox(sItem) and it does not execute. I added a MsgBox("hello") right before the For Each and it did execute
Shit i have to go. I'm sorry!
 
so that means the sItem is empty
 
4:29 PM
?...
 
you collection has 20 blank items
 
this is interesting. Let me test that when I get back. Thank you so much!
 
Change this line selectItems.Add rs!DESCRIP to If len(trim(rs!DESCRIP))<>0 then selectItems.Add rs!DESCRIP Now check what is the count of the collection
I have posted an answer with an explanation. Have a look. Gotta go... Hope it helps
 
 
3 hours later…
7:37 PM
AHHHHHHH! I finally got it. So stupid of me. You helped me figure it out though. I changed the line to: selectItems.Add CStr(rs!DESCRIP)
It wasn't recognizing my values as string so they were empty. Thank you so much!!!
 

last day (14 days later) »