Passing Parameters and Returning Values

Both subroutines and functions can receive arguments (parameters), but only functions can return values. The following subroutine (found under the Pass Parameters command button of the frmParametersAndReturnValues form) receives two parameters, txtFirst and txtLast. It then displays a message box with the first character of each of the parameters passed to it:

Private Sub cmdPassParameters_Click()
  Call Initials(Nz(Me.txtFirstName.Value), Nz(Me.txtLastName.Value))
End Sub

Sub Initials(strFirst As String, strLast As String)
' This procedure can be found by selecting General in
' the Object drop-down list in the VBE window
  MsgBox "Your Initials Are: " & Left$(strFirst, 1) _
   & Left$(strLast, 1)
End Sub

Notice that the values in the controls txtFirstName and txtLastName from the current form (represented by the Me keyword) are passed to the subroutine called Initials. That subroutine receives the parameters as strFirst and strLast and displays the first character of each parameter in the message box.

The preceding code simply passes values and then operates on those values. This next example (found under the Return Values command button of the frmParametersAndReturnValues form) uses a function to return a value:

Private Sub cmdReturnValues_Click()
    Dim strInitials As String
    strInitials = ReturnInit(Nz(Me.txtFirstName.Value), _
    MsgBox "Your initials are: " & strInitials
End Sub

Function ReturnInit(strFName As String, strLName As String) As String
' This procedure can be found by selecting General in
' the Object drop-down list in the VBE window
    ReturnInit = Left$(strFName, 1) & Left(strLName, 1)
End Function

Notice that this example calls the function ReturnInit, sending values contained in the two text boxes as parameters. The function sets the ReturnInit function equal to the first two characters of the strings. This returns the value to the calling routine (cmdReturnValues _Click) and sets strInitials equal to the return value.


Notice that the function ReturnInit is set to receive two string parameters. You know this because of the As String keywords that follow each parameter. The function is also set to return a string. You know this because the keyword As String follows the list of the parameters, outside the parentheses. If you don't explicitly state that the function should return a particular type of data, it returns a variant.

    Part III: Creating Your Own Database and Objects
    Part V: Advanced Topics