instance, you might have a listbox that lists user-friendly form
names. When a user selects a name, you want Visual Basic to display
the associated form.
This type of feature, however, requires the use of a dynamic form name.
After all, you won't know which form the user has selected, as you
would with other pre-defined methods, such as opening a specific form
when the user clicks a button. Fortunately, Visual Basic provides an
easy way to reference a form dynamically with the Forms collection.
This global collection object represents all loaded standard, MDI and
MDI child forms in an application. As with most VB collections, the
Forms object lets you refer to items either by index or by name, as
seen below:
Set frm = Forms(1)
or
Set frm = Forms("frmEditor")
And of course, you can substitute a variable for any of the index
values, like so:
Set frm = Forms(strName)
With this collection available, it becomes a relatively easy matter to
load a form dynamically. The following code shows a simplified way to
do so:
Private Sub Form_Load()
With List1
.AddItem "Form1"
.AddItem "Form2"
.AddItem "Form3"
End With
End Sub
Private Sub List1_Click()
Dim frm As Form
Dim selForm As String
With List1
selForm = .List(.ListIndex)
End With
Set frm = Forms.Add(selForm)
frm.Show
Set frm = Nothing
End Sub
Comments