Declaring and Using Object Variables

The variables you've learned so far are used to store data. Storing data is the main reason for using "normal" variables in your procedures. In addition to the normal variables that store data, there are special variables that refer to the Visual Basic objects. These variables are called object variables. Object variables don't store data. They store the location of the data. You can use them to reference databases, forms, and controls as well as objects created in other applications. Object variables are declared in a similar way as the variables you already know. The only difference is that after the As keyword you enter the type of object your variable will point to. For instance:

Dim myControl As Control

The statement above declares the object variable called myControl of type Control.

Dim frm As Form

This statement declares the object variable called frm of type Form.

You can use object variables to refer to objects of a generic type such as Application, Control, Form, or Report, or you can point your object variable to specific object types such as TextBox, ToggleButton, CheckBox, CommandButton, ListBox, OptionButton, Subform or Subreport, Label, BoundObjectFrame or UnboundObjectFrame, and so on. After declaring an object variable, you also have to assign a specific value to the object variable before you can use this variable in your procedure. You assign a value to the object variable by using the Set keyword. The Set keyword is then followed by the equals sign and the value that the variable refers to. For example:

Set myControl = Me!CompanyName

The above statement assigns a value to the object variable called myControl. This object variable will now point to the CompanyName control on the active form. If you omit the word Set, Visual Basic will display the error message "Run-time error 91: Object variable or With block variable not set."

Again, it's time to see a practical example. The HideControl procedure in Hands-On 3-8 below demonstrates the use of the object variables frm and myControl.

0 0

Post a comment