The UserName() function returns a string consisting of the first name and last name specified as its parameter values. If one of the parameters is omitted, it returns an incomplete name.
When working with optional parameters, you must use the IsMissing() function, which returns True if the corresponding parameter was not passed to the procedure, and False otherwise.
Function procedure with optional parameters
Function UserName(Optional LastName As String, _ Optional FirstName As String) As String If Not (IsMissing(LastName)) And Not (IsMissing(FirstName)) Then UserName = LastName & Space(1) & FirstName ElseIf IsMissing(LastName) And Not (IsMissing(FirstName)) Then UserName = FirstName ElseIf Not IsMissing(LastName) And IsMissing(FirstName) Then UserName = LastName End If End Function
Demonstration of using the function:
Sub DemoUserName()
MsgBox UserName(LastName:="Bond", FirstName:="James")
' Bond James
MsgBox UserName("James", "Bond")
' James Bond
MsgBox UserName("Bond")
' Bond
MsgBox UserName(, "James")
' James
MsgBox UserName()
' Nothing
End Sub