Whats a better way to call a form from another form

vb6

Solution

In VB6 when a program runs, as soon as you reference a form via it's form name VB6 creates an instance of that form. That instance is also added to the Forms collection.

You can discover which forms have been instantiated using this code or a suitable variation thereof:

Dim frmCurrent As Form
Dim output As String
For Each frmCurrent In Forms
    output = output & frmCurrent.Name & vbCrLf
Next
MsgBox output

So when you call Form2.abc() you are calling the abc procedure on the newly created instance of the Form2 form (you can substitute the word class for form if it helps your understanding).

When it comes time to exit the program you can get a type of error where the program is hanging around in memory but is not visible on the screen because you have closed all the visible forms but not the ones instantiated via calls like `Form2.abc`. This lead to the popular 'close all forms' code being added to the exit procedure of many VB6 programs:

Private Sub cmdExit_Click()
   Dim current As Form
   Dim output As String
   For Each current In Forms
      Unload current
   Next
End Sub

When you dimension a variable and assign a new instance of Form2 to it you are creating a new form with scope according to the variable. The instance is not added to the Forms collection:

Dim frmNew As New frmTest
frmNew.abc

Dim frmCurrent As Form
Dim output As String
For Each frmCurrent In Forms
    output = output & frmCurrent.Name & vbCrLf
Next
MsgBox output 'Does not include frmNew aka frmTest

Thus your second method is generally the better one as it doesn't create an instance of Form2 in the Forms collection or reuse an exisiting instance that may give you an unexpected result.

Problem

Say I have 2 forms named, Form1 and Form2. I want to call a function abc() in Form2 from Form1. Which one is better and why? Method 1: ``` 'In Form1 Form2.abc() ``` Method 2: ``` 'In Form1 Dim oFrm As New Form2 oFrm.abc() ```

Original source