Use VB6's TypeOf keyword to work with controls

Are you looking for a way to make a change to all the controls of a certain type on a VB6 form? Then find out why you should take advantage of the TypeOf keyword for these types of development tasks.

There may be times when you want to do something with all controls of a certain type on a VB6 form. For example, you might want to change the foreground color of all Text Box controls to red.

It's easy to loop through all the controls on a form using the Form.Controls collection. But how do you distinguish one type of control, such as a Text Box, from others, such as Radio Buttons?

All you have to do is enter VB6's TypeOf keyword. When you use it in an If statement, it returns True if the referenced control is of the specified type; it returns False if the referenced control is not of the specified type.

In the following example, the code changes the forecolor of all Text Box controls on Form1 to red:

Dim c As Control

For Each c In Form1.Controls
    If TypeOf c Is TextBox Then
        c.ForeColor = vbRed
    End If

You'll also find this approach useful for many other tasks, such as unchecking all of the CheckBox controls.

Miss a tip?

Check out the Visual Basic archive, and catch up on the most recent editions of Peter Aitken's column.

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

Editor's Picks

Free Newsletters, In your Inbox