Some forms are merely dialog boxes that show something to the user and sometimes get something in return. For example, you might have to create a form that displays a tabulated listbox of information?contacts, for example. The form needs to know which item should be selected initially, and you want to know which item the user chose in the end. You can share this information through public variables, but wrapping the form into a function proves a better way. Create a standard EXE project and add an extra form to it. Place a command button on the first form and a listbox with a button on the second. Place this code in the first form:
Private Sub Command1_Click() MsgBox Form2.ShowList(4)End Sub
Place this code in the second form:
Dim iSelectedIndexPrivate Sub Command1_Click() Me.HideEnd SubPrivate Sub Form_Load() Dim i As Long For i = 0 To 20 List1.AddItem "Item " & i Next i List1.ListIndex = iSelectedIndexEnd Sub' This is where the magic happens. Note that we have to ' display a modal form to prevent the continuation of this ' function until we are ready.Public Function ShowList(Initial As Integer) As String iSelectedIndex = Initial ' Store the parameter for later use Me.Show vbModal ' Display the form ShowList = List1.List(List1.ListIndex) ' Return Unload MeEnd Function
This technique not only lets you avoid using public variables, but it also gives you excellent portability because you can simply copy the form into a different project. None of the code is affected. You have wrapped a form into a function.