Article ID: 147665
Article Last Modified on 7/1/2004
Dim MyFormObject1 As Form1 Dim MyFormObject2 As Form2 Set MyFormObject1 = New Form1 Set MyFormObject2 = New Form2 MyFormObject1.Show MyFormObject2.ShowWhile this style of coding has many advantages, Visual Basic also does some work behind the scenes to allow the manipulation of a form without previously declaring a variable to hold the reference to that form. Visual Basic does the equivalent of automatically declaring an object variable with the same name as each form class. When a program with a startup form begins, or the first time a property or method of a form class is called, Visual Basic creates a form object from the form class and assigns it to the implicitly declared reference. In the example below, the caption property that is set is of the automatically declared Form2 variable and automatically created object of type Form2. Because of Visual Basic's implicit declaration and creation of the form, this code works properly.
Private Sub Form_Load()
Form2.Caption = "Hello VB World"
End Sub
People familiar with the use of OLE servers from Visual Basic may have
heard the statement that 'the first time a property or method of a [class]
is referenced, Visual Basic creates [an object] from the [class].' This
sounds suspiciously like Visual Basic's behavior when an object variable as
been declared 'As New'. With this kind of declaration, Visual Basic will
automatically create an object when a property or method is referenced, if
an object doesn't already exist (see pages 200-201 of the Programmer's
Guide for more information). Visual Basic's implicit declaration of form
variables can be thought of as this sort of equivalent Visual Basic
statement:
Public MyForm As New MyFormIf one chooses to follow the convention that all form objects should be created and destroyed explicitly, it is easy to accidentally refer to a property or method of the form when the form object does not exist (either because it hasn't been explicitly created or because it has been previously destroyed). By default, because of the above implicit declaration, Visual Basic will happily create a new instance of the given form class and allow the code to proceed unheeded. This can easily lead to logic errors that can be difficult to find. To avoid this problem, one can override the implicit declaration with their own explicit declaration. Doing so will cause Visual Basic to correctly raise error 91, "Object variable not set," if a property or method of a non-existing form is referenced.
Public MyForm As MyForm Public MySecondForm as MySecondFormAfter these declarations, each form must be created with a Set statement before being used, for example:
Sub Main()
Set MyForm = New MyForm
MyForm.Show
End Sub
Additional query words: kbVBp400 kbVBp500 kbVBp600 kbVBp kbdsd kbDSupport kbVBA
Keywords: kbhowto KB147665