Presentation is loading. Please wait.

Presentation is loading. Please wait.

Sub Procedures Functions And Call Statements

Similar presentations


Presentation on theme: "Sub Procedures Functions And Call Statements"— Presentation transcript:

1 Sub Procedures Functions And Call Statements
4/15/2019 Prepared by: Deborah Becker

2 Prepared by: Deborah Becker
Topics to Cover What benefits structured programming offers Why short, numerous procedures beat long procedures How to write your own functions and subroutines When to use functions How to code argument lists Why VB uses two argument-passing methods How to protect passed arguments 4/15/2019 Prepared by: Deborah Becker

3 Structuring Your Program
The best way to structure the program is Small procedures that perform one function Don’t write long procedures that do everything If an event procedure need to perform several tasks, use called procedures to perform each task. You already know the best way to structure programs because you can use Microsoft's Visual Basic design as a guide. The small event procedures you've seen and coded are perfect examples of the correct way to code. Don't write long routines that do everything; instead, write small code procedures that each perform only one task, such as respond to a user's keystroke. If the keystroke is to trigger a bunch of things, keep the event procedure small and call other small procedures that do the detailed work. New Term: Structured programming is a programming method you use to break long programs into numerous small procedures, putting off the details as long as possible. Structured Programming: Means breaking up long programs into manageable small procedures. 4/15/2019 Prepared by: Deborah Becker

4 Prepared by: Deborah Becker
For Example Suppose you need to perform the following: To Reconcile your Check Book 1. Display check marks next to cleared items. 2. Total the cleared items. 3. Total the un-cleared items. 4. If Balanced = True then a. Print a reconciliation report. 5. Display “Checkbook Out of balance” 4/15/2019 Prepared by: Deborah Becker

5 Prepared by: Deborah Becker
What are the steps? Private Sub cmdReconcile_Click () Call ClearItems () Call UnClearItems () If ChkBkIsBalanced = true Then Call ReconcilePrint () End If Call OutBalanceAction () End Sub 4/15/2019 Prepared by: Deborah Becker

6 This is Structured Programming
In structured programming you delay coding details for as long as you can. Keep subdividing your procedures so that simple control procedures call more detailed procedures. Finally you reach the point where a task cannot be further subdivided. All of this event procedure's called procedures should themselves be as small as possible and only perform a single task, or a series of calls to other procedures. All of your code becomes a structured, manageable set of routines that each perform a single task or that control other tasks. Not only does structured programming make writing code easier, it makes managing code really simple. If your application contains a bug, you can more easily locate the bug because you follow the thread of procedures until you get to the routine that controls the logic with the bug. If your unclear balance is incorrect, you can go directly to the procedure that computes that balance and then locate the problem without affecting lots of other code around that routine. 4/15/2019 Prepared by: Deborah Becker

7 Prepared by: Deborah Becker
New Terms The called procedure is the procedure called by another procedure. The calling procedure is the procedure that triggers another's execution When one procedure contains a Call statement, the Call statement puts the current procedure on hold and executes the called procedure. Therefore, when one procedure's execution reaches its Call statement, that procedure is put on hold and execution begins at the called Procedure. Once the called procedure ends (whether it ends with the End Sub statement or an Exit Sub statement or by other means), the called procedure returns control to the calling procedure. The same thing happens when you call the built-in functions because a built-in function is a special kind of procedure: Your code temporarily stops, and the built-in function's code takes over and uses the argument and finally returns a value as well as control back to your code. Call statement Format: Call ProcedureName 4/15/2019 Prepared by: Deborah Becker

8 User Defined Procedures
You've seen event Sub Procedures and you've executed the built-in function (Val(), Format()), and Visual Basic supports two other kinds of procedures: Standard subroutine procedures Standard function procedures A standard subroutine or function procedure does not respond to an event. A standard procedure only executes when called from elsewhere in the program. WARNING: If a procedure is defined with the Private keyword, then only procedures elsewhere within that module can call that procedure. If a procedure is defined with the Public keyword, all procedures in the project can call the procedure. 4/15/2019 Prepared by: Deborah Becker

9 Standard Function Module
Generally, programmers put general-purpose Public procedures in their external modules (modules that are not form modules). These general-purpose subroutines and functions perform work such as calculations and printed output that you may want to repeat in several different applications. For example, if you want to incorporate Visual Basic code that prints your letterhead in two or more applications, you can write the code once, store the code in a standard module, and then add that module to whatever application needs the letterhead printed. The application's regular form module code might call the external module's letterhead routine when ready for the printed letterhead, such as before the body of a specific report prints. 4/15/2019 Prepared by: Deborah Becker

10 Prepared by: Deborah Becker
Standard Procedure Standard procedures, whether they are subroutines or functions, can reside either inside a form module (following the event procedures) or inside an external module file you add to your project. Figure 1 illustrates the difference between subroutines and functions. The calling code calls both and they both do work. The subroutine does not return a value to the calling procedure. The function does return a value to the calling procedure, and the calling procedure must do something with that value such as assign the value to a variable or control. 4/15/2019 Prepared by: Deborah Becker

11 Prepared by: Deborah Becker
To Insert A Module Form In the Coding window click ToolsAdd Procedure Give the Procedure a Name Select the type Select the scope The Sub & Function keyword indicates that you are creating a subroutine or a user defined function To add an external module to a project, simply right-click over the Project Explorer window and select Add Module. The extra module appears in the Explorer window and in the Code window. You then can switch between modules by double-clicking the module name in the Explorer window. The Sub keyword indicates that you're coding a subroutine and Function indicates that you're writing a function. Of course, you can put standard subroutines and functions inside form modules and you should do that if your event procedures get too long. The standard procedures serve to break down the longer problem into more manageable structured routines, as described earlier. 4/15/2019 Prepared by: Deborah Becker

12 Prepared by: Deborah Becker
When To Use Them? A standard function procedure is a standalone non-event procedure that does work when called by another procedure and returns a single value to the called procedure. A standard subroutine procedure is a standalone non-event procedure that does work when called by another procedure. It may return none, one, or more values to the calling procedure. When you want to write a procedure that performs a task but does not need to return a value, write a subroutine procedure. If you need to write a procedure that performs a task and returns a value, such as a calculated result, write a function procedure. You can pass arguments to either kind of procedure. 4/15/2019 Prepared by: Deborah Becker

13 Prepared by: Deborah Becker
Coding Subroutines Give the procedure a meaningful name such as CostOfSales. Determine whether you want to put the procedure in the form module or in a separate external module. Open the Code window and scroll to the bottom. On a blank line below the last line type Private Sub CostOfSales(). Or use the Add Procedure Button under Tools You'll find uses for subroutines as you begin writing larger applications. For example, suppose you were writing a company sales status program. You might need a specialized routine that calculates a cost of sales value and displays that value in a label. By putting that code in a subroutine procedure, you help separate the task from other tasks and make the application more manageable. In addition, if several procedures in the application need the calculation, you can call the procedure from every place that needs it instead of repeating the same code in every place. Make up an appropriate name for the procedure using the same naming rules as you use for variables. If you think you'll use the code in other applications, add a new module to your Project Explorer window, but if the code goes with this application only, you can add the code to the current form module. (If you fail to type the parentheses, Visual Basic adds them for you because all procedure names terminate with the parentheses to hold possible arguments.) 4/15/2019 Prepared by: Deborah Becker

14 Prepared by: Deborah Becker
Example Code Private Sub CostOfSales()] To execute this procedure, Another procedure (event or another standard procedure) can issue either of these statements: Call CostOfSales() CostOfSales Call is optional in the Call statement format NOTE: Use default property values for the text boxes and labels if you want to shorten your code somewhat. Coding just txtTotalInv accomplishes the same purpose as coding txtTotalInv.Text because Text is the default property for all text boxes. Caption is the default property for labels. If the subroutine uses no arguments, you don't need to use Call and the parentheses to trigger the subroutine's execution. If CostOfSales() did use one or more arguments, you would not need Call, but you could leave off the Call keyword. 4/15/2019 Prepared by: Deborah Becker

15 Users Functions CalcTax()
All functions returns a single value. And they will appear in an assignment statement lblTaxAmt.Caption = CalcTax() You can also use the function call inside an math expression: curAmount = curPrice + CalcTax() You can write your own general-purpose function procedures that are not tied to specific events. You can call these functions from any Visual Basic application just as you can subroutine procedures. Function procedures work just like subroutine procedures in every way; you call them from elsewhere in the code. Unlike subroutine procedures, however, a function procedure always returns a value. If you run across a needed calculation and Visual Basic has no built-in function equivalent, you can write your own function that returns that calculated value. When you call the function, you must do something with the returned value. You cannot put a function call on a line by itself as you can with a subroutine. If CalcTax() is a function, you must call the function. 4/15/2019 Prepared by: Deborah Becker

16 Prepared by: Deborah Becker
Concept You should code as though the function call becomes its return value. In other words, when CalcTax() returns from doing its job, the return value temporarily replaces the function call inside the expression. The functions that you write aren't quite as built-in as Visual Basic's built-in functions, but they behave the same way. Your functions never become part of VB's library, but you can put them in any module that needs to access them. Over time, you will write many general-purpose function and subroutine procedures and you might want to keep a module library of common routines that you'll use throughout different applications. To use one of the procedures that you write, you can add that procedure's module to whatever application needs the procedure. You will write new function procedures the same way you write new subroutine procedures (with Tools | Add Procedure or by typing the first function procedure's line at the end of the module). Use the Function keyword in place of Sub. 4/15/2019 Prepared by: Deborah Becker

17 Prepared by: Deborah Becker
Function CalcTax() The following statements would code the beginning and ending statements for the CalcTax() function: Public Function CalcTax () As Single End Function You'll notice something extra on that function's opening statement: As Single. In addition to using the Function keyword, you must also specify the function's return value data type in the function's opening declaration line. Therefore, this CalcTax() function returns a single-precision data type. 4/15/2019 Prepared by: Deborah Becker

18 Prepared by: Deborah Becker
Coding Example The post office charges 37 cents for 8 ounces or less. Add 15 cents for each 4 ounces above the first 8. The weight cannot exceed 24 ounces. 4/15/2019 Prepared by: Deborah Becker

19 Prepared by: Deborah Becker
Solution Public Function Postage() The function returns the value Postage Postage is not the name of a variable but the name of the function When you assign a value to the function’s name the function uses that as the return value The function's code assumes that the letter or package weight appears in a text box control named txtWeight.Text. In addition, the weight must appear as ounces. Therefore, any application that uses this function must make sure these conditions are met before calling the function. Listing 2 demonstrates the way you return the value from a function. There is no variable declared named Postage, yet the second-to-last line assigns a value to Postage. Postage is the name of the function, not a variable! Inside a function procedure, when you assign a value to the function's name, the function uses that value as the return value. This function does not actually end until the End Function statement is reached, but the return value is set right before the terminating statement. 4/15/2019 Prepared by: Deborah Becker

20 Prepared by: Deborah Becker
Coding Arguments When you declare variable remember the rule: Always limit the scope of the varible In order to share the value of local variables that are inside Sub Procedures and Functions We Pass arguments Variables that are local to a procedure can only be used inside that procedure. Variables declared inside a module's general section are global to the module and available throughout the entire module. Variables declared with Public instead of Dim inside the general section are global to the entire project. You've seen throughout the first part of this book that you should avoid global variables as much as possible and use only local variables. If, however, you only use local variables but you write lots of small procedures (as you should), how can the procedures share data? If all the data is local, then a called procedure has no access to the calling procedure's data. As you probably suspect, you'll share data through argument lists. When one procedure must call another procedure, and the called procedure needs information from the calling procedure, the calling procedure can send that information inside the argument list. 4/15/2019 Prepared by: Deborah Becker

21 Prepared by: Deborah Becker
Passing Arguments Arguments are local variable from the calling procedure The called procedure uses them like data and may even manipulate the value When you call a built-in function, you pass one or more arguments to the function so that the function's internal code has data to work with. When you call your own subroutine and function procedures, you also can pass arguments to them. The arguments are nothing more than the passing procedure's local variables that the receiving procedure needs to work with. Once you pass data, that data is still local to the original passing procedure, but the receiving procedure has the opportunity to work with those values for the time of the procedure execution. Depending on how you pass the arguments, the receiving procedure might even be able to change those values so that when the passing procedure regains control, its local variables have been modified by the called procedure. 4/15/2019 Prepared by: Deborah Becker

22 Remember the Arguments….
The passed argument name (or names) do not have to be the same. Therefore, you might call a subroutine Call CalcIt(X) and the subroutine begins with this declaration line: Private Sub CalcIt(Y As Int). Although in this case both X and Y refer to the same value. Receiving & Passing are different. The argument list requirements are that the calling and receiving argument lists must match in number of arguments, match in data type, and order. 4/15/2019 Prepared by: Deborah Becker

23 Example Sub or Function?
Call RecProc(I, J, K) The following statement declares the RecProc() procedure: Private Sub RecProc (I As Integer, J As _ Integer, K As Single) End Sub The calling procedure already knows the data types of I, J, and K, but those values are unknown to RecProc(). Therefore, you'll have to code the data type of each received argument so that the receiving function knows the data type of each sent argument. Remember that Call is funny about its argument parentheses. If you use Call, you must also enclose the arguments in parentheses. You may omit the Call keyword, but if you do, omit the parentheses as well. Here is a Call statement equivalent to that shown earlier with parentheses: Do we need to declare RecProc? 4/15/2019 Prepared by: Deborah Becker

24 Receiving by Reference and by Value
New Term: By reference is a way in which you pass values and allow the called procedure to change those values. Also called by address. New Term: By value is a way in which you pass values and protect the calling procedure's passed data so that the called procedure cannot change the data. Visual Basic lets you pass arguments two ways: by reference and by value. The way you use them determines whether the receiving procedure can change the arguments so that those changes remain in effect after the calling procedure regains control. If you pass and receive by reference (the default method), the calling procedure's passed local variables may be changed in the receiving procedure. If you pass and receive by value, the calling procedure can access and change its received arguments, but those changes don't retain their effects in the calling procedure. 4/15/2019 Prepared by: Deborah Becker

25 Prepared by: Deborah Becker
ByVal Keyword Arguments are passed by reference, meaning that the passed arguments can be changed by their receiving procedure. If you want to keep the receiving procedure from being able to change the calling procedure's arguments, you must pass the arguments by value. To pass by value, precede any and all receiving argument lists with the ByVal keyword, or enclose the passed arguments in an extra set of parentheses. 4/15/2019 Prepared by: Deborah Becker

26 Prepared by: Deborah Becker
Example By Reference Sub Changes (N As Integer, S As Single) ` Receives arguments by reference N = N * 2 ` Double both S = S * 2 ` arguments ` When the calling routine regains control, ` its two local variables will now be twice ` as much as they were before calling this .End Sub 4/15/2019 Prepared by: Deborah Becker

27 Prepared by: Deborah Becker
Allow No Change to Data Sub NoChanges (ByVal N As Integer, ByVal S As Single) ` Receives arguments by value N = N * 2 S = S * 2 ` When the calling routine regains control, ` its two local variables will not be ` changed from their original values End Sub As you can see, Changes() receives its arguments by reference. (Remember that the default passing method is by reference, even if you omit ByRef.) Therefore, when the procedure doubles the arguments, the calling procedure's argument variables change as well. In NoChanges(), the procedure receives its arguments by value. Therefore, nothing NoChanges() does can change those values in the calling procedure. 4/15/2019 Prepared by: Deborah Becker

28 Prepared by: Deborah Becker
Q & A Why should I write structured code? If I'm careful, what does it matter how I receive arguments? To make my program easier to read and maintain……… I may want to retain the original value of my data………… 4/15/2019 Prepared by: Deborah Becker

29 Summary General Procedures
User defined Sub Procedures User Defined Functions To insert a Sub procedure or Function into a Form Press Alt/T/P (Receive)Parameters & (Pass) Arguments 4/15/2019 Prepared by: Deborah Becker

30 Rules to Pass By Arguments (A’s) Pass A’s in the same order Same type
Same Number of A’s ByVal ByRef By Reference is the default for VB 4/15/2019 Prepared by: Deborah Becker

31 Prepared by: Deborah Becker
Declared or Passed? What is the difference between a declared variable and a passed argument? An argument must be declared as a variable before you can pass it to another procedure. There it can be renamed but also must be redefined. 4/15/2019 Prepared by: Deborah Becker

32 Definitions Library General Procedure Sub Procedure Function
Collection of Universal Sub Procedures Functions and Sub Procedures A part of a program that perform one or more related tasks A part of a program that perform one or more related tasks and returns a single value. 4/15/2019 Prepared by: Deborah Becker

33 Prepared by: Deborah Becker
Definitions The items appearing inside the parentheses of a Private Sub or Function statement. Parameters Arguments The items appearing inside the parentheses of a call statement Or Function call. 4/15/2019 Prepared by: Deborah Becker

34 Prepared by: Deborah Becker
Structured Programs Sequences Decisions Loops 4/15/2019 Prepared by: Deborah Becker

35 Prepared by: Deborah Becker
Advantages Easy to write Reusable Easier to Maintain Easy to Understand Easy to debug 4/15/2019 Prepared by: Deborah Becker


Download ppt "Sub Procedures Functions And Call Statements"

Similar presentations


Ads by Google