1 / 0

Sub Procedures and Functions

Sub Procedures and Functions. Procedures in VBA. The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions) We’ve already seen event procedures, which are sub procedures, and we’ve seen Excel user functions Why create more procedures?

anais
Télécharger la présentation

Sub Procedures and Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Sub Procedures and Functions

  2. Procedures in VBA The main idea: encapsulate some code in its own procedure (There are two kinds: Sub Procedures and Functions) We’ve already seen event procedures, which are sub procedures, and we’ve seen Excel user functions Why create more procedures? If we are repeatedly doing the same task, we can write the code in one place and then call the procedure repeatedly; the call is much simpler than the entire code If a program is long and complex, we can break it into understandable parts
  3. Parallel with Problem-Solving Strategies Master a particular task that comes up repeatedly so you don’t have to think about how it works each time it occurs Break a large, complex problem into smaller, more manageable parts
  4. Example: Left Turn When you first learn to drive, you learn a whole procedure for left turn: [Check it is ok to get in the left lane] [Signal a lane change] [Get in the left lane] Signal for a left Slow down at the intersection Look for oncoming traffic or pedestrians; stop if necessary Turn when the way is clear, at a safe speed
  5. Left turn… After you know how to drive, you use this procedure without needing to think through all the steps explicitly If someone says “Turn left” you do all the steps; you don’t need them spelled out You can turn left at any corner, not just the ones where you learned to drive You have internalized a left-turn procedure
  6. Two Aspects of Procedures The Definition: a separate piece of code where the procedure is defined, as we do with event procedures The Procedure Call: A piece of code that invokes a procedure from within an event procedure or other procedure Event procedures, like Form_Initialize or btnProcess_Click in our RealEstate V2 example, are invoked when the event happens, like loading the form or clicking the button, instead of using an explicit call in the code
  7. Definition vs Call The definition is like the place in your brain where you remember how to do the left turn. The definition is established when you learn how to turn left. The call is like having someone tell you, “Turn left at the next corner,” after you know how to drive. It happens in a completely different context than learning to drive, but it makes you go back to what you learned and execute the procedure
  8. Definition vs Call So the procedure definition is the code that tells the computer how to do the procedure The procedure call makes the procedure actually happen (The examples we use next are in workbook SubAndFunctionDemo)
  9. Sub Procedure Definition A sub procedure has a name, possible parameters, and a body of code. Example sub procedure definition: SubPrintAnswer(ByVal param1 As Double,ByVal param2 As Double) Dim answer As Double answer = param1 + param2 lstResults.AddItem ("param1 = " & CStr(param1) & (" param2 = ") & CStr(param2)) lstResults.AddItem ("answer = " & CStr(answer)) End Sub Let’s look at the elements more closely…
  10. Procedure Name Consider the parts of the header: SubPrintAnswer(ByVal param1 As Double,ByVal param2 As Double) PrintAnswer is the name of the procedure. We’ll start procedure names with capital letters (and variable names with lower-case letters). Use a verb in the procedure name; one that reflects what the procedure does.
  11. Parameters SubPrintAnswer(ByVal param1 As Double,ByVal param2 As Double) The (formal) parameters are param1 and param2 A ByVal parameter is very similar to a local variable Its type is declared in the header (these are type Double) Its initial value is set in the procedure call (NOT in the definition!) Changes to ByVal parameters have no effect on variables elsewhere in the program; still, it is best as a programming practice not to set them to new values inside the procedure
  12. More on Formal Parameters SubPrintAnswer(ByVal param1 As Double,ByVal param2 As Double) Recall that variable names are used in two ways On the right side of an assignment statement, a variable name represents a value On the left side, it represents a location where a value can be stored Instead of passing a value to a parameter, we could pass a location, essentially hooking up the formal parameter to a variable elsewhere in the program; this would be a reference parameter. If you don’t specify ByVal, VBA will use pass by reference as a default Reference parameters are used when we want the procedure to change a value elsewhere in the program Our preference is to use value parameters except in very unusual situations
  13. Procedure Body SubPrintAnswer(ByVal param1 As Double, ByVal param2 As Double) Dim answer As Double answer = param1 + param2 lstResults.AddItem ("answer = " & CStr(answer)) End Sub Note the local variable answer The result of calling this procedure is to make some text appear in list box lstResults
  14. Sub Procedure Call A sub procedure is called from elsewhere in the program, for example from within an event procedure The call uses the procedure name and arguments (sometimes called actual parameters) A sub procedure call is a statement Here’s what it might look like: Dim varA, varBAs Double varA = CDbl(txtArg1.Text) varB = CDbl(txtArg2.Text) Call PrintAnswer(varA, varB - 1)
  15. Arguments vs Formal Parameters Arguments are used to feed information to the procedure They are connected with the formal parameters by position; the names are irrelevant Think of the procedure as a sealed room with a slot for each parameter The call puts a value through each slot Inside the room, there is a name on each slot (the name of the formal parameter). Whatever value comes through the slot, that name is used for it throughout the procedure execution. The people inside the room never know what the values are called on the outside
  16. Examples With this procedure code: SubPrintAnswer(ByVal param1 As Double, ByVal param2 As Double) Dim answer As Double answer = param1 + param2 lstResults.AddItem ("answer = " & CStr(answer)) End Sub The procedure call CallPrintAnswer(3, 5) sets param1 = 3 and param2 = 5 CallPrintAnswer(x,y) sets param1 = x and param2 = y, whatever the values of x and y happen to be
  17. Function Procedures Function procedures have one extra element: they return a value We’ve seen examples of functions built into VBA: for example, Format, or any user function A function can have parameters A function returns a result that has a particular data type A function call is an expression with a data type
  18. Function Definition A function procedure definition has a name, possible formalparameters, a body of code, and a type Example function definition: FunctionComputeAnswer(ByVal param1 As Double, ByVal param2 As Double) As Double ComputeAnswer = param1 + param2 End Function
  19. About the Function Definition To set the value returned by the function, we use an assignment to the name of the function: Specifying the type of the function at the end of the header appears to be optional, even with Option Explicit turned on, but it is a good idea to do it Note the function just computes a value and returns (at the end of the code). ComputeAnswer = param1 + param2
  20. Function Call A function is called from elsewhere in the program, for example from within some event procedure The call uses the function name and arguments (sometimes called actual parameters), and returns a value Here’s what it might look like: varA = CDbl(txtArg1.Text) varB = CDbl(txtArg2.Text) answer = ComputeAnswer(varA, varB)
  21. What Happens in a Procedure Call The expressions for the argument values are evaluated, and the formal parameters are set to those values The Dim statements for the procedure are used to create any local variables The code for the procedure is executed Control returns to the line after the procedure call (sub procedure), or to the line of the call with the returned value (function)
  22. A Picture of the Control Flowfor a Procedure Call Some program code Set parameter values Procedure call Procedure code Return value (function) More program code
  23. Let’s look the procedure demo

  24. Procedures and Program Structure The main program in the procedure demo is the event procedure for btnResults We could have simply put all the code in this procedure To make our program better structured and more readable, though, we broke out each major step into its own procedure or function
  25. The Main Procedure Private Sub btnResults_Click() Dim bmi, thrAs Integer 'compute bmi bmi = ComputeBMI() 'compute thr thr = ComputeTHR() 'print results with warning if too fat or thin Call PrintResults(bmi, thr) End Sub
  26. Pseudocode One way to design a program is to use flowcharts Another way is to write pseudocode (“pseudo”, as a prefix, means “false”; it’s pronounced like sudo) With pseudocode, you write down the main steps of the program and as much detail as you want, but informally, instead of as code Then, you gradually fill in with real code
  27. Example In the prior demo there were three main steps I wrote the three steps as pseudocode and inserted them as comments in the event procedure shell for btnResults_Click Then I filled in the code, step by step. I wrote the printing code as I went along to facilitate debugging.
  28. Choices You can use either pseudocode or flowcharts when designing a program (or any other process, for that matter) If you use pseudocode for complex if statements, you should set up the structure of the if statement with indenting, else’s, etc You can always mix and match: for example, write pseudocode but do flowcharts for complex if statements Always do some planning; at the very least, write down your main steps as comments before you start coding
More Related