Excel VBA – Creating Function Procedures Dr Joanna Wyrobek 1.

Slides:



Advertisements
Similar presentations
Excel and Visual Basic. Outline Data exchange between Excel and Visual Basic. Programming VB in Excel.
Advertisements

Microsoft Office XP Microsoft Excel
Using Macros and Visual Basic for Applications (VBA) with Excel
Developing an Excel Application
Tutorial 8: Developing an Excel Application
AE6382 VBA - Excel l VBA is Visual Basic for Applications l The goal is to demonstrate how VBA can be used to leverage the power of Excel u VBA syntax.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Tutorial 12: Enhancing Excel with Visual Basic for Applications
Writing General Procedures Often you will encounter programming situations in which multiple procedures perform the same operation This condition can occur.
VBA Modules, Functions, Variables, and Constants
Example 2.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
String Variables Visual Basic for Applications 4.
XP New Perspectives on Microsoft Office Excel 2003, Second Edition- Tutorial 2 1 Microsoft Office Excel 2003 Tutorial 2 – Working With Formulas and Functions.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one procedure Therefore,
Data Types and Operations Programming Fundamentals (Writing Code)Programming Fundamentals (Writing Code)
1 Computing for Todays Lecture 8 Yumei Huo Spring 2006.
5.05 Apply Looping Structures
VBA & Excel Barry L. Nelson IEMS 465 Fall Quarter 2003.
COMPREHENSIVE Excel Tutorial 8 Developing an Excel Application.
Variables and Constants
Using the Select Case Statement and the MsgBox Function (Unit 8)
XP Abdul Hameed 1 Microsoft Office Excel 2013 Tutorial 2 – Working With Formulas and Functions.
IE 212: Computational Methods for Industrial Engineering
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #4: Working with Variables and User Interfaces IE 212: Computational Methods for Industrial Engineering.
© McGraw-Hill Companies, Inc., McGraw-Hill/Irwin Extended Learning Module M Programming in Excel with VBA.
McGraw-Hill/Irwin Copyright © 2013 by The McGraw-Hill Companies, Inc. All rights reserved. Extended Learning Module M Programming in Excel with VBA.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Enhancing User Interaction Through Programming
Ch 11: Userforms CP212 Winter Topics Designing User Forms o Controls Setting Properties o Tab Order o Testing Writing Event Handlers o Userform_Initialize.
1 VBA – podstawowe reguły języka Opracowanie Janusz Górczyński wg Microsoft Help.
1 Visual Basic for Applications (VBA) for Excel Prof. Yitzchak Rosenthal.
® Microsoft Access 2010 Tutorial 11 Using and Writing Visual Basic for Applications Code.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Microsoft® Excel Use Insert Function. 1 Key and point to enter functions. 2 Navigate with and create named ranges. 3 Use range names in functions.
Lab 01 Forms in excel Tahani ALdweesh Insert form into your project. 2. Change form’s properties. 3. Put controls on the form. 4. Change controls’
Visual Basic.NET Comprehensive Concepts and Techniques Chapter 7 Using Menus, Common Dialogs, Procedures, Functions, and Arrays.
OCC Network Drives  H:\  P:\ 
Date Variables Visual Basic for Applications 5. Objectives n In this tutorial, you will learn how to: n Reserve a Date variable n Use an assignment statement.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Microsoft Visual Basic 2005: Reloaded Second Edition Chapter 3 Variables, Constants, Methods, and Calculations.
A lesson approach © 2011 The McGraw-Hill Companies, Inc. All rights reserved. a lesson approach Microsoft® Excel 2010 © 2011 The McGraw-Hill Companies,
ME 142 Engineering Computation I Using Subroutines Effectively.
Lab 2 Introduction to VBA (II) ► Lab 1 revisited - Sub & Function procedures - Data types and variable declaration ► Recording.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
Introduction to Excel VBA UNC Charlotte CPE/PDH Series December 17, 2009.
XP 1 Microsoft Office Excel 2003 Working With Formulas and Functions.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
XP 1 ﴀ New Perspectives on Microsoft Office 2003, Premium Edition Excel Tutorial 2 Microsoft Office Excel 2003 Tutorial 2 – Working With Formulas and Functions.
Visual Basic Objects / Properties / Methods PropertyAdjective ObjectNoun Part of the application Attribute MethodVerb Action to do something.
Chapter 4 Getting Started with VBA. Subroutines Subroutine is the logical section of code that performs a particular task. Subroutine is also called a.
Controlling Program Flow with Decision Structures.
COMPREHENSIVE Access Tutorial 11 Using and Writing Visual Basic for Applications Code.
An electronic document that stores various types of data.
Chapter 15: Sub Procedures and Function Procedures Spreadsheet-Based Decision Support Systems Prof. Name Position (123) University.
Chapter 4.  Variables – named memory location that stores a value.  Variables allows the use of meaningful names which makes the code easier to read.
Chapter 10 Using Macros, Controls and Visual Basic for Applications (VBA) with Excel Microsoft Excel 2013.
Lecture 6 – Working with VBA Sub Procedures Dr Joanna Wyrobek 1.
COMPREHENSIVE Excel Tutorial 12 Expanding Excel with Visual Basic for Applications.
Excel Tutorial 8 Developing an Excel Application
A variable is a name for a value stored in memory.
VBA - Excel VBA is Visual Basic for Applications
VBA - Excel VBA is Visual Basic for Applications
Spreadsheet-Based Decision Support Systems
Data Validation and Protecting Workbook
2. Understanding VB Variables
Objectives Learn about Function procedures (functions), Sub procedures (subroutines), and modules Review and modify an existing subroutine in an event.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Presentation transcript:

Excel VBA – Creating Function Procedures Dr Joanna Wyrobek 1

Sub Procedures vs Function Procedures A VBA Function is a procedure that performs calculations and returns a value. Function procedures, on the other hand, usually return a single value (or an array), just like Excel worksheet functions and VBA built-in functions. As with built-in functions, your Function procedures can use arguments. Function procedures are versatile, and you can use them in two situations: – As part of an expression in a VBA procedure – In formulas that you create in a worksheet In fact, you can use a Function procedure anywhere that you can use an Excel worksheet function or a VBA built-in function. 2

Function Example (uses 1 arg) Function REMOVEVOWELS(Txt) As String ‘ Removes all vowels from the Txt argument Dim i As Long RemoveVowels = “” For i = 1 To Len(Txt) If Not UCase(Mid(Txt, i, 1)) Like “[AEIOU]” Then REMOVEVOWELS = REMOVEVOWELS & Mid(Txt, i, 1) End If Next i End Function 3

Function Definition Location When you create custom functions that will be used in a worksheet formula, make sure that the code resides in a normal VBA module (use Insert ⇒ Module to create a normal VBA module). If you place your custom functions in a code module for a UserForm, a Sheet, or ThisWorkbook, they won't work in your formulas. Your formulas will return a #NAME? error. 4

=REMOVEVOWELS(A1) 5

Function Procedure Syntax The syntax for declaring a function is as follows: [Public | Private][Static] Function name ([arglist])[As type] [instructions] [name = expression] [Exit Function] [instructions] [name = expression] End Function 6

Function Procedure Elements 1 Public: Optional. Indicates that the Function procedure is accessible to all other procedures in all other modules in all active Excel VBA projects. Private: Optional. Indicates that the Function procedure is accessible only to other procedures in the same module. Static: Optional. Indicates that the values of variables declared in the Function procedure are preserved between calls. Function: Required. Indicates the beginning of a procedure that returns a value or other data. name: Required. Any valid Function procedure name, which must follow the same rules as a variable name. 7

Function Procedure Elements 2 arglist: Optional. A list of one or more variables that represent arguments passed to theFunction procedure. The arguments are enclosed in parentheses. Use a comma to separate pairs of arguments. type: Optional. The data type returned by the Function procedure. instructions: Optional. Any number of valid VBA instructions. Exit Function: Optional. A statement that forces an immediate exit from the Function procedure before its completion. End Function: Required. A keyword that indicates the end of the Function procedure. 8

A Function Scope Here are a few things to keep in mind about a function's scope: If you don't declare a function's scope, its default scope is Public. Functions declared As Private don't appear in Excel's Insert Function dialog box. Therefore, when you create a function that should be used only in a VBA procedure, you should declare it Private so that users don't try to use it in a formula. If your VBA code needs to call a function that's defined in another workbook, set up a reference to the other workbook by choosing the Visual Basic Editor (VBE) Tools ⇒ References command. You do not have to establish a reference if the function is defined in an add-in. Such a function is available for use in all workbooks. 9

Executing Function 1 Although you can execute a Sub procedure in many ways, you can execute a Function procedure in only four ways: – Call it from another procedure (next slide) – Use it in a worksheet formula (following slide) – Use it in a formula that's used to specify conditional formatting (following slide) – Call it from the VBE Immediate window (following slide) 10

Executing Function (2) from Another Procedure You can call custom functions from a VBA procedure the same way that you call built-in functions. For example, after you define a function called SUMARRAY, you can enter a statement like the following: Total = SUMARRAY(MyArray) This statement executes the SUMARRAY function with MyArray as its argument, returns the function's result, and assigns it to the Total variable. You also can use the Run method of the Application object. Here's an example: Total = Application.Run (“SUMARRAY”, “MyArray”) The first argument for the Run method is the function name. Subsequent arguments represent the arguments for the function. The arguments for the Run method can be literal strings (as shown in the preceding), numbers, expressions, or variables. 11

Executing Function (3) in a Worksheet Formula Using custom functions in a worksheet formula is like using built-in functions except that you must ensure that Excel can locate the Function procedure. If the Function procedure is in the same workbook, you don't have to do anything special. If it's in a different workbook, you may have to tell Excel where to find it. You can do so in three ways: Precede the function name with a file reference. For example, if you want to use a function called COUNTNAMES that's defined in an open workbook named Myfuncs.xlsm, you can use the following reference: =Myfuncs.xlsm!COUNTNAMES(A1:A1000) 12

Executing Function (3) in a Worksheet Formula Set up a reference to the workbook. You do so by choosing the VBE Tools ⇒ References command. If the function is defined in a referenced workbook, you don't need to use the worksheet name. Even when the dependent workbook is assigned as a reference, the Paste Function dialog box continues to insert the workbook reference (although it's not necessary). Create an add-in. When you create an add-in from a workbook that has Functionprocedures, you don't need to use the file reference when you use one of the functions in a formula. You'll notice that unlike Sub procedures, your Function procedures don't appear in the Macro dialog box when you issue the Developer ⇒ Code ⇒ Macros command. In addition, you can't choose a function when you issue the VBE Run ⇒ Sub/UserForm command (or press F5) if the cursor is located in a Function procedure. Therefore, you need to do a bit of extra up- front work to test your functions while you're developing them. One approach is to set up a simple procedure that calls the function. If the function is designed to be used in worksheet formulas, you'll want to enter a simple formula to test it. 13

Executing Function (4) in a Formula that's used to Specify Conditional Formatting When you specify conditional formatting, one of the options is to create a formula. The formula must be a logical formula (that is, it must return either TRUE or FALSE). If the formula returns TRUE, the condition is met and formatting is applied to the cell. You can use custom VBA functions in your conditional formatting formulas. For example, here's a simple VBA function that returns TRUE if its argument is a cell that contains a formula: Function CELLHASFORMULA(cell) As Boolean CELLHASFORMULA = cell.HasFormula End Function 14

Executing Function (4) in a Formula that's used to Specify Conditional Formatting After defining this function in a VBA module, you can set up a conditional formatting rule so that cells that contain a formula contain different formatting: 1. Select the range that will contain the conditional formatting. For example, select A1:G Choose Home ⇒ Styles ⇒ Conditional Formatting ⇒ New Rule. 3. In the New Formatting Rule dialog box, select the option labeled Use a Formula to Determine Which Cells to Format. 4. Enter this formula in the formula box — but make sure that the cell reference argument corresponds to the upper-left cell in the range that you selected in Step 1: =CELLHASFORMULA(A1) 5. Click the Format button to specify the formatting for cells that meet this condition. 6. Click OK to apply the conditional formatting rule to the selected range. Cells in the range that contain a formula will display the formatting you specified. In the New Formatting Rule dialog box shown in Figure on the next slide, I am specifying a custom function in a formula. 15

16

Executing Function (5) in the VBE Immediate window The final way to call a Function procedure is from the VBE Immediate window. This method is generally used only for testing. Figure on the next slide shows an example. The ? character is a shortcut for print. You also can execute a procedure by entering its name in the Immediate window of VBE. (If the Immediate window isn't visible, press Ctrl+G.) The Immediate window executes VBA statements while you enter them. To execute a procedure, simply enter the name of the procedure in the Immediate window and press Enter. This method can be useful when you're developing a procedure because you can insert commands to display results in the Immediate window. The following procedure demonstrates this technique: Sub ChangeCase() Dim MyString As String MyString = “This is a test” MyString = UCase(MyString) Debug.Print MyString End Sub 17

18

Passing Arguments to Procedures 1 A procedure's arguments provide it with data that it uses in its instructions. The data that's passed by an argument can be any of the following: A variable A constant An expression An array An object You are probably familiar with many of Excels worksheet functions. Arguments for procedures are similar: A procedure may not require any arguments. A procedure may require a fixed number of arguments. A procedure may accept an indefinite number of arguments. A procedure may require some arguments, leaving others optional. A procedure may have all optional arguments. 19

Passing Arguments to Procedures 2 For example, a few of Excels worksheet functions, such as RAND and NOW, use no arguments. Others, such as COUNTIF, require two arguments. Others still, such as SUM, can use up to 255 arguments. Still other worksheet functions have optional arguments. The PMT function, for example, can have five arguments (three are required; two are optional). 20

Passing Arguments to Procedures 2 The following example shows two procedures. The Main procedure calls the ProcessFile procedure three times (the Call statement is in a For-Next loop). Before calling ProcessFile, however, a three-element array is created. Inside the loop, each element of the array becomes the argument for the procedure call. The ProcessFile procedure takes one argument (named TheFile). Note that the argument goes inside parentheses in the Sub statement. When ProcessFile finishes, program control continues with the statement after the Call statement. Sub Main() Dim File(l To 3) As String Dim i as Integer File(l) = "deptl.xlsx" File (2) = "dept2.xlsx" File (3) = "dept3.xlsx" For i = 1 To 3 Call ProcessFile(File(i)) Next i End Sub Sub ProcessFile(TheFile) Workbooks.Open FileName:=TheFile `’(more code here) End Sub 21

FUNCTION EXAMPLES 22

Functions without arguments Function SHEETCOUNT() ‘ Returns the number of sheets in the workbook SHEETCOUNT = Application.Caller.Parent.Parent.Sheets.Count End Function Function SHEETNAME() ‘ Returns the name of the worksheet SHEETNAME = Application.Caller.Parent.Name End Function 23

Functions without arguments RND() DATE() NOW() To stop RNS from automatic recalculation, use: Application.Volatile True and to restore it Application.Volatile False: Function NONSTATICRAND() ‘ Returns a random number that changes with each calculation Application.Volatile True NONSTATICRAND = Rnd() End Function 24

Functions with one argument Function COMMISSION(Sales) Const Tier1 = 0.08 Const Tier2 = Const Tier3 = 0.12 Const Tier4 = 0.14 ‘ Calculates sales commissions Select Case Sales Case 0 To : COMMISSION = Sales * Tier1 Case To : COMMISSION = Sales * Tier2 Case To : COMMISSION = Sales * Tier3 Case Is >= 40000: COMMISSION = Sales * Tier4 End Select End Function 25

Functions with one argument SQR(number) UCASE, LCASE(text) LN, TAN, ATAN, SIN, COS (number) (Excel function) VALUE(text) FIX (returns the integer portion of a number) ABS (absolue value of a number) EXP(number) CURDIR(drive) FILELEN(file_path) LEN(text) ASC(string) and CHR(ascii_value) LTRIM(text) removes leading spaces from a string TRIM (text) removes leading and trailing spaces ISNUMERIC(text), ISNULL(number) 26

Functions with 2 arguments Function COMMISSION2(Sales, Years) ‘ Calculates sales commissions based on years in service Const Tier1 = 0.08 Const Tier2 = Const Tier3 = 0.12 Const Tier4 = 0.14 Select Case Sales Case 0 To : COMMISSION2 = Sales * Tier1 Case To : COMMISSION2 = Sales * Tier2 Case To : COMMISSION2 = Sales * Tier3 Case Is >= 40000: COMMISSION2 = Sales * Tier4 End Select COMMISSION2 = COMMISSION2 + (COMMISSION2 * Years / 100) End Function 27

Functions with 2 arguments ROUND(expression, [decimal_places]) LEFT(text, [number_of_characters]) RIGHT(text, [number_of_characters]) [] – optional argument 28

Functions with 3 arguments TimeSerial(hour, minute, second) WeekdayName(number, [abbreviate], [firstdayofweek]) 29

Functions with 4 arguments SYD(cost, salvage, life, period) DatePart(interval, date, [firstdayofweek], [firstweekofyear]) – returns a specified part of a given date 30

A Function with an Array Argument Function SUMARRAY(List) As Double Dim Item As Variant SumArray = 0 For Each Item In List If WorksheetFunction.IsNumber(Item) Then _ SUMARRAY = SUMARRAY + Item Next Item End Function 31

A Function with Optional Arguments Function USER(Optional UpperCase As Variant) If IsMissing(UpperCase) Then UpperCase = False USER = Application.UserName If UpperCase Then USER = UCase(USER) End Function 32

A Function with Optional Arguments If you need to determine whether an optional argument was passed to a function, you must declare the optional argument as a Variant data type. Then you can use the IsMissing function in the procedure, as demonstrated in this example. In other words, the argument for the IsMissing function must always be a Variant data type. 33

A Function with Optional Arguments The following is another example of a custom function that uses an optional argument. This function randomly chooses one cell from an input range and returns that cell's contents. If the second argument is True, the selected value changes whenever the worksheet is recalculated (that is, the function is made volatile). If the second argument is False (or omitted), the function isn't recalculated unless one of the cells in the input range is modified. 34

A Function with Optional Arguments Function DRAWONE(Rng As Variant, Optional Recalc As Variant = False) ‘ Chooses one cell at random from a range ‘ Make function volatile if Recalc is True Application.Volatile Recalc ‘ Determine a random cell DRAWONE = Rng(Int((Rng.Count) * Rnd + 1)) End Function 35

A Function that returns a VBA Array VBA includes a useful function called Array. The Array function returns a variant that contains an array (that is, multiple values). If you're familiar with array formulas in Excel, you have a head start on understanding VBA's Array function. You enter an array formula into a cell by pressing Ctrl+Shift+Enter. Excel inserts curly braces around the formula to indicate that it's an array formula. 36

A Function that returns a VBA Array It's important to understand that the array returned by the Array function isn't the same as a normal array made up of elements of the Variant data type. In other words, a variant array isn't the same as an array of variants. 37

A Function that returns a VBA Array It's important to understand that the array returned by the Array function isn't the same as a normal array made up of elements of the Variant data type. In other words, a variant array isn't the same as an array of variants. 38