The object of this tip is to describe a simple, but effective use of
procedures where multiple variables or objects are required in the calling code. Functions can be a useful way of passing a series of parameters and retrieving a resultant response based around those initial parameters. However, consider a situation where a single resultant response isn't enough. For example, a procedure that returns 3 strings in plain text: the day, month and year given a single
(dd/mm/yyyy) date; or a procedure that returns multiple fields from a table given a unique field reference. Consider the function below:
Private Function curCalcTotal(curAmount as Currency) as Currency
Dim curTax as Currency
Dim curPostage as Currency
Dim curTotal as Currency
'calc Tax
curTax = curAmount * 0.175
'set Postage Amount
curPostage = 2.45
'calc Total
curCalcTotal = curAmount + curTax + curPostage
End Function
This works fine, unless we require a breakdown of each stage of the calculation which would return the tax, postage and total. To return multiple variables from functions we could declare the variables curTax, curPostage and curTotal as public variables visible to both the calling code and the above function, although this isn't the preferred method as these variables are exposed to all the events, methods and procedures within the form/class/module and could be amended outside the calling code and above function. The best solution is to pass curAmount, curTax, curPostage and curTotal into the function as
shown below:
Private Function blnCalcTotal(curAmount as Currency, curTax as Currency, _
curPostage as Currency, curTotal as Currency) as Boolean
On Error Goto ErrorHandler
blnCalcTotal = False
'calc Tax
curTax = curAmount * 0.175
'set Postage Amount
curPostage = 2.45
'calc Total
curTotal = curAmount + curTax + curPostage
blnCalcTotal = True
Exit Function
ErrorHandler:
MsgBox "Error No. " & Err & ", " & Err.Description", _
vbExclamation, "blnCalcTotal"
End Function
The calling code will require curAmount, curTax, curPostage and curTotal to be declared, but only curAmount to be assigned a value prior to calling blnCalcTotal. Once blnCalcTotal has executed, curAmount, curTax, curPostage and curTotal should all have been populated within the function and passed back to the calling code. The advantage of this type of function is
that the return object blnCalcTotal can be used as a flag to indicate the success or failure of the functions execution, plus an unlimited no of variables or objects can be returned by the function and are not exposed to code other than the function or calling code.
|