Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA loop thru consecutively numbered names

Tags:

for-loop

vba

I know how to loop through numbers in parentheses like

For i = 0 To (ComboBox4.ListCount - 1)
If ComboBox4.Value = ComboBox4.List(i) Then inList = True
Next i

But how can I loop through numbers that are not in parentheses? Like consecutively numbered names:

Me.ComboBox1.Value = ""
Me.ComboBox2.Value = ""
Me.ComboBox3.Value = ""

I tried:

for i=1 to 3
"Me.ComboBox"&i&".Value" = ""
next i

But that does not work. How should it look like?

like image 622
Luitpold Wienerle Avatar asked Aug 31 '26 18:08

Luitpold Wienerle


1 Answers

You'd use the Controls collection.

E.g.:

Me.Controls("ComboBox" & i)  

Edit:
As the controls on a form are part of a collection you can also iterate through the collection pulling each control in turn:

    Private Sub UserForm_Initialize()

        Dim ctl As Control

        For Each ctl In Me.Controls
            If TypeOf ctl Is MSFORMS.ComboBox Then
'           If TypeName(ctl) = "ComboBox" Then
                MsgBox ctl.Name
            End If
        Next ctl

    End Sub

I've added two ways to identify the control type as suggested by @CallumDA.

Microsoft writes:

  • The TypeName function returns a string and is the best choice when you need to store or display the class name of an object.
  • The TypeOf...Is operator is the best choice for testing an object's type, because it is much faster than an equivalent string comparison using TypeName.
like image 189
Darren Bartrup-Cook Avatar answered Sep 04 '26 08:09

Darren Bartrup-Cook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!