Article ID: 141605
Article Last Modified on 1/19/2007
Sub MyTest(strTest1 As String, _
Optional Test2 As Variant, _
Optional Test3 As Variant)
This was a requirement because optional arguments were passed at the end
of the function call. In Microsoft Access 97 improvements have been made to
the use of the Optional keyword by allowing the data type casting of the
optional variable to be pre-assigned. For example:
Sub MyTest(strTest1 As String, _
Optional Test2 As String = "Test2", _
Optional Test3 As String = "Test3")
This allows for the placement of the optional variable anywhere in the
calling order of the function and allows you to test the contents of the
variable.
Option Explicit
Function CallEmployeeInfo()
If Forms!employees!Title <> "Sales Representative" Then
EmployeeInfo Forms!employees!FirstName, Forms!employees!LastName
Else
EmployeeInfo Forms!employees!FirstName, _
Forms!employees!LastName, Forms!employees!Title
End If
End Function
Sub EmployeeInfo(fname, lname, Optional Title)
If IsMissing(Title) Then
MsgBox lname & ", " & fname
Else
MsgBox lname & ", " & fname & " " & Title
End If
End Sub
? CallEmployeeInfo()
Option Explicit
Sub OptionalTest(Optional Country)
Dim dbs As DATABASE, rst As Recordset
Dim strSQL As String
' Return Database variable pointing to current database.
Set dbs = CurrentDb
If IsMissing(Country) Then
strSQL = "SELECT * FROM Orders"
'This will return all the records
Else
strSQL = "SELECT * FROM Orders WHERE [ShipCountry] = '" &_
Country & "';"
'This will return only values matching the argument you entered.
End If
Set rst = dbs.OpenRecordset(strSQL)
rst.MoveLast
Debug.Print rst.RecordCount
End Sub
OptionalTest "UK"
OptionalTest
Keywords: kbhowto kbprogramming KB141605