Introduction to Procedures and Functions |
|
Sub Procedures
Introduction
A procedure is a section of code that performs an assignment so that other parts of the program can directly use the result of that assignment. For example, a procedure can be created to display a message to a user. Another procedure can be used to calculate something that the other parts of the database would use when and where necessary.
The Visual Basic language supports two categories of procedures: sub-procedures and functions.
Practical Learning: Introducing Procedures
Creating a Procedure
A sub-procedure is a section of code that carries an assignment but doesn't give back a result. The formula to create a sub-procedure is:
Sub procedure-name() End Sub
The Sub keyword and the End Sub expressions are required. The Sub keyword is followed by the name of the sub-procedure. The name is followed by parentheses. Normally, the Sub keyword and the name of the procedure (including its parentheses) are written on the same line. The name of a sub-procedure follows the same rules we reviewed for the names of variables, omitting the prefix:
The section between the Sub procedure-name line and the End Sub line is referred to as the body of the procedure. In the body of a procedure, you define what the procedure is supposed to do. If you need to use a variable, you can declare it and specify what kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a sub procedure:
Sub CreateName()
Dim strFullName As String
End Sub
In the same way, you can declare as many variables as you want in the body of a procedure. A procedure can be used to perform a simple calculation such as adding two numbers. Here is an example:
Sub CalculateTotalStudents()
Dim StudentsInClass1 As Integer
Dim StudentsInClass2 As Integer
Dim TotalNumberOfStudents As Integer
StudentsInClass1 = 32
StudentsInClass2 = 36
TotalNumberOfStudents = StudentsInClass1 + StudentsInClass2
End Sub
Practical Learning: Creating a Procedure
Sub Sub SolveRectangle() ' Declare the necessary variables for the rectangle Dim dblWidth As Double, dblHeight As Double Dim dblPerimeter, dblArea As Double ' Retrieve the values of the sides dblWidth = txtWidth dblHeight = txtHeight ' Calculate the perimeter and the area of the rectangle dblPerimeter = (dblWidth + dblHeight) * 2 dblArea = dblWidth * dblHeight ' Prepare to display the result in the appropriate text boxes txtPerimeter = dblPerimeter txtArea = dblArea End Sub
After creating a procedure, you can use it in the section of code where you need it. Using a procedure is referred to as calling it. To call a simple procedure, just write its name. Here is an example:
Sub ShowMessage()
lblMessage.Caption = "Helium is a chemical element found, or used, in solids, in liquids, and in gases."
End Sub
Private Sub cmdMessage_Click()
ShowMessage
End Sub
Practical Learning: Calling a Procedure
Private Sub cmdCalculate_Click()
SolveRectangle
End Sub
Parameters and Arguments
Introduction
To carry out an assignment, a procedure may need a value. That is, in order to perform its assignment, a prodcedure may need the calling code to supply it with a value, such as value is external to the procedure. Such a value is called a parameter. The type of the parameter depends on your goal. If you are writing your own procedure, you decide based on your intentions.
To create a procedure that uses a parameter, inside of the parentheses of the procedure, write the name of the parameter followed by the As keyword followed by the type of value of the parameter. Here is an example:
Sub ShowMessage(Msg As String)
End Sub
In the body of the procedure, you can ignore and not use the parameter if you don't need it. Otherwise, in the body of the procedure, use the parameter as you would use a local variable. Here is an example:
Sub ShowMessage(Msg As String)
lblMessage.Caption = Msg
End Sub
Of course, the parameter can be involved in an expression.
Here is an example:
Sub Calculation Function CubeArea(Side As Double)
Dim value As Double
Let value = Side * Side * 6
End Sub
Calling a Procedure That Has a Parameter
If a sub-procedure is taking a parameter, to call it, you must provide a value for the parameter. Providing a value for the parameter is referred to as passing the argument. To pass an argument to a procedure, type the name of the procedure, followed by a space, and followed by the value of the parameter. Here is an example:
Sub Describe(Power As String)
lblMessage.Caption = Power
End Sub
Private Sub cmdMessage_Click()
Describe "Electricity is used to supply power to machines and devices."
End Sub
Alternatively, you can use the Call keyword to call a sub procedure. In this case, type the Call keyword on the left side of the calling procedure and include the argument between parentheses. Here is an example:
Sub ShowMessage(Power As String)
lblMessage.Caption = Power
End Sub
Private Sub cmdMessage_Click()
Call ShowMessage("Electricity is used to supply power to machines and devices.")
End Sub
The argument passed to a procedure can come from a variable. In this case, the name of the variable and that of the parameter don't have to be the same. Here is an example:
Sub Evaluate(Salary As Double)
Dim OvertimeSalary As Double
OvertimeSalary = Salary * 1.5
txtOvertimeSalary = OvertimeSalary
End Sub
Private Sub cmdCalculate_Click()
Dim HourlyWages As Double
HourlyWages = txtHourlySalary
Evaluate HourlyWages
End Sub
A Procedure With Many Parameters
A procedure can take more than one parameter. If you are creating such a procedure, In the parentheses of the procedure, each parameter must have a unique name and it must specify its type. The parameters are separated by commas. The parameters can use the same type. Here is an example:
Sub CalculatePerimeter(Length As Double, Height As Double) End Sub
The parameters can also use different types. Here is an example:
Sub DisplayGreetings(strFullName As String, intAge As Integer, dblDistance As Double) End Sub
In the body of the procedure, you can ignore all parameters, you can use one or some parameter, or you can use all of them. Here is an example:
Sub Evaluate(Salary As Double, Times As Double) Dim WeeklySalary As Double WeeklySalary = Salary * Times txtWeeklySalary = WeeklySalary End Sub
Calling a Procedure With Many Parameters
If a sub-procedure is taking many parameters, when calling it, you must provide a value for each parameter. If a procedure takes more than one argument, you must provide a value for each parameter, in the exact order they appear in the parentheses of the procedure. In that case, the values must be separated by commas. Here is an example:
Sub Evaluate(Salary As Double, Times As Double)
Dim WeeklySalary As Double
WeeklySalary = Salary * Times
txtWeeklySalary = WeeklySalary
End Sub
Private Sub cmdCalculate_Click()
Dim HourlyWages As Double
Dim TimeWorked As Double
HourlyWages = txtHourlySalary
TimeWorked = txtTimeWorked
Evaluate HourlyWages, TimeWorked
End Sub
Remember that, as an alternative, you can use the Call keyword, in which case the arguments must be includes in parentheses. Here is an example:
Sub Evaluate(Salary As Double, Times As Double)
Dim WeeklySalary As Double
WeeklySalary = Salary * Times
txtWeeklySalary = WeeklySalary
End Sub
Private Sub cmdCalculate_Click()
Dim HourlyWages As Double
Dim TimeWorked As Double
HourlyWages = txtHourlySalary
TimeWorked = txtTimeWorked
Call Evaluate(HourlyWages, TimeWorked)
End Sub
Introduction
A function is a procedure that performs an assignment and produces a result. Proceducing a result is also referred to as returning a value. A function resembles a sub-procedure in all except that a function returns a value.
A function is started like a sub-procedure with a few more rules. To start, instead of the Sub keyword, a function uses the Function keyword. The name of the function follows the same rules and suggestions we reviewed for the sub-procedures. Because a function must return a value, after the parentheses, you must specify a data type. This is done by typing the As keyword followed by the type of value the function must return. Therefore, the primary formula to create a function is:
Function function-name() AS data-type End Function
Here is an example:
Function GetFullName() As String
End Function
When we studied variables, we saw that, instead of using the As data-type expression, we could use a type character. This technique also applies to functions. To use it, on the right side of the name of the function, type the special character that represents the data type, followed by the parentheses of the function, and omit the As data-type expression. Here is an example:
Function GetFullName$()
End Function
As with the variables, you must use the appropriate character for the function:
Character | The function must return |
$ | A String type |
% | An Integer |
! | a Single type |
# | a Double |
@ | a Long |
Implementing a Function
The implementation of a function is primarily done the same way as a sub-procedure. Because a function must return a value, after performing whatever assignment you need in the body of the function, assign the final result to the name of the function before the End Function line. Here is an example:
Function GetFullName() As String
Dim strFirstName, strLastName As String
strFirstName = txtFirstName
strLastName = txtLastName
GetFullName = strFirstName & " " & strLastName
End Function
You can also start the assignment line with the Let keyword. Here is an example:
Function GetFullName() As String
Dim strFirstName, strLastName As String
strFirstName = txtFirstName
strLastName = txtLastName
Let GetFullName = strFirstName & " " & strLastName
End Function
Practical Learning: Creating a Function
Function CalculateDiameter() As Double
Dim radius As Double
radius = txtRadius
CalculateDiameter = radius * 2#
End Function
Function CalculateArea() As Double Dim radius As Double radius = txtRadius CalculateArea = radius * radius * PI End Function
To call a function, you have two main options. If the function was implemented as simple as a sub-procedure, just write its name where its result is needed. If you want to use the return value of a function, assign the name of the function to a local variable. Here is an example:
Private Sub Detail_DblClick(Cancel As Integer)
txtFullName = GetFullName
End Sub
Practical Learning: Calling a Function
Private Sub cmdCalculate_Click()
txtDiameter = CalculateDiameter
txtArea = CalculateArea
End Sub
Const PI = 3.14159265359 Function CalculateDiameter() As Double Dim radius As Double radius = txtRadius CalculateDiameter = radius * 2# End Function Function CalculateArea() As Double Dim radius As Double radius = txtRadius CalculateArea = radius * radius * PI End Function Sub ProcessCircumference() Dim radius As Double Dim circumference radius = txtRadius circumference = CalculateDiameter() * PI txtCircumference = circumference End Sub Private Sub cmdCalculate_Click() txtDiameter = CalculateDiameter ProcessCircumference txtArea = CalculateArea End Sub
Functions and Arguments
A Function With a Parameter
Like a sub-procedure, a function may need one or more external values in order to carry its assignment. To create a function that takes an argument, use the same approach as for a sub-procedure. Here is an example:
Function CalculatOvertime(Salary As Double) As Double Dim OvertimeSalary OvertimeSalary = Salary * 1.5 CalculatOvertime = OvertimeSalary End Function
Practical Learning: Creating a Parameterized Function
Function CalculateSingleArea(side As Double) As Double
CalculateSingleArea = side * side * 6
End Function
Calling a Function With a Parameter
To call a function that takes an argument, if you are not planning to use its return value, proceed as done for a sub-procedure: Type the name of the function followed by a space and the argument. Here is an example:
Function CalculatOvertime(Salary As Double) As Double
Dim OvertimeSalary
OvertimeSalary = Salary * 1.5
CalculatOvertime = OvertimeSalary
End Function
Private Sub cmdCalculate_Click()
Dim HourlyWages As Double
HourlyWages = txtHourlySalary
CalculatOvertime HourlyWages
End Sub
Otherwise, if you want to use the value produced by the function, assign its call to a variable and put the argument in parentheses. Here is an example:
Function CalculatOvertime(Salary As Double) As Double
Dim OvertimeSalary
OvertimeSalary = Salary * 1.5
CalculatOvertime = OvertimeSalary
End Function
Private Sub cmdCalculate_Click()
Dim HourlyWages As Double
Dim OvertimeSalary As Double
Let HourlyWages = txtHourlySalary
OvertimeSalary = CalculatOvertime(HourlyWages)
Let txtOvertimeSalary = OvertimeSalary
End Sub
Practical Learning: Calling a Parameterized Function
rivate Sub cmdCalculate_Click()
Dim s As Double
Dim sa As Double
s = txtSide
sa = CalculateSingleArea(s)
txtSingleArea = sa
End Sub
Function CalculateTotalArea(side As Double) As Double CalculateTotalArea = CalculateSingleArea(side) * 6 End Function Function CalculateVolume(side As Double) As Double CalculateVolume = CalculateSingleArea(side) * side End Function Private Sub cmdCalculate_Click() Dim s As Double Dim sa As Double Dim ta As Double Dim vol As Double s = txtSide sa = CalculateSingleArea(s) ta = CalculateTotalArea(s) vol = CalculateVolume(s) txtSingleArea = sa txtTotalArea = ta txtVolume = vol End Sub
A Function With Many Parameters
A function needs many parameters, create it as we saw for sub-procedures. Make sure the last line of the function specifies the value it returns. When calling the function, specify the arguments in its parentheses. Here is an example:
Function CalculatOvertime(Salary As Double, Times As Double) As Double
CalculatOvertime = Salary * Times
End Function
Private Sub cmdCalculate_Click()
Dim HourlyWages As Double
Dim TimeWorked As Double
Dim WeeklyWages As Double
HourlyWages = txtHourlySalary
TimeWorked = txtTimeWorked
WeeklyWages = CalculatOvertime(HourlyWages, TimeWorked)
txtWeeklySalary = WeeklyWages
End Sub
Practical Learning: Writing Procedures With Parameters
Function CalculateArea(dblLength As Double, _ dblHeight As Double, _ dblWidth As Double) As Double Dim area As Double area = 2 * ((dblLength * dblHeight) + _ (dblHeight * dblWidth) + _ (dblLength * dblWidth) _ ) CalculateArea = area End Function Function CalculateVolume(dblLength As Double, _ dblHeight As Double, _ dblWidth As Double) As Double Dim volume As Double volume = dblLength * dblHeight * dblHeight CalculateVolume = volume End Function
Private Sub cmdCalculate_Click() Dim area As Double, volume As Double Dim dWidth As Double, dHeight As Double, dDepth As Double Let dWidth = txtWidth Let dHeight = txtHeight Let dDepth = txtDepth Let area = CalculateArea(dWidth, dHeight, dDepth) Let volume = CalculateVolume(dWidth, dHeight, dDepth) Let txtArea = area Let txtVolume = volume End Sub
Techniques of Passing Arguments
Optional Arguments
Unless specified otherwise, from this section and the rest of our lessons, the word "procedure" represents both the sub-procedure and the function. The name "sub-procedure" will be used only if the issue particularly relates to that type. The name "function" will be used only if the procedure returns a value, that is, if the topic is particularly related to functions. |
If you create a procedure that takes an argument, whenever you call that procedure, you must provide a value for that argument. If you fail to do that, you will receive an error. Imagine you create a function that will be used to calculate the final price of an item after discount. The function would need the discount rate in order to perform the calculation.
Practical Learning: Introducing Optional Arguments
Function CalculateNetPrice(DiscountRate As Double) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function
Function CalculateNetPrice(DiscountRate As Double) As Currency
Dim OrigPrice As Double
OrigPrice = CCur(txtMarkedPrice)
CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100
End Function
Private Sub cmdCalculate_Click()
txtPriceAfterDiscount = CalculateNetPrice()
End Sub
To make an argument optional, in the parentheses of its procedure, start the parameter with the Optional keyword. On the right side of the data type of the argument, type the assignment operator, followed by the desired default value. To apply an example, change the code as follows:
Function CalculateNetPrice(Optional DiscountRate As Double = 0.20) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function Private Sub cmdCalculate_Click() txtPriceAfterDiscount = CalculateNetPrice(dblDiscount#) End Sub
Function CalculateNetPrice(Optional DiscountRate As Double = 0.2) As Currency Dim OrigPrice As Double OrigPrice = CCur(txtMarkedPrice) CalculateNetPrice = OrigPrice - CLng(OrigPrice * DiscountRate * 100) / 100 End Function Private Sub cmdCalculate_Click() Dim dblDiscount# dblDiscount = CDbl(txtDiscountRate) Let txtPriceAfterDiscount = CalculateNetPrice(dblDiscount) End Sub
Function CalculateNetPrice(OrigPrice As Currency, _ Optional TaxRate As Double = 0.0575, _ Optional DiscountRate As Double = 0.25) As Currency Dim curDiscountValue As Currency Dim curPriceAfterDiscount As Currency Dim curTaxValue As Currency Dim curNetPrice As Currency curDiscountValue = CLng(OrigPrice * DiscountRate * 100) / 100 curPriceAfterDiscount = OrigPrice - curDiscountValue curTaxValue = CLng(curPriceAfterDiscount * TaxRate * 100) / 100 txtDiscountValue = CStr(curDiscountValue) txtPriceAfterDiscount = CStr(curPriceAfterDiscount) txtTaxValue = CStr(curTaxValue) CalculateNetPrice = curPriceAfterDiscount + curTaxValue End Function
Private Sub cmdCalculate_Click()
Dim curMarkedPrice As Currency
Dim dblTaxRate#
Let curMarkedPrice = CCur(txtMarkedPrice)
Let dblTaxRate = CDbl(txtTaxRate)
Let txtNetPrice = CalculateNetPrice(txtMarkedPrice)
End Sub
Private Sub cmdCalculate_Click() Dim curMarkedPrice As Currency Dim dblDiscountRate# Dim dblTaxRate# curMarkedPrice = CCur(txtMarkedPrice) dblDiscountRate = CDbl(txtDiscountRate) dblTaxRate = CDbl(txtTaxRate) txtNetPrice = CalculateNetPrice(txtMarkedPrice, txtTaxRate, dblDiscountRate) End Sub
Function CalculateNetPrice(OrigPrice As Currency, _
Optional TaxRate As Double = 0.0575, _
Optional DiscountRate As Double = 0.25) As Currency
Dim curDiscountValue As Currency
Dim curPriceAfterDiscount As Currency
Dim curTaxValue As Currency
Dim curNetPrice As Currency
curDiscountValue = CLng(OrigPrice * DiscountRate * 100) / 100
curPriceAfterDiscount = OrigPrice - curDiscountValue
curTaxValue = CLng(curPriceAfterDiscount * TaxRate * 100) / 100
txtDiscountValue = CStr(curDiscountValue)
txtPriceAfterDiscount = CStr(curPriceAfterDiscount)
txtTaxValue = CStr(curTaxValue)
CalculateNetPrice = curPriceAfterDiscount + curTaxValue
End Function
Private Sub cmdCalculate_Click()
Dim curMarkedPrice As Currency
Dim dblDiscountRate#
Dim dblTaxRate#
curMarkedPrice = CCur(txtMarkedPrice)
dblDiscountRate = CDbl(txtDiscountRate)
txtNetPrice = CalculateNetPrice(curMarkedPrice, , dblDiscountRate)
End Sub
When you call a procedure that takes more than one argument, you must pass the arguments in the right order. Consider the following function:
Function ResumeEmployee$(salary As Currency, name As String, dHired As Date) Dim strResult$ Let strResult = name & ", " & CStr(dHired) & ", " & CStr(salary) Let ResumeEmployee = strResult End Function
When calling this function, you must pass the first argument as a currency value, the second as a string, and the third as a date value. If you pass a value in the wrong position, you would receive an error. This is what would happen if you call it as follows:
Private Sub cmdResume_Click()
Dim strFullName As String
Dim dteHired As Date
Dim curHourlySalary As Currency
Dim strResume$
Let strFullName = [txtFullName]
Let dteHired = CDate([txtDateHired])
Let curHourlySalary = CCur(txtHourlySalary)
Let strResume = ResumeEmployee(strFullName, dteHired, curHourlySalary)
Let txtResume = strResume
End Sub
While you must respect this rule, Microsoft Visual Basic provides an alternative. You don't have to pass the arguments in their strict order. Instead, you can assign the desired value to each argument using its name. To do this, when calling the procedure, in the parentheses of the function, type the name of the parameter, followed by the := operator, followed by the (appropriate) value.
Practical Learning: Randomly Passing Arguments
Function ResumeEmployee(Salary As Currency, _ Name As String, _ DateHired As Date) As String Dim strResult As String strResult = Name & ", " & CStr(DateHired) & ", " & CStr(Salary) ResumeEmployee = strResult End Function Private Sub cmdResume_Click() Dim strFullName As String Dim dteHired As Date Dim curHourlySalary As Currency Dim strResume$ strFullName = [txtFullName] dteHired = CDate([txtDateHired]) curHourlySalary = CCur(txtHourlySalary) strResume = ResumeEmployee(Name:=strFullName, DateHired:=dteHired, _ Salary:=curHourlySalary) txtResume = strResume End Sub
Normally, when you call a procedure that uses one or more parameters, the argument itself is not changed. This technique is referred to as passing an argument by value. To reinforce this, you can type the ByVal keyword on the left side of the argument. Here is an example:
Function CalculateTriangleArea#(ByVal Base As Double, ByVal Height As Double) CalculateTriangleArea = Base * Height / 2 End Function
Practical Learning: Passing Arguments By Value
Private Function CalculateTriangleArea(ByVal Base As Double, _ ByVal Height As Double) As Double CalculateTriangleArea = Base * Height / 2 End Function Private Sub cmdCalculate_Click() Dim dblBase As Double Dim dblHeight As Double dblBase = CDbl([txtBase]) dblHeight = CDbl([txtHeight]) txtArea = CalculateTriangleArea(dblBase, dblHeight) End Sub
Passing Arguments By Reference
The Visual Basic language includes a feature that allows a procedure to change the value of a parameter. This is referred to as passing an argument by reference. To do this, type the ByRef keyword on the left side of the name of the parameter.
If you create a procedure that uses more than one parameter, you can decide which one(s) would be passed by value and which one(s) would be passed by reference.
Practical Learning: Passing Arguments By Reference
Private Sub CalculateTriangleArea(ByRef Area As Double, _ ByVal Base As Double, _ ByVal Height As Double) Area = Base * Height / 2 End Sub Private Sub cmdCalculate_Click() Dim dblBase As Double Dim dblHeight As Double Dim dblArea As Double Let dblBase = txtBase Let dblHeight = txtHeight CalculateTriangleArea dblArea, dblBase, dblHeight Let txtArea = dblArea End Sub
Options on Variables and Procedures
Introduction to the Scope and Lifetime of a Procedure
Like a variable, a procedure has scope. A procedure is global if it can be accessed from any code in the database. Normally, any procedure you create like those we have used so far is global.
Private Procedures
A procedure is private if it can be accessed only by events and procedures of the same module. To create a private procedure, precede its introductory Sub or Function with the Private keyword.
Public Procedures
A public procedure is one that can be called from any event or any procedure of the same application. As mentioned above, this is the default for the procedures. To re-inforce the fact that a procedure is public, precede its creation with the Public keyword.
Microsoft Visual Basic simplifies the creation of a procedure through the use of the Insert Procedure dialog box. To display the Insert Procedure:
If you are creating a sub-procedure, click the Sub radio button. If you want the procedure to be accessed only by the objects, events and procedure of the same module, click the Private radio button. If you want to access the procedure from outside of the current module, click the Public radio button.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2002-2022, FunctionX, Inc. | Next |
|