Chapter 11: Mastering VBA Data Types and Procedures
447
An important feature of this example code is that it combines data extracted from a database table
(Price, DiscountPercent) with data passed as parameters (dblTaxPercent, lngIn-
voiceNum). All the extraction and calculations are automatically performed by the code, and the
user is never aware of how the tax amount is determined.
Tip
Functions and subprocedures are important to the concepts of reusable code within an application. You should
try to use functions and subprocedures and pass them parameters whenever possible. A good rule is this: The
first time you find yourself copying a group of code, it’s time to create a procedure or function.
Simplifying Code with Named Arguments
Another significant feature of Access VBA is the use of named arguments for procedures. Without
named arguments, the arguments passed to procedures must appear in the correct left-to-right
order. With named arguments, you provide the name of each parameter passed to a subroutine or
function, and the subroutine or function uses the argument based on its name rather than on its
position in the argument list.
Also, because every parameter passed to a procedure is explicitly named, you can omit an unused
parameter without causing an error. Named arguments are a great way to clean up your code while
making it much easier to read and understand.
Assume your application includes the function shown here:
Function PrepareOutput(sStr1 As String, sStr2 As String, _
sStr3 As String) As String
PrepareOutput = sStr1 & “ “ & sStr2 & “ “ & sStr3
End Function
This function, of course, does nothing more than concatenate sStr1, sStr2, and sStr3 and
return it to the calling routine. The next example shows how this function might be called from
another procedure:
Private Sub cmdForward_Click()
txtOutput = PrepareOutput(txtFirstName, _
txtLastName, txtHireDate)
End Sub
The arguments required by PrepareOutput() must be passed in left-to-right order. The results
of this function are shown in Figure 11.15. The text in the Function Output text box on this form
shows the arguments in the order in which they appear in the text boxes on the left side of this
form.
Each argument can be specified by its name as you pass it to functions. Naming arguments makes
them position-independent.