VBA See TextBox or Label Using Loop

I am trying to replace the following:

txt1.Text = ""
txt2.Text = ""
txt3.Text = ""
txt4.text = ""
...continues for quite awhile

WITH

Dim cCont As Control

For Each cCont In Me.Controls

If TypeName(cCont) = "TextBox" Then
'reset textbox value
   ???
End If
Next cCont

How can I reference a text field using a common control?

+3
source share
1 answer

You already have your control in cCont.

Dim cCont As Control

For Each cCont In Me.Controls
  If TypeOf cCont Is MSForms.TextBox Then
    cCont.Text = "hi"
    MsgBox cCont.Name
  End If
Next

If you are confused by the fact that you did not get the property Textfrom IntelliSense, just add Controlto the more derived type:

Dim cCont As Control

For Each cCont In Me.Controls
  If TypeOf cCont Is MSForms.TextBox Then
    Dim cText As MSForms.TextBox

    Set cText = cCont

    cText.Text = "hi"
    MsgBox cText.Name
  End If
Next

This will use early binding instead of late binding and you will get your code suggestions.

+7
source

All Articles