Export (0) Print
Expand All

Object Variables

In addition to storing values, a variable can refer to an object. You assign an object to a variable for the same reasons you assign any value to a variable:

  • A variable name is often shorter and easier to remember than the full path of methods or properties necessary to access the object itself.
  • Using a variable that refers to an object is more efficient than repeatedly accessing the object itself through the necessary methods or properties.
  • You can change a variable to refer to other objects while your code is running.

You can use object variables to shorten the code you have to type. For example, you might have a code segment like the following:

' Assume Me is a valid Form, or replace Me with a valid Form.
Me.Activate()   ' Make this the active form.
Me.ActiveControl = Label1   ' Make some valid control the active control.
' ...
Me.ActiveForm.ActiveControl.Text = "Test"
Me.ActiveForm.ActiveControl.Location = New Point(100, 100)

You can shorten this code, and speed up execution, if you use an object variable for the control. You should declare the object variable with the specific class that you intend to assign to it (Control in the following example). Once you assign an object to the variable, you can treat it exactly the same as you do the object to which it refers. You can set or return the properties of the object or use any of its methods, as shown in the following example:

Dim ctrlBal As Control  ' Must declare to be of class Control.
' ...
ctrlBal = Me.ActiveForm.ActiveControl
ctrlBal.Text = "Test"
ctrlBal.Location = New Point(100, 100)

In This Section

Object Variable Declaration
Discusses declaring object variables and choosing the class you declare them to be.
Object Variable Assignment
Describes how to assign objects to object variables, and combine assignments and declarations.
Object Variable Values
Describes how to return information about what an object variable refers to.

Related Sections

Variable Declaration
Describes how to specify variable names and characteristics, including which type of data the variable can contain.
© 2014 Microsoft