Download presentation
Presentation is loading. Please wait.
Published byKatherine Ward Modified over 8 years ago
1
Excel VBA – Creating Function Procedures Dr Joanna Wyrobek 1
2
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
3
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
4
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
5
=REMOVEVOWELS(A1) 5
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
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
15
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:G20. 2. 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
16
17
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
18
19
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
20
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
21
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
22
FUNCTION EXAMPLES 22
23
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
24
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
25
Functions with one argument Function COMMISSION(Sales) Const Tier1 = 0.08 Const Tier2 = 0.105 Const Tier3 = 0.12 Const Tier4 = 0.14 ‘ Calculates sales commissions Select Case Sales Case 0 To 9999.99: COMMISSION = Sales * Tier1 Case 10000 To 19999.99: COMMISSION = Sales * Tier2 Case 20000 To 39999.99: COMMISSION = Sales * Tier3 Case Is >= 40000: COMMISSION = Sales * Tier4 End Select End Function 25
26
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
27
Functions with 2 arguments Function COMMISSION2(Sales, Years) ‘ Calculates sales commissions based on years in service Const Tier1 = 0.08 Const Tier2 = 0.105 Const Tier3 = 0.12 Const Tier4 = 0.14 Select Case Sales Case 0 To 9999.99: COMMISSION2 = Sales * Tier1 Case 10000 To 19999.99: COMMISSION2 = Sales * Tier2 Case 20000 To 39999.99: COMMISSION2 = Sales * Tier3 Case Is >= 40000: COMMISSION2 = Sales * Tier4 End Select COMMISSION2 = COMMISSION2 + (COMMISSION2 * Years / 100) End Function 27
28
Functions with 2 arguments ROUND(expression, [decimal_places]) LEFT(text, [number_of_characters]) RIGHT(text, [number_of_characters]) [] – optional argument 28
29
Functions with 3 arguments TimeSerial(hour, minute, second) WeekdayName(number, [abbreviate], [firstdayofweek]) 29
30
Functions with 4 arguments SYD(cost, salvage, life, period) DatePart(interval, date, [firstdayofweek], [firstweekofyear]) – returns a specified part of a given date 30
31
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
32
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
33
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
34
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
35
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
36
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
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. 37
38
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.