VBNotebook Home | Functions | How To Treat a Modal Form as a Function
A commonly asked question in newsgroups is, "How do I pass information from one form to another?" This example routine shows you a method for doing this with a modal pop-up form where you want to receive input from the user and pass it back to a main form.
We'll start with the pop-up form that we'll call frmPopup. This form should have two buttons on it, cmdOK and cmdCancel. For purposes of this demo, we'll also add a single textbox called txtData. You could, of course, have several other buttons and data entry fields if you wanted to.
The following code would be added to frmPopup.
__________________________________________________________________________________________
Option Explicit
Dim mbCancel As Boolean
Private Sub Form_Load()
' nothing goes here
End Sub
Public Function DisplayPopupForm(sData As String) As Boolean
Load Me
txtData.Text = sData
'
' Any other process to do before showing the form would go here
'
Me.Show vbModal
If Not mbCancel Then
sData = txtData.Text
'
' Any other data gathering or processing before returning
' would be done here
'
End If
DisplayPopupForm = Not mbCancel
Unload Me
End Function
Private Sub cmdCancel_Click()
mbCancel = True
Me.Hide
End Sub
Private Sub cmdOK_Click()
mbCancel = False
Me.Hide
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If UnloadMode <> vbFormCode Then
mbCancel = True
Me.Hide
Cancel = True
End If
End Sub
__________________________________________________________________________________________
Note that the Form_Load routine isn't used at all and that all loading and showing of the form happens in the DisplayPopupForm routine. The code treats clicking on the 'X' close button of the form the same as clicking the Cancel button.
On the main form, called frmMain in this case, we'll have a command button
called cmdGetInfo. Here's how the code would look
there.
__________________________________________________________________________________________
Private Sub cmdGetInfo_Click()
Dim sData As String
If
frmPopup.DisplayPopupForm(sData) Then
Debug.Print sData
'
' If a value is returned, do whatever processing
' we need to do with the value
'
End If
End Sub
Copyright 2000-2005, J. Frank Carr