2

Here is my String array with a list of listbox names...

Public ListOfBoxes As String() = {"lstWords02", "lstWords03", "lstWords04", "lstWords05", _
                                  "lstWords06", "lstWords07", "lstWords08", "lstWords09", _
                                  "lstWords10", "lstWords11", "lstWords12", "lstWords13", _
                                  "lstWords14", "lstWords15", "lstWords16", "lstWords17", _
                                  "lstWords18"}

I would like to loop through each of the listboxes and run some code. my attempt below fails because lbx is a string, not a listbox.

       For Each lbx As String In ListOfBoxes
           lbx.Items.Add(SomeStringVariable)
       Next

Any Ideas? Any help will be greatly appreciated. -Cam

0

2 Answers 2

1

You can use the name of the listboxes directly in the array like this.

Public ListOfBoxes As ListBox() = {lstWords02, lstWords03, lstWords04, lstWords05}

Then loop over the array like this

For Each lbx As ListBox In ListOfBoxes
   lbx.Items.Add(SomeStringVariable)   
Next

If you still want to use the names of the listboxes, try this

Public ListOfBoxes As String = {"lstWords02", "lstWords03", "lstWords04", "lstWords05"}

For Each item As String In ListOfBoxes
    Ctype(Controls.Find(item, True)(0), ListBox).Items.Add(SomeStringVariable)
Next

Controls.Find returns an array of all the controls with the specified name. In the example I gave above, I assumed each control on the form has unique names. You can adjust the code as per requirements.

Sign up to request clarification or add additional context in comments.

Comments

0
by your ref code "lbx.Items.Add(SomeStringVariable)" is using for add item in list.




Public ListOfBoxes As String() = {"lstWords02", "lstWords03", "lstWords04", "lstWords05", _
                                          "lstWords06", "lstWords07", "lstWords08", "lstWords09", _
                                          "lstWords10", "lstWords11", "lstWords12", "lstWords13", _
                                          "lstWords14", "lstWords15", "lstWords16", "lstWords17", _
                                          "lstWords18"}
  For Each lbx As String In ListOfBoxes
            Listbox.Items.Add(lbx)
        Next

1 Comment

In your For Each you are referring to the class ListBox. You need an instance of the class to refer to. The OP doesn't want to add the names of list boxes to some other list box. This code doesn't make much sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.