Variables

Objects

You will find that quite often you need to refer to the same object a number of times. However, if you are refererring to that object using a property that will change, such as frmMain.ActiveForm, once the active form changes, you cannot refer to the object any more.

In order to be able to do this, you can assign a variable to it. You do this in the same way as any other variable, except that you need to use the Set statment before the assignment:

Set ObjectName = Object

You also need to declare the variable as an object:

Dim ObjectName As Object

On occasions, you will know that the object that the variable will point to will always be a form, or a text box etc. If this is the case, you can declare the object as a text box. Visual Basic will create an error when you try to assign a different object to it. To access the objects properties, you simply use the variable name in place of the object:

Set objForm As Form1
' Sets Form1's Caption
objForm.Caption = "hello"

The following code assigns objForm to the ActiveForm in the MDI window (called MDIMain). You will notice that even if the ActiveForm property changes, the variable will still point to the same object:

Dim objForm As Form
' Assign Form
Set objForm = MDIMain.ActiveForm
' Set the caption
objForm.Caption = "Welcome"
' Activate another form
Form1.SetFocus
' Change the old active forms back colour
objForm.BackColor = vbRed
' Activate the old form
objForm.SetFocus

Once you have finished using an object in your code, you should remove the reference to the object. You can do this using the Nothing keyword. The following code sets objForm to refer to Nothing.

Set objForm = Nothing

If you ever try to access a variable that is an object when no object is assigned to it, you will get a run time error:

Err 91
Object variable or With block variable not set

You must always assign an object to the variable before you can use it.

You might also like...

Comments

About the author

James Crowley

James Crowley United Kingdom

James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audien...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra