What is procedure in excel vba

Excel VBA Tutorial about User-Defined FunctionsOne of the most commonly used features in Excel are its functions.

This is hardly surprising. After all, Excel has hundreds of built-in functions.

The variety, in terms of uses and complexity, is quite remarkable. Excel seems to have a function for everything.

But…

Is this really the case?

And…

Even assuming that there is a function for everything, is relying solely on Excel’s built-in functions the most productive way to work?

If these type of questions have ever crossed your mind, and you’ve ever wondered how you can create new functions in Excel, I’m sure you’ll find this tutorial interesting.

On the other hand, you may think that with all the functions that are available in Excel, there is absolutely no need to create new functions. If that is the case, I’m confident that you’ll still find useful information in this blog post. Additionally, I believe that the information within it may just change your opinion.

The reason why I believe that, regardless of your opinion about the need to create new functions in Excel, you’ll find this Excel tutorial interesting is that, indeed, it explains how to you can create your own custom functions (technically called VBA Function procedures). And, just in case you believe this is unnecessary, this guide also provides strong reasons why you should consider creating and using these custom VBA functions.

The main purpose of this tutorial is to introduce to you Excel VBA Function procedures, also known as custom functions, User-Defined Functions or UDFs. More precisely, after reading this Excel tutorial on Excel VBA Function procedures, you’ll know the most relevant aspects regarding the following topics:

Where relevant, every concept and explanation is illustrated with the help of a basic example.

This Excel VBA Function Procedures Tutorial is accompanied by an Excel workbook containing these examples. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Let’s start by understanding, more precisely…

What Is A Procedure: Excel VBA Function Procedures Vs. VBA Sub Procedures

In general terms, a procedure is the part of a computer program that performs a particular task or action. If you’re working with Excel’s Visual Basic Editor, a procedure is the block of statements enclosed by a declaration statement and an End declaration.

When working with Visual Basic for Applications, you’ll constantly encounter 2 types of procedures:

  • Sub procedures, which carry out one or more actions in Excel.
    • Sub procedures don’t require arguments and don’t return data. You’ll see below that Function procedures do both of these.
  • Function procedures, which carry out a calculation and return a value (can be a number or a string) or array.
    • Function procedures are passive: they generally don’t carry out any actions. There is, however, at least one exception to this rule: It is possible to change the text in a cell comment using Function procedures.
    • There are other methods that, when used in a VBA function, can also make changes to a workbook. Additionally, Function procedures that aren’t used in worksheet formulas can do pretty much the same as a regular Sub procedure.

In practice, you’re likely to (mostly) work with Sub procedures. In other words: Most of the procedures you’ll create will (likely) be Sub procedures.

The reason for this is that most macros are small/brief automations. As a consequence, most macros are self-contained Sub procedures.

The fact that most macros are self-contained Sub procedures used to carry out relatively simple jobs shouldn’t stop you from creating more complex and sophisticated macros when required.

As you’ll see in this Excel tutorial, VBA Function procedures can play a key role when creating complex and sophisticated macros. Therefore, let’s take a closer look at…

What Is An Excel VBA Function Procedure

Even if you’re not very familiar with Excel, you’re probably familiar with the concept of functions.

The reason for this is that, even if you’ve never used Visual Basic for Applications, you’ve probably worked quite a bit with worksheet functions. These are the functions that you use every time you create a formula in an Excel worksheet and, as a side-note, you can also use them in VBA.

Some examples of worksheet functions are SUM, IF, IFERROR and VLOOKUP function.

Worksheet functions work very similarly to Excel VBA Function procedures. Worksheet functions (generally) proceed as follows:

  • Step #1: They generally take one or more arguments. There are some exceptions to this rule, as some functions such as TRUE and FALSE take no arguments.
  • Step #2: The functions carry out a particular calculation.
  • Step #3: Finally, a value is returned.

Excel VBA Function procedures do exactly the same thing. In other words, VBA functions take arguments and return values.

VBA Function procedures are very versatile. You can use them both when working with Visual Basic for Applications or directly in an Excel worksheet formula. I explain both ways of executing a VBA Function procedure below.

If Excel VBA Function procedures function similarly to regular worksheet functions, you may wonder…

Why Create And Use Excel VBA Function Procedures?

Excel has hundreds of functions. These functions carry out a huge range of calculations, some more useful than others.

Considering the huge amount of available worksheet functions, you may wonder whether you should take the time to learn how to create additional functions using Visual Basic for Applications.

I hope that, after reading this Excel tutorial and getting an idea about what Excel VBA Function procedures can do for you, you’ll agree with me that it makes sense to learn about this tool and use it when appropriate. The reason is that VBA Function procedures allow you to simplify your work. More precisely: User-Defined Functions (Function procedures) are useful when working with both:

  • Worksheet formulas; and
  • VBA procedures.

The following are some of the advantages of using Excel VBA Function procedures:

  • VBA Function procedures can help you shorten your formulas. Shorter formulas are easier to read and understand. More generally, they are easier to work with.
  • When creating applications, custom functions may help you reduce duplicated code. Among other advantages, this helps you minimize errors.
  • When using VBA functions, you can write functions that perform operations that would (otherwise) be impossible.

The simplicity of of Excel VBA Function procedures (once they’re created) is illustrated by the fact that, once the User-Defined Function (Function procedure) has been created, a regular user (only) needs to know the function’s:

  • Name; and
  • Arguments.

VBA Function procedures can be extremely helpful when creating large and complex VBA projects. The reason for this is that, when working in large projects, you’ll usually create a structure involving multiple procedures (both Sub and Function procedures).

Since VBA Functions take incoming data (arguments) and return other data (values that result from calculations), they’re very useful for purposes of helping different procedures communicate between themselves. In other words, one of the strongest reasons why you should create and use VBA Function procedures is for purposes of improving your VBA coding skills in general. Appropriately working with Function procedures and Sub procedures becomes increasingly important as the size and complexity of your VBA Applications increases.

More precisely, when creating large and complex projects, you can take advantage of the ability of VBA functions to return a value. You can (usually) do this by assigning the name of the Excel VBA Function procedure to a variable in the section of the procedure where you call the function.

I explain how to call VBA Function procedures from other procedures further below.

Basic Syntax Of An Excel VBA Function Procedure

When working with VBA Sub procedures you can, up to a certain extent, rely on Excel’s macro recorder. This allows you to create basic macros by simply carrying out and recording the actions you want the macro to record and store.

When working with Excel VBA Function procedures, you can’t use the macro recorder. In other words, you must always enter the relevant VBA code.

The macro recorder may, however, be a helpful tool for purposes of finding properties (which I explain this blog post) and methods (which I cover here) that you may want to use in the Function procedure you’re creating.

The basic elements of an Excel VBA Function procedure are the following:

  • It always begins with the Function keyword.
  • It always ends with the End Function statement.
  • Between the declaration and End statements, it contains the relevant block of statements with instructions.

As an example, let’s take the following very simple Excel VBA Function procedure (called Squared), which simply squares a certain number which is given to it as an argument.

Excel VBA Function example of syntax

In practice, you’ll be working with much more complex VBA Function procedures. However, this basic function is enough for the purposes of this Excel tutorial and allows us to focus in understanding the concepts that will later allow you to build much more complicated Function procedures.

Let’s take a closer look at the first element of the sample Excel VBA Function above:

Declaration Statement Of An Excel VBA Function Procedure

As you can see in the example above, the first statement is composed of 3 items:

  • The Function keyword, which declares the beginning of the VBA Function procedure.
    Excel VBA Function procedure example Function keyword
  • The name of the VBA Function procedure which, in this example, is “Squared”.
    Excel VBA Function example of name
  • The arguments taken by the VBA function, enclosed by parentheses. In the example above, the Squared function takes only 1 argument: number.
    Excel VBA Function example of an argument
    • If the VBA Function procedure that you’re creating takes several arguments, use a comma (,) to separate them.
    • If you’re creating a function that takes no arguments, leave the parentheses empty. Note that you must always have the parentheses, even if they are empty.
    • I explain the concept of arguments, in the context of Excel VBA Function procedures, in more detail below.

How To Name Excel VBA Function Procedures

The name of the VBA Function procedure appears in the declaration statement itself, as shown above.

As a general rule, Function procedure names must follow the sale rules as variable names. These rules are substantially the same as those that apply to naming naming VBA Sub procedures and, more generally, to most items or elements within the Visual Basic for Applications environment.

The following are the main rules when naming variables:

  • Names must start with letters.
  • As long as the name complies with the above, they can also include numbers and certain (not all) punctuation characters. For example, underscore (_) is commonly used.
  • The maximum number of characters a name can have is 255.
  • Names can’t be the same as any of Excel’s key words, such as “Sheet”.
  • No spaces are allowed. In other words, names must be a “continuous string of characters only”.

The following are common additional suggestions for naming your VBA Function procedures:

  • Don’t use function names that match a cell reference or a named range, such as A1.
    • If you do this, you can’t use that particular VBA function in a worksheet formula. If you try to do it, Excel displays the #REF! error.
  • Don’t use VBA Function procedure names that are the same as that of a built-in function, such as SUM.
    • This causes a name conflict between functions. In such cases, Excel uses the built-in function instead of the VBA function.

You may have noticed that the names of Excel’s built-in functions are always in uppercase, such as SUM, IFERROR or AND. Some VBA users like to use uppercase names, so that they match Excel’s style. This is (however) not mandatory.

For example, I have not applied this same formatting rule in the examples that appear in this Excel tutorial, where the sample VBA functions are called “Squared”, “Squared_Sign”, “Squared_Sign_2” and “Squared_Sign”.

How To Tell An Excel VBA Function Procedure Which Value To Return

The sample Excel VBA Function above only contains one statement between the declaration statement and the End declaration statement: “Squared = number ^ 2”.

Excel VBA Function example of main statement

This statement simply takes a number, squares it (elevates it to the power of 2), and assigns the resulting value to the variable Squared. You’ll notice that “Squared” is also the name of this Excel VBA Function procedure.

Excel VBA Function example of name and variable assignment

The reason for the name of the variable matching the name of the function is that this is how you tell an Excel VBA Function procedure which value to return. You specify the value to return by assigning that value to the function’s (Function procedure’s) name.

In other words, in these cases, the name of the function also acts as a variable. Therefore, when working with Function procedures, you’ll constantly encounter the name of the function being used as the name of a variable within the Function procedure itself. You must (as a general rule) assign a value to the Function procedure’s name one time (as a minimum).

You may see this clearer when dividing the process followed by a VBA function in the following 3 steps:

  • Step #1: The function carries out the relevant calculations.
  • Step #2: The VBA function assigns the obtained results to its own name.
  • Step #3: Once the function ends, it returns the results.

Therefore, when creating Excel VBA Function procedures, you want to ensure that the condition above is complied with. In other words, make sure that, somewhere in the main body of the VBA code, the correct value is assigned to the variable that corresponds to the function name. In the example above, the only statement of the function assigns a value to the Squared variable.

Once an Excel VBA Function procedure has carried out any intermediate calculations, it returns the final value of the variable whose name is the same as the function’s name.

In the example above, the name of the function and returned variable is “Squared”. Therefore, once the VBA Function procedure carries out the required calculations, it returns the final value of the variable Squared.

Arguments Within Excel VBA Function Procedures

Arguments are the information or data that a function uses as input to carry out calculations.

When working with Excel VBA Function procedures you’ll usually encounter arguments in the following 2 situations:

  • Situation #1: When declaring an Excel VBA Function procedure, you always include a set of parentheses. This is where you include the arguments taken by the function. If the function takes no arguments at all, you leave the parentheses empty.
    • The Squared VBA Function used as an example above takes only 1 argument: number.
      Example of argument in Excel VBA Function procedure
  • Situation #2: When executing the VBA Function procedure, you’ll usually (although not always) enter the arguments that the function must use to carry out its calculations.
    • You can see how to execute an Excel VBA Function procedure, and enter the relevant arguments, below.

The following is a list of important points to bear in mind when working with both regular worksheet functions and VBA Function procedures.

  • There are several ways in which a function can receive arguments. You can use any of the following as formula arguments:
    • #1: Cell references.
    • #2: Variables, including arrays.
    • #3: Constants.
    • #4: Literal values.
    • #5: Expressions.
  • The number of arguments vary from function to function.
    • There are functions that have absolutely no arguments, such as TRUE and FALSE.
    • On the other hand, there are functions that can take a very large number of arguments. For example, functions such as AND or OR can take up to 255 arguments. This leads me to the last point…
  • Arguments can be either required or optional. The number of required or optional arguments varies between functions.
    • Some functions have only a fixed number of required arguments. For example, the IF function has 3 required arguments.
    • Other functions combine required and optional arguments. Examples of such functions are LEFT and RIGHT, which you can use to find what the first (LEFT) or last (RIGHT) characters in a text string are.

After seeing this last point, you may now be wondering…

How To Create Excel VBA Function Procedures With Optional Arguments

You already know how to declare the arguments of an Excel VBA Function procedure by listing them within parentheses when you declare the function.

Arguments are mandatory by default. If, when calling a VBA function, you forget to input them, the function won’t be executed.

In the case of the Excel VBA Function procedure Squared, which I’ve used as an example above, the argument number is required.

Required argument in a VBA Function procedure

In order to make an argument optional, you need to list it differently. More precisely, optional arguments are:

  • Preceded by the Optional keyword. This allows Excel to understand that the particular argument is optional.
  • Ideally, although not required, followed by an equal sign and the default value for the optional argument. This determines the value that the Excel VBA Function procedure uses if the optional argument is not passed on to the function.
    • The default value can be a string, a constant or a constant expression.
  • Always last in the list of arguments within the parentheses. Once you use the Optional keyword, all the arguments that follow it must also be optional.

Let’s take a look at an example:

When squaring a number (even if the number is negative), the result is a non-negative number. For example, you can square both –10 or 10 and, in both cases, the result is 100.

Let’s assume that, in some situations, you need a negative number. In other words, you’d like to have the ability to ask Excel to return a non-positive number, such as –100 instead of 100 (when squaring –10 or 10).

For these purposes, you can use an Excel VBA Function procedure such as the following, called “Squared_Sign”:

Excel VBA Function procedure with optional argument

The VBA code of Squared_Sign shares many items that are also in code for the simpler Squared VBA Function procedure.

In fact, all of the items that appear in the VBA code of Squared also appear in the code of Squared_Sign. Take a look at the following image, which underlines them:

Repeated items in Excel VBA Function procedure

You already know what each of these items does. When put together, the sections that are underlined above simply take the argument (number) and square it.

There are only 2 new elements that have been added to the Squared_Sign function, as compared to the original Squared VBA Function procedure. These are the ones that give users the option to ask Excel to return a non-positive number by using an optional argument. Let’s take a closer look at them:

An alternative, although slightly more advanced, approach to the above situation involves using the IsMissing function.

The IsMissing function is particularly helpful for purposes of testing whether an optional argument has been given. In other words, IsMissing returns a logical value that indicates whether a particular Variant argument has been passed to the relevant procedure. More precisely:

  • If no value is passed to IsMissing, it returns True.
  • Otherwise, IsMissing returns False.

The VBA Function procedure (called Squared_Sign_2) that appears in the image below uses the IsMissing function to proceed as follows:

  • Step #1: If the second argument (called negative) is False or missing, IsMissing sets the value of “negative” to its default value of False.
    • If negative is False, the function returns a positive number. This is the same result obtained with the Squared VBA function.
  • Step #2: If the argument called negative is True, the Squared_Sign_2 VBA function returns a negative number.

VBA Function procedure with optional argument

How To Create Excel VBA Function Procedures With An Indefinite Number Of Arguments

There are some built-in functions that can take an “indefinite” number of arguments.

By “indefinite”, I mean up to 255.

One example of a built-in function that accepts an indefinite number of arguments in Excel is SUM. Take a look at the following screenshot of how this looks like in the Function Arguments dialog:

Example of Excel function with unlimited arguments

You can also create VBA Function procedures that take an unlimited number (meaning up to 255) arguments. You do this as follows:

  • Use an array as the last or only argument in the list of arguments that you include in the declaration statement of the VBA function.
  • Use the ParamArray keyword prior to that final (or only) array argument.

When used in the context of a VBA Function procedure, ParamArray indicates that the final argument of that function is an “optional array of Variant elements”.

You can’t use ParamArray alongside other optional keywords in the argument list of a VBA Function, such as Optional, ByVal or ByRef. Therefore, you can’t use both Optional and ParamArray in the same function.

Let’s see how ParamArray works in practice by creating a function that proceeds as follows:

  • Step #1: Squares (elevates to the power of 2) a particular number. This is what the (less complex) Squared VBA Function achieves.
  • Step #2: Sums the squared numbers.

The following VBA Function procedure (called “Squared_Sum”) is a relatively simple way of achieving this. Notice how the arguments are declared as an optional array of elements of the Variant data type.

VBA code for Function procedure with unlimited arguments

This Excel VBA Function procedure isn’t particularly flexible. For example, it fails if you use a range of cells as argument and 1 of the cells contains a string (instead of a number).

However, for our purposes, Squared_Sum gets the job done. It particularly illustrates how you can use the ParamArray keyword to create VBA functions with an unlimited number of arguments.

In order to test that the Squared_Sum function works as planned, I have created an array listing the integers from 1 to 100 and applied Squared_Sum to it.

Application of VBA Function with unlimited arguments

In order to confirm that the result returned by Squared_Sum is correct, I manually (i) squared each of the numbers in the array and (ii) added those squared values. Check out the 2 screenshots below showing how I set up this control:

Control 1 from Function procedure with unlimited parameters

Control 2 for VBA Function procedure with unlimited arguments

As shown in the image below, the results returned by both methods are exactly the same.

Results of VBA Function procedure with unlimited arguments

The Squared_Sum VBA function is, however, easier and faster to implement than carrying out the calculations manually or creating long and complicated nested formulas.

This Excel VBA Function Procedures Tutorial is accompanied by an Excel workbook containing the data and procedures I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Other Optional Items For An Excel VBA Function Procedure

The syntax described in the sections above outlines and illustrates the basic items you should include in the VBA code of a Function procedure.

Below is a much more comprehensive syntax for declaring functions, by including all its optional elements. Let’s take a look at it:

[Public | Private] [Static] Function name ([arglist]) [As type]
    [instructions]
    [name = expression]
    [Exit function]
    [instructions]
    [name = expression]
End Function

Notice that this structure shares many elements in common with that of a Sub procedure.

Let’s take a look at the optional elements (within brackets [ ]) that appear in the structure above.

Element #1: [Public | Private]

Private and Public are access modifiers and determine the scope of the VBA Function procedure. This means that the access modifiers are used to determine if there are any access restrictions in place.

In more practical terms, this is important because the scope of a function is what determines whether that particular VBA function can be called by VBA procedures that are stored in other modules or worksheets.

More precisely:

  • Public Function procedures have no access restrictions. As a consequence, they can generally be accessed by all other VBA procedures in any module within any active Excel VBA project.
    • Public is the default scope of VBA functions.
    • Despite the above, Excel VBA Function procedures within a module that uses the Option Private statement, are not accessible from outside the relevant project.
  • Private Function procedures are restricted. Therefore, only other VBA procedures within the same module can access them.
    • Additionally, Private functions are not listed in Excel’s Insert Function dialog, which is one of the ways of calling an Excel VBA Function procedure. Knowing this is useful if you’re creating VBA functions that are designed to be called only by a Sub procedure. In that case, you can declare the relevant function as Private to reduce the probability of a user using such a function in a worksheet formula.
    • Declaring an Excel VBA Function procedure as Private doesn’t fully prevent that function from being used in a worksheet formula. It simply prevents the display of the relevant function in the Insert Function dialog. I explain how you can call a VBA function using a worksheet formula below.

Element #2: [Static]

If you use the Static statement, any variables declared within the VBA Function procedure retain their values “as long as the code is running”. In other words, the values of any variables declared within the function are preserved between calls of the function.

Element #3: [arglist]

I explain the concept of arguments above.

Even though arguments are optional, meaning that you can have an Excel VBA Function procedure that takes no arguments, the set of parentheses after the Function name isn’t optional. You must always have the set of parentheses.

Element #4: [As type]

The As keyword, when combined with the Type statement, is used to determine which data type the VBA Function procedure returns.

Even though this item is optional, it’s (also) commonly recommended.

Element #5: [instructions]

Instructions are the VBA instructions that determine the calculations to be carried out by the Excel VBA Function procedure.

I mention these above as, generally, most Excel VBA Functions include some instructions.

Element #6: [name = expression]

This element makes reference to the fact that a correct value must be assigned to the variable that corresponds to the function name at least 1 time. This happens, generally, when execution of the instructions is completed.

An easy way to ensure that you’re meeting this condition is to follow the syntax “name = expression”, where:

  • “name” is the name of the Excel VBA Function procedure.
  • The name is followed by an equal (=) sign.
  • “expression” is the value that the function should return.

Despite the above, this item is technically optional.

This topic is further explained above, where I explain how the value that a VBA function returns is determined.

Element #7: [Exit Function]

The Exit Function statement immediately exits the Function procedure.

Where To Store Excel VBA Function Procedures

There are 2 separate points that you may want to consider when storing an Excel VBA Function procedure. Let’s take a look at them:

Point #1: Always Store Excel VBA Function Procedures In Standard Modules

VBA code is generally stored in a module.

There are, however, a few different types of modules. If you put your VBA code in the wrong module, Excel isn’t able to find it or execute it.

Excel VBA Function procedures should always be stored in a standard module.

Make sure that you don’t store your Function procedures in other type of modules. If you fail to store your functions in a standard module, those formulas return the #NAME? error when executed.

The reason for this is that, when you enter a VBA Function procedure in another module, Excel doesn’t recognize that you’re creating a new VBA function.

You can refer to The Beginners Guide to Excel’s Visual Basic Editor, to see how you can insert and remove VBA modules.

As long as you meet the requirement of storing your VBA functions in standard modules, you can store several VBA Function procedures in a single module.

Point #2: Suggestions To Determine Where To Store Excel VBA Function Procedures

Consider the following guidelines to decide where to store VBA Function procedures:

  • If the particular VBA function is only for your use, and won’t be used in another computer, store it in your personal macro workbook: Personal.xlsb.
    • The personal macro workbook is a special type of workbook where you can store macros that are generally available when you use Excel in the same computer. This is the case, even if you’re not working on the same workbook in which you created the macro.
  • If you need to distribute an Excel workbook that contains a VBA function to several people, store the function in that workbook.
  • If you need to create several workbooks that use the same VBA Function procedure, and you’ll be distributing the workbooks to many people, store the function in a template.
  • If you’ll be sharing a workbook with a VBA function among a determined group of people, use an add-in.
    • You may also want to consider using an add-in for storing functions that you use constantly. The following are the 2 (main) advantages of using add-ins for these purposes:
      • Advantage #1: Once the add-in is installed, you can use the functions in any Excel workbook.
      • Advantage #2: You can, slightly, simplify your formulas whenever you’re using VBA functions that aren’t stored in the same Excel workbook you’re working in. The reason for this is that you avoid the need of having to tell Excel where is the VBA function by providing a filename qualifier. I explain the topic of such references in detail below.
    • Using a add-ins, however, also carry some disadvantages. The more important disadvantage is that your Excel workbooks become dependent on the add-in file. Therefore, whenever you share a workbook that uses a VBA function stored in an add-in, you also need to share the relevant add-in.

VBA Data Types And Excel VBA Function Procedures

I explain why learning and understanding the different VBA data types is important here.

At the most basic level, data types determine the way in which data is stored in the memory of a computer.

An inadequate choice or use of VBA data types usually results in an inefficient use of the memory. This inefficient use may have different effects in practice, with the most common being a slower execution of the VBA applications where data types are chosen or used incorrectly.

In the context of Excel VBA Function procedures, VBA data types are important in 2 scenarios:

  • Scenario #1: An Excel VBA Function procedure can return different types of data types. You can choose which particular VBA data type is returned by a Function procedure.
    • You can find an explanation of how to use the As keyword and Type statement for purposes of setting the appropriate data type above.
    • You should generally make use of this option and explicitly determine the data type returned by any function.
  • Scenario #2: When declaring arguments for an Excel VBA Function, you can also use the As keyword and Type statement for purposes of determining its data type.
    • Some advanced VBA user argue that specifying the data type is always a good idea because it helps you conserve memory and, mainly, helps you avoid errors caused by other procedures passing the incorrect type of information to a function.
    • It goes without saying that you should ensure that the data type of the argument matches the data type expected by the relevant procedure.

How To Execute An Excel VBA Function Procedure

I explain 9 ways in which you can execute a VBA Sub procedure here. The options to execute, run or call an Excel VBA Function procedure are much more restricted. In particular, you can’t execute an Excel VBA Function procedure directly by using the same methods you can use to execute a VBA Sub procedure, such as using the Macro dialog, a keyboard shortcut, or a button or other object.

You can generally only execute a Function procedure in the following 3 (broad) ways:

  • Option #1: By calling it from another procedure. The calling procedure can be either a VBA Sub procedure or a VBA Function procedure.
  • Option #2: By calling it from the Immediate Window of the Visual Basic Editor.
  • Option #3: By using it in a formula, such as a worksheet formula or a formula used to specify conditional formatting.

Let’s take a look at how you can implement each of these options:

Option #1: How To Call An Excel VBA Function Procedure From Another Procedure

Let’s take a look again at the sample Excel VBA Function procedure called Squared:

Excel VBA Function example

The easiest method to call an Excel VBA Function Procedure is to simply use the function’s name. When using this particular method, you simply need to enter 2 things in the VBA code of the calling procedure:

  1. The name of the Excel VBA Function procedure being called.
  2. The argument(s) of the procedure being called.

As an example, let’s create a very simple VBA Sub procedure (named Squared_Caller) whose only purpose is to call the Squared VBA Function procedure to square the number 15 and display the result in a message box.

Excel VBA called Sub procedure example

If you execute the above macro, Excel displays the following message box:

Result of Excel VBA Function procedure

Let’s take a look at the process followed by the Squared_Caller Sub procedure step-by-step.

  • Step #1: The Squared_Called Sub procedure is called using any of the methods that can be used to execute an Excel VBA Sub procedure.
  • Step #2: The Squared_Called Sub procedure calls the Squared function procedure and passes to it the argument of 15.
  • Step #3: The Squared function receives the argument of 15.
  • Step #4: The Squared function performs the relevant calculation (squaring) using the value it has received as an argument. The resulting value when squaring 15 is 225.
  • Step #5: The Squared function assigns the result of its calculations (225) to the variable Squared.
  • Step #6: The Squared function ends and control returns to the Squared_Called Sub procedure.
  • Step #7: The MsgBox function displays the value of the Squared variable which, as explained above, is 225.

Alternatively, you can use the Application.Run method. In this case, the equivalent of the Squared_Caller VBA Sub procedure that appears above, is as the following Sub procedure (called Squared_Caller_Run):

How to call Function procedure with Application.Run method

The first argument of the Application.Run method is the macro to run (Squared in the case above). The subsequent parameters (there is only 1 in the example above) are the arguments to be passed to the function being called.

The following can be arguments when using the Application.Run method:

  • Strings.
  • Numbers (as above).
  • Expressions.
  • Variables.

Option #2: How To Call An Excel VBA Function Procedure From The Immediate Window Of The Visual Basic Editor

The Immediate Window of the Visual Basic Editor is very useful for purposes of checking, testing and debugging VBA code.

The following image shows a possible way of calling the Squared VBA function from the Immediate Window:

call vba function procedure immediate window

The word Print that appears in the Immediate Window above allows you to evaluate an expression immediately. Alternatively, you can use a question mark (?), which acts as a shortcut for Print.

Option #3: How To Call An Excel VBA Function Procedure Using A Formula

You can’t execute VBA Sub procedures directly by using a worksheet formula. This is because a Sub procedure doesn’t return a value.

Executing an Excel VBA Function procedure using a worksheet formula is relatively simple, as long as you have some basic familiarity with regular worksheet functions.

In fact, working with an Excel VBA Function procedure in this way is substantially the same as working with the regular worksheet functions such as SUM, IF, IFERROR and VLOOKUP.

The main difference between built-in worksheet formulas and VBA Function procedures is that, when using VBA functions, you must make sure that (when necessary) you tell Excel the location of the function. This is the case, usually, when you’re calling Excel VBA Function procedures that are stored in a different workbook from the one you’re working on. I explain how to do this further below.

In addition to using VBA Function procedures in worksheet formulas, you can use them in formulas that specify rules for conditional formatting. When creating conditional formatting formulas, the logic is similar to that explained below.

In order to understand this, let’s take a look at 2 of the most common methods for executing a worksheet function and see how they can be applied for purposes of executing a VBA Function procedure.

Method #1: How To Enter A Formula Using A VBA Function Procedure

If you’ve worked with formulas before, you’re probably aware that you can generally execute worksheet functions by entering a formula into a cell.

You can do exactly the same with VBA Function procedures. In other words, you can execute a Function procedure by simply typing a formula in a cell. This particular formula must contain the Function procedure you want to execute. For these purposes:

  • The name of the function is exactly the same name you’ve assigned to the Excel VBA Function procedure.
  • The arguments, if applicable, are entered within the parentheses that follow the name of the function (just as you’d do with any other function).

As an example, let’s assume that you want to execute the sample Squared VBA Function procedure to square the number 10. For these purposes, simply type the following formula in a cell:

Excel VBA Function example worksheet formula

As expected, the result that Excel returns is the value 100.

Result of Excel VBA Function in worksheet formula

The syntax described above only works when you’re executing Excel VBA Function procedures from the same Excel workbook as that which contains the function you’re calling, or when the function is stored in an add-in. Functions stored in add-ins are available for use in any Excel workbook.

Let’s assume, however, that you’re actually working in a different Excel workbook from the one that contains the module with the Function procedure you want to call. In these cases, you must tell Excel where it can find the VBA function you want to work with.

In such a case, you can proceed in either of the 2 following ways. This assumes that the VBA Function procedure you want to refer to is Public, and not Private.

Option #1: Include File Reference Prior To Function Name.

In this case, you must modify the syntax slightly by adding the name of the relevant workbook before the function name. When doing this, make sure that:

  • You separate the worksheet and function names using an exclamation mark (!).
  • The Excel workbook that contains the relevant Function procedure is open.

For example, let’s assume that the Squared VBA Function procedure above is defined in the Excel workbook Book1.xlsm. You’re working in a different Excel workbook, and want to square the number 10 using Squared. In such case, the formula that you should type is as follows:

VBA Function procedure syntax with different workbook

As expected, Excel returns the value 100.

Result of applying VBA Function procedure in another workbook

Option #2: Set Up A Reference To Appropriate Excel Workbook.

You can set up a reference to the appropriate Excel workbook using the References command of the Visual Basic Editor. You can find this in the Tools menu of the VBE.

Reference a VBA Function procedure using the VBE

If you choose to set up a reference to the Excel workbook where the relevant VBA Function procedure is stored, you don’t need to modify the syntax to include the file reference prior to the Function name.

Let’s take a look now at the second way in which you can call an Excel VBA Function procedure using a formula:

Method #2: How To Execute A VBA Function Procedure Using The Insert Function Dialog

You can also (generally) execute VBA Function procedures by using the Insert Function dialog. The main exception to this rule are VBA functions that are defined as Private.

Using the Private keyword is useful when you create VBA Function procedures that aren’t designed to be used in formulas. These functions are, then, generally executed by calling them from another procedure.

Let’s see how to execute a VBA function using the Insert Function dialog in the following 4 easy steps.

Step #1: Display The Insert Function dialog.

To get Excel to display the Insert Function dialog, click on “Insert Function” in the Formulas tab of the Ribbon or use the keyboard shortcut “Shift + F3”.

How to display Insert Function dialog in Excel

Step #2: Ask Excel To Display User Defined Functions.

Once you’ve clicked on “Insert Function”, Excel displays the Insert Function dialog. Functions are organized in different categories, such as Financial, Text and Logical. You can see all the categories by clicking on the Or select a category drop-down menu.

Insert Function dialog in Excel

For the moment, the category we’re interested in is User Defined functions. Therefore, click on “User Defined”.

User Defined Functions in Insert Function dialog

Excel VBA Function procedures appear in the list of User Defined functions by default. You can, however, change the category in which such functions appear by following the procedure that I describe below.

You can’t use the search feature at the top of the Insert Function dialog for purposes of searching VBA functions.

The following screenshot shows what happens if I search for the Squared VBA Function procedure. Notice how none of the functions that appear in the Select a function list box is the one I’m actually looking for.

Search VBA Function procedure in Excel

Step #3: Select The Excel VBA Function Procedure To Be Executed.

Once you’ve selected User Defined functions, Excel lists all the available VBA Function procedures in the Select a function list box.

Select the function that you want to execute and click on the OK button located on the lower right corner of the Insert Function dialog.

In the example image below, there’s only 1 VBA Function procedure: Squared. Therefore, in order to execute Squared, I select it and click on the OK button, as shown in the image below.

Execute Excel VBA Function procedure in Insert Function dialog

Step #4: Insert The Arguments For The Excel VBA Function Procedure.

Once you’ve selected the Excel VBA Function procedure to be executed, Excel displays the Function Arguments dialog.

Enter the relevant argument(s) that the function should work with (if any). Once you’ve entered these arguments, click the OK button on the lower right corner of the Function Arguments dialog to complete the process.

In the case of the sample Squared VBA Function procedure, the Function Arguments dialog looks as follows. Just as in the example above (entering a formula directly on the active cell), I enter the number 10 as argument.

Function Arguments dialog in Excel

As expected once again, the result returned by Excel is 100, which is correct.

Result of VBA Function procedure

Despite the fact that, operationally, executing an Excel VBA Function procedure is substantially the same as executing a regular worksheet function, you may have noticed 1 key difference:

Excel usually displays a description of worksheet functions. This happens regardless of which of the 2 methods described above you use. However, the same doesn’t happen (automatically) in the case of VBA Function procedures.

Let’s take a closer look at this difference, and see how we can get Excel to display the description of any VBA Function procedure:

How To Add A Description For An Excel VBA Function Procedure

First, let’s take a look at the way in which Excel displays the descriptions of regular worksheet functions, depending on which of the 2 methods of executing functions (described above) you’re using.

Method #1: Entering A Formula On An Active Cell

If you’re entering a function on an active cell, Excel displays a list of functions that can be used to complete the formula you’re writing. Additionally, Excel displays the description of the function that is currently selected in that list.

The following image shows how Excel automatically displays a list of options while I’m typing “=sum” to help me complete the formula. Note, in particular, how Excel describes the SUM function using tooltips.

Worksheet function description

Excel also includes VBA Function procedures in its list of suggestions to complete a formula. However, it doesn’t show a description of those functions.

For example, when I type “=squared”, Excel does suggest the Squared VBA Function procedure that I’ve created. However, it doesn’t display any description.

Entering VBA Function without description

Method #2: Using The Insert Function Dialog

A similar thing happens if you’re using the Insert Function dialog for purposes of executing a function.

As a general rule, the Insert Function dialog displays the description of the function that is currently selected in Select a function list box. You see this on the lower section of the Insert Function dialog.

For example, in the case of the SUM function, the Insert Function dialog looks roughly as follows:

Description of worksheet function in Insert Function dialog

However, in the case of the Squared VBA Function procedure, things look different. As you’ll notice in the image below, the Insert Function dialog states that no help is available.

VBA Function procedure in Insert Function dialog

In this Excel Macro Tutorial for Beginners, I explain why you should get in the habit of describing your macros. Among other benefits, this allows you and other users to be aware (always) of what a particular macro does and what to expect when running it.

This suggestion also applies to Excel VBA Function procedures. Ideally, you should always add a description for any function you create.

Therefore, let’s take a look at how you can add a description for a VBA Function procedure in Excel:

How To Add A Description For An Excel VBA Function Procedure When Using The Insert Function Dialog

You can add a description for an Excel VBA Function procedure using either of the following 2 methods.

Any description of an Excel VBA Function procedure that you add using either of these 2 methods is only displayed when working with the Insert Function dialog. In other words, this method doesn’t add a tooltip that appears when entering a formula in an active cell.

Method #1: Using The Macro Dialog

You can add a VBA function description using the Macro dialog in the following 3 simple steps.

Step #1: Open The Macro Dialog.

To open the Macro dialog, click on “Macros” in the Developer tab of the Ribbon or use the keyboard shortcut “Alt + F8”.

How to open Macro dialog

Excel displays the Macro dialog. You’ll notice that this dialog lists only VBA Sub procedures. Excel VBA Function procedures don’t appear.

For example, in the following screenshot, the only macro that is listed is Squared_Caller. As I explain above, this is a VBA Sub procedure whose only purpose is to call the Squared Function procedure.

Macro dialog without VBA Function procedures

Take a look at the following step to see how to work with VBA Function procedures from the Macro dialog.

Step #2: Type The Name Of The VBA Function Procedure You Want To Describe And Click On The Options Button.

Despite the fact that the Macro dialog doesn’t display Excel VBA Function procedures, you can still work with them using the Macro dialog.

For these purposes, simply enter the name of the relevant function in the Macro name field. Once you’ve entered the appropriate name, click on the Options button located on the right side of the Macro dialog.

For example, when working with the VBA function called Squared, type “Squared” and click on “Options” as shown in the image below.

How to work with VBA Function in Macro dialog

Step #3: Enter A Description Of The Excel VBA Function Procedure And Click The OK Button.

After you click “Options” in the Macro dialog, Excel displays the Macro Options dialog.

Type the description you want to assign to the VBA Function in the Description box and click on the OK button on the lower right corner of the Macro Options dialog.

The following image shows how this looks like in the case of the Squared VBA Function procedure.

Add description for VBA Function procedure

Step #4: Click On The Cancel Button.

Once you’ve entered the description of the Excel VBA Function procedure and clicked the OK button, Excel returns to the Macro dialog.

To complete the process of assigning a description to a VBA Function, click on the Cancel button on the lower right corner of the Macro dialog.

How to complete assignment of description to VBA Function

Notice how the Macro dialog displays (on its lower part) the new description of the Excel VBA Function procedure.

Description of Excel VBA Function procedure

Next time you execute the Excel VBA Function using the Insert Function dialog, Excel displays the relevant description that you’ve added. For example, the following image shows how the description of the Squared function appears in the Insert Function dialog.

Description of Excel VBA Function procedure in dialog

As mentioned at the beginning of this section, this way of adding a description to an Excel VBA Function procedure doesn’t add a tooltip when entering a formula in an active cell. For example, when entering “=squared”, Excel continues to suggest the Squared VBA Function without showing its description.

Excel VBA Function procedure without description
As I explain below, this issue is more complicated to solve and exceeds the scope of this Excel VBA tutorial.

Method #2: Using The Application.MacroOptions Method

You can also add a description for an Excel VBA Function procedure using VBA code. For these purposes, you use the Application.MacroOptions method.

The main use of the Application.MacroOptions method is that it allows you to work with the Macro Options dialog. As shown below, you can also use this method for purposes of changing the category of an Excel VBA Function procedure.

The Application.MacroOptions method has several optional parameters. In this particular case, I only use 1 argument: Description. As you may expect, this argument determines the description of the VBA function.

The following macro (called Function_Description) is an example of how Application.MacroOptions can be applied for purposes of adding a description for the Squared_Sign VBA Function procedure:

VBA code for Function procedure description

You only need to execute this macro once. Once the Function_Description macro has run, and you’ve saved the Excel workbook, the description you’ve assigned to the VBA function is stored for the future.

The following image shows how this description looks like in the Insert Function dialog:

Excel VBA Function procedure with description

However, just as with the previous method, this way of adding a description isn’t able to make Excel show a tooltip when entering a formula with the Squared_Sign function in an active cell. Notice how, in the image below, Excel doesn’t display any description for this particular VBA function:

Excel Function procedure without tooltip

You may be wondering:

Is there a way to make Excel display a description of a VBA Function procedure when entering a formula in an active cell?

Let’s take a brief look at this topic:

The Issue Of Adding A Description For An Excel VBA Function Procedure When Entering A Formula

Let’s go back to the question above:

Is it possible to add a description for an Excel VBA Function procedure that will be displayed when entering a formula in an active cell?

The short answer is no. Currently you can’t add a tooltip for an Excel VBA Function procedure such as those that appear when working with the standard worksheet functions. This may change in the future.

The longer answer is more complicated. The topic of adding a description for an Excel VBA Function procedure when entering a formula has been the subject of several discussions.

The way I usually handle the lack of a function description when entering formulas with Excel VBA Function procedures is by using the keyboard shortcut “Shift + Ctrl + A” to get Excel to display all the arguments of the function.

You can implement this workaround in the following 2 easy steps.

Step #1: Type The Formula With The Name Of The Relevant Excel VBA Function Procedure

This is self-explanatory. Simply type a formula as you’d usually do.

For example, if working with the Squared VBA Function procedure, simply type “=squared”.

Typing formula with VBA Function procedure

Step #2: Press The Keyboard Shortcut “Ctrl + Shift + A”

Once you’ve typed the name of the relevant Excel VBA Function, use the keyboard shortcut “Ctrl + Shift + A”.

Once you do this, Excel displays all the arguments of the Excel VBA Function procedure in order to help you complete the formula. For example, in the case of the Squared function, Excel displays the following:

Excel VBA Function with arguments

Even though this isn’t exactly the same as having Excel display a description of the VBA Function procedure, getting all the arguments of the function may help you understand what the function does. This is particularly true if both the function and the arguments have descriptive and meaningful names.

For example, if Excel displays “=squared(number)” as in the screenshot above, you’ll probably be able to figure out that the purpose of that particular VBA Function procedure is to square the number that is given as an argument.

If you’re not able to figure out what the function does using this method, you can always go to the Insert Function dialog where the description of the Excel VBA Function you’ve added always appears.

Now that we’re talking about function arguments, did you know that you can also add argument descriptions for your Excel VBA Function procedures?

Let’s take a look at how you can do this:

How To Add Descriptions For The Arguments Of An Excel VBA Function Procedure

When you use the Insert Function and Function Arguments dialogs to enter a built-in function, Excel displays a description for each of the arguments. For example, in the case of the SUM function, this looks as follows:

Function Arguments dialog with description

However, Excel doesn’t show (by default) descriptions of the arguments for an Excel VBA Function procedure. For example, the description for the arguments of the Squared function within the Function Arguments dialog looks (by default) as follows:

Excel VBA Function procedure without argument description

This is very similar to what happens with the description of the function itself, as described in the section above. And just as you can add a description for the whole Excel VBA Function procedure, you can add a description for its arguments.

The possibility of adding argument descriptions for Excel VBA Function procedures was only added in Excel 2010. If you use an earlier version of Excel, argument descriptions are not displayed.

You add descriptions for the arguments of an Excel VBA Function procedure using the Application.MacroOptions method. This method allows you to work with the Macro Options dialog.

Let’s see how you can use the Application.MacroOptions method to add a description for the arguments of a VBA Function procedure. The following macro (Argument_Descriptions) adds a description to the only argument of the Squared VBA Function.

Argument description code for VBA Function procedure

Once you’ve run this macro once and save the Excel workbook, the argument description is stored and associated with the relevant VBA Function procedure.

Let’s go once more to the Function Arguments dialog for the Squared VBA Function. The following screenshot shows how, now, the argument has a description (is the number to be squared).

Function argument description for Excel VBA Function

You can use macros that are similar to the Argument_Descriptions macro that appears above for purposes of adding argument descriptions to any Excel VBA Function procedure you create. The macro has only one statement containing the following 3 items:

Macro to add argument description to VBA Function

Item #1: Application.MacroOptions method.

This is simply the Application.MacroOptions method, which allows you to work on the Macro Options dialog box. In this particular case, the Application.MacroOptions method uses the 2 parameters that appear below (Macro and ArgumentDescriptions).

Item #2: Macro Parameter.

The Macro parameter of the Application.MacroOptions method is simply the name of the Excel VBA Function procedure you want to assign an argument description to.

In the example above, this is “Squared”.

Item #3: ArgumentDescriptions Parameter.

The ArgumentDescriptions parameter is an array where you include the descriptions of the arguments for the Excel VBA Function procedure that you’ve created. These are the descriptions that, once the macro has been executed, appear in the Function Arguments dialog.

You must always use the Array function when assigning argument descriptions. This applies even if, as in the case above, you’re assigning a description for a single argument.

In the case that appears above, there is only one argument description: “Number to be squared”. If you want or need to add more than one argument, use a comma to separate them.

How To Change The Category Of An Excel VBA Function Procedure

You’ve already seen that when you create an Excel VBA Function procedure, Excel lists it by default in the User Defined category. Check out, for example, the following screenshot of the Insert Function dialog. Notice how both the Squared and the Squared_Sign VBA Function procedures appear as User Defined functions.

Excel VBA Function procedures as User Defined functions

You may, however, want to have your VBA functions listed in a different category. That may make more sense, depending on the function that you’ve created and how are you planning to use it.

After all, the Excel Function Library has several different categories other than User Defined.

In the case of the Squared VBA Function procedure that appears in the screenshot above, it makes sense to list it under the Math & Trig category. To do this, you just need to run the following macro (named Function_Category) one time:

VBA code to assign a VBA Function to a category

Once you’ve executed this macro and saved the Excel workbook with the Squared VBA Function procedure, Squared is assigned permanently to the category 3, which is Math & Trig. You can see how this looks in the Insert Function dialog:

Excel VBA Function in Math & Trig category

Additionally, you can also see the Squared VBA Function procedure in the Math & Trig category in the Formulas tab of the Ribbon:

VBA Function procedure in Math & Trig category

You can apply similar macros for purposes of organizing any other Excel VBA Function procedures you may have created. You just need to adjust the VBA code that appears above accordingly. Let’s take a look at this code so you understand how it proceeds and how you should use it.

The Function_Category Sub procedure contains a single statement, with the following 3 main items:

Items in VBA code assigning function category to Function procedure

Item #1: Application.MacroOptions Method

You can use the Application.MacroOptions method, among others, for purposes of determining in which category an Excel VBA Function procedure is displayed. In the case above, the Application.MacroOptions method has only 2 parameters (Macro and Category).

Item #2: Macro Parameter

You’ve already seen the Macro parameter being used in the Application.MacroOptions method when assigning a description to a VBA Function procedure or its arguments. This parameter is simply the name of the VBA Function you want to assign a category to.

In the case above, this is Squared.

Item #3: Category Parameter

The Category parameter of the Application.MacroOptions method is an integer that determines the relevant function category. In other words, this parameter determines in which category the Excel VBA Function procedure appears.

In the example above, this is 3. However, as of the time of writing, Excel has the following 18 built-in categories.

  1. Financial.
  2. Date & Time.
  3. Math & Trig.
  4. Statistical.
  5. Lookup & Reference.
  6. Database.
  7. Text.
  8. Logical.
  9. Information.
  10. Commands.
  11. Customizing.
  12. Macro Control.
  13. DDE/External.
  14. User Defined.
  15. Engineering.
  16. Cube.
  17. Compatibility (introduced in Excel 2010).
  18. Web (introduced in Excel 2013).

In addition to the built-in categories listed above, you can create custom categories. Let’s take a look at one of the ways in which you can assign an Excel VBA Function procedure to a new custom category…

How To Create New Categories For Excel VBA Function Procedures

There are several methods to create custom categories for Excel VBA Function procedures. I may cover them in a future tutorial. If you want to be informed whenever I publish new blog posts or Excel tutorials, please make sure to register below:

In this particular section, I explain a simple way of defining a new category using the same Application.MacroOptions method described above.

When using this method, you simply replace the category parameter of the Application.MacroOptions method (3 in the example above) with a string containing the name of the new category. Let’s see how this looks in practice:

In the section above, you’ve assigned the Squared VBA Function to the Math & Trig category. However, the Squared_Sign function continues to be listed in the User Defined category.

Excel VBA Function procedure in User Defined Category

Let’s assume that you want to list this particular VBA Function procedure under a new category named “Useful Excel Functions”. The macro that appears below achieves this. Notice how the only things that change, when compared with the Function_Category macro used above, are the parameter values, namely the name of the macro and the function category.

Excel VBA Function assigned to custom category

Once you’ve executed this macro one time and saved the relevant Excel workbook, the Squared_Sign VBA Function is assigned permanently to the Useful Excel Functions list. The reason why this works is that, if you use a category name that has never been used, Excel simply defines a new category using that name.

The result of executing the macro above looks as follows in the Insert Function dialog:

Custom function category in Insert Function dialog

You may be wondering:

What happens if, when using the Application.MacroOptions method, you include a category name that is exactly the same as that of a built-in category?

For example, let’s go back to the Function_Category Sub procedure used to assign the Squared VBA Function to the Math & Trig category. Let’s change the integer representing the Math & Trig category (3) by the string “Math & Trig”, as shown in the image below:

Excel VBA Function procedure assigned to built-in category

As shown in the screenshot below, Excel simply lists the relevant VBA Function in the Math & Trig built-in category. No new categories are defined.

Excel VBA Function in built-in function list

In other words, both using (i) the integer 3 or (ii) the string “Math & Trig”, as category parameter when using the Applications.MacroOptions method yield the same result: the function is assigned to the Math & Trig list (category #3).

More generally, whenever you use a category name that matches a built-in category name (such as Financial, Logical, Text, or Date & Time), Excel simply lists the relevant VBA Function procedure in that built-in category.

Conclusion

By now, you probably have a very good grasp of Excel VBA Function procedures and are ready to start creating some custom functions. However, the knowledge you’ve gained from this Excel tutorial isn’t limited to this…

You’ve also seen how you can add descriptions and organize the VBA functions you create for purposes of making their use easier later, both for you and for the people you share your Excel workbooks with.

Finally, I hope that, if you’re not yet convinced of the usefulness of Excel VBA Function procedures, you’ve found the arguments in favor of using them compelling. Hopefully, you’ll give it a try soon.

Skip to content

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • Procedures in Excel VBA – What is a Sub Procedure?
    • Calling a Sub Procedure
    • Procedures and Access Levels
    • Examples on Sub Procedures – With and With Out Parameters
    • Example File

Page load link

Go to Top

Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic

Introduction

This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).

Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.

  • In 1996, there were over 30 million users of Microsoft Excel (source).
  • Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.

We’re one big happy family!

In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.

Prerequisites

You don’t need any prior programming experience to understand this tutorial. However, you will need:

  • Basic to intermediate familiarity with Microsoft Excel
  • If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
  • A willingness to try new things

Learning Objectives

Over the course of this article, you will learn:

  1. What VBA is
  2. Why you would use VBA
  3. How to get set up in Excel to write VBA
  4. How to solve some real-world problems with VBA

Important Concepts

Here are some important concepts that you should be familiar with to fully understand this tutorial.

Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.

If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!

Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:

  • Subroutines: a group of VBA statements that performs one or more actions
  • Functions: a group of VBA statements that performs one or more actions and returns one or more values

Note: you can have functions operating inside of subroutines. You’ll see later.

Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.

Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.

For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.

What is VBA?

Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.

Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.

But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.

Pizza in a pizza oven

Yum.

Why use VBA in Excel?

Because wood-fired pizza is the best!

But seriously.

A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?

Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.

You should consider using VBA if you need to:

  • Automate repetitive tasks
  • Create easy ways for users to interact with your spreadsheets
  • Manipulate large amounts of data

Getting Set Up to Write VBA in Excel

Developer Tab

To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.

VBA developer tab

To add the Developer tab to the ribbon:

  1. On the File tab, go to Options > Customize Ribbon.
  2. Under Customize the Ribbon and under Main Tabs, select the Developer check box.

After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.

VBA Editor

Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.

VBA editor

Excel VBA Examples

First, let’s create a file for us to play around in.

  1. Open a new Excel file
  2. Save it as a macro-enabled workbook (. xlsm)
  3. Select the Developer tab
  4. Open the VBA Editor

Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.

Example #1: Display a Message when Users Open the Excel Workbook

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub

Save, close the workbook, and reopen the workbook. This dialog should display.

Welcome to XYZ notebook message example

Ta da!

How is it doing that?

Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:

  • Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
  • Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
  • By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
  • msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”

In short, this is a simple subroutine that contains a function.

When could I use this?

Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.

  • Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
  • Solution: create a user message that contains a concise answer to each of these frequently answered questions.

Real World Examples

  • Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
  • Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
  • Use the InputBox function to get information from the user

Example #2: Allow User to Execute another Procedure

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub

Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub

Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.

Now click the button. This message should display:

Process the XYZ report message example

Click “yes” or hit Enter.

Thanks for processing the XYZ report message example

Once again, tada!

Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first…

How is it doing that?

This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:

  • Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
  • Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
  • UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
  • Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
  • If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.

When could I use this?

This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.

For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.

  • Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
  • Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.

Real World Examples

  • Create a dialog box for user to automatically populate certain information across multiple sheets
  • Use the InputBox function to get information from the user, which is then populated across multiple sheets

Example #3: Add Numbers to a Range with a For-Next Loop

For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub

Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.

This should happen:

For-Next loop results

Etc, until the 100th row.

How is it doing that?

  • Dim X As Integer: declares the variable X as a data type of Integer.
  • For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
  • Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
  • Next X: this tells the loop to run again

When could I use this?

The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.

Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.

You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.

Real World Examples

  • Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
  • Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
  • Loop through each character in a string and extract all numbers
  • Randomly select a number of values from an array

Conclusion

Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.

  • What is VBA?
  • How do I get set up to start using VBA in Excel?
  • Why and when would you use VBA?
  • What are some problems I could solve with VBA?

If you have a fair idea of how to you could answer these questions, then this was successful.

Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.

Happy coding!

Learning Resources

  • Excel VBA Programming for Dummies, John Walkenbach
  • Get Started with VBA, Microsoft Documentation
  • Learning VBA in Excel, Lynda

A bit about me

I’m Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I’m continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

In this Article

  • What are Sub Procedures?
  • Creating a Sub Procedure with the Macro Recorder
  • Creating a Sub Procedure in the VBE Window
  • Calling a Sub Procedure from Another Sub-Procedure
  • Adding an Argument to a Sub Procedure
  • Assigning a Button in Excel to a Sub Procedure
  • Creating a Function to Return a Value

This tutorial will explain VBA Sub Procedures in Excel.

What are Sub Procedures?

Sub procedure are one of the major cornerstones of VBA. A Sub procedure does things. They perform actions such as formatting a table or creating a pivot table.  The majority of procedures written are Sub procedures. All macros are Sub procedures. A sub procedure begins with a Sub statement and ends with an End Sub statement. The procedure name is always followed by parentheses.

Sub Gridlines ()
  ActiveWindow.DisplayGridlines = False
End Sub

A Sub Procedure in VBA can be created by the Macro Recorder or directly in the Visual Basic Editor (VBE).

Creating a Sub Procedure with the Macro Recorder

In the Ribbon, select View > Macros > Record Macro.

VBAProject ViewRibbon

OR

Developer > Visual Basic > Record Macro

Note: If you don’t see the Developer Ribbon, you’ll need to enable it.  You can learn how to do that here.

1) Type in the name for your macro, and then 2) Select where to store the macro. This can be in the Personal Macro workbook, the workbook you are currently editing or a new workbook entirely.VBAProject RecordMacro

Once you have clicked OK, you can follow the steps that you want in your macro (for example bolding a cell, changing the color of the text, etc.), and then click the stop button at the bottom of the screen to stop recording the macro.

VBAProject StopButton

To view your macro, in the Ribbon, select View > Macros > View Macros.

VBAProject ViewMacros

OR

Developer > Visual Basic >Macros

Click on the Macro in the Macro name list, and then click on Edit.

VBAProject Macros

This will  open the VBE and jump you into the VBA Code.

VBAProject ProjectView

A VBA Project has now automatically been created for your workbook, and within this project, a module (Module 1) has also been created.  The Sub Procedure (macro) is contained within this new module on the right hand side.

Creating a Sub Procedure in the VBE Window

To create a new procedure, we first need to insert a module into our VBA Project or make sure you are clicked in the module in which you wish to store the procedure. To insert a new module into your code, click on the Insert option on the menu bar, and click Module. VBA 18 PIC 01 Or, click on the Insert Module button which you will find on the standard ribbon. VBA 18 PIC 02 Once you have selected your module, the easiest way to create a procedure is by typing directly into the Module Window. If you type the word Sub followed by the name of the procedure, the End Sub will be automatically added to the code for you. VBASubProcedure TestAlternatively, you can go to Insert > Procedure instead: VBASubProcedure InsertProcedureThe following dialog box will appear: VBA 18 PIC 08

  1. Type the name of your new procedure in the name box – this must start with a letter of the alphabet and can contain letters and number and be a maximum of 64 characters.
  2. You can have a Sub procedure, a Function procedure or a Property procedure. (Properties are used in Class modules and set properties for ActiveX controls that you may have created). To create a Sub procedure, make sure that option is selected.
  3. You can make the scope of the procedure either Public or Private. If the procedure is public (default), then it can be used by all the modules in the project while if the procedure is private, it will only be able to be used by this module.
  4. You can declare local variables in this procedure as Statics (this is to do with the Scope of the variable and makes a local procedure level variable public to the entire module). We will not use this option.

When you have filled in all the relevant details, click on OK.

You then type your code between the Sub and End Sub statements.

Public Sub Test()
  ActiveWindow.DisplayGridlines = Not ActiveWindow.DisplayGridlines
End Sub

The code above will switch off the gridlines in the active window if they are on, but if they are off, it will switch them on!  

Calling a Sub Procedure from Another Sub-Procedure

Often we write code that can then be used repetitively throughout the VBA Project. We might have a macro that format a cell for example – perhaps makes the text bold and red, and then in a different macro, we also want to format the cell, as well as do some other stuff to the cell. In the second procedure, we can CALL the first procedure, and then continue with our additional code.

Firstly, we create the first procedure:

Sub FormatCell ()
 ActiveCell.Font.Bold = True
 ActiveCell.Font.Color = vbRed
End Sub

Then, in a second procedure, we can refer to the first procedure to run that procedure as well.

Sub AdditionalFormatCell()
 'call first procedure
FormatCell 'add additional formatting
ActiveCell.Font.Italic = True
ActiveCell.Interior.Color = vbGreen
End Sub

So while the first procedure will make a cell bold and the text red, the second one will in addition to the first one, add italic and make the background of the cell green.

Adding an Argument to a Sub Procedure

We can further control how our code works by adding an argument or arguments to our Sub-Procedure.

Consider the following:

VBASubProcedure Arguement

Our sub-procedure TestFormat, is calling the procedure AdditionalFormatCell. Although we have an argument for that procedure, we have marked it as Optional. An optional argument means that you do not have to pass the value to the procedure.

Due to the fact that we are not passing a value, the value of i will be zero – therefore the procedure FormatCell2 will be called instead of FormatCell. If we have passed a value to i – as long as that value was 1, then FormatCell would have been called instead.

Assigning a Button in Excel to a Sub Procedure

Once we have created a macro in Excel VBA, we can create a button on the worksheet to run the macro.  We need the Developer tab switched on to do this.

In the Ribbon, select Developer > Insert > Form Controls > Button.

VBA Buttons FormControl

Click and drag in the worksheet to create a button.  As soon as you release the mouse button, the assign macro dialog box will appear.  

VBASubProcedure InsertButton

Select the macro you wish to assign to the button, and click OK.

Right click on the button, and select Edit Text to change the text on the button.

VBA Buttons Edit Text

Click on the button to run the macro.

VBASubProcedure Button

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Creating a Function to Return a Value

A Function procedure differs from a Sub Procedure in that it will return a value. It can have multiple arguments, and the value it returns can be defined by a data type (eg: Text, Number, Date etc).

Function ConvertWeight(dblAmt As Double, WeightType As Integer) As Double
If WeightType = 1 Then
ConvertWeight = dblAmt / 2.2
Else
ConvertWeight = dblAmt * 2.2
End If
End Function

We can then create 2 Sub Procedures to use this function.  One to convert from pounds to kilos and the other from kilos to pounds.

VBASubProcedure Function

Содержание

  1. Урок 7 по VBA — Процедуры
  2. VBA процедуры типа Sub – подпрограммы
  3. VBA процедуры типа Function – функции
  4. VBA Sub Procedure
  5. What are Sub Procedures?
  6. Creating a Sub Procedure with the Macro Recorder
  7. Creating a Sub Procedure in the VBE Window
  8. Calling a Sub Procedure from Another Sub-Procedure
  9. Adding an Argument to a Sub Procedure
  10. Assigning a Button in Excel to a Sub Procedure
  11. VBA Coding Made Easy
  12. Creating a Function to Return a Value
  13. VBA Code Examples Add-in

Урок 7 по VBA — Процедуры

В отличии от языка VBScript, VBA процедуры классифицируются не на два типа (процедура-функция и процедура-подпрограмма), а четырех типов: процедура-функция, процедура-подпрограмма, процедура свойств и обработка событий. Также существуют некоторые дополнения в плане передачи параметров (по значению или по ссылке). Третьим моментом является область видимости – в VBA вызов процедуры может осуществляться как в пределах текущего модуля (макроса), так и за его пределами – во всех проектах. Все это обусловлено тем, что VBA – это не столько язык программирования, сколько программный пакет, с возможностью создания форм и проектов.

Давайте сначала кратко рассмотрим типы VBA процедур:

Подпрограммы – блоки кода заключенные в конструкцию Sub …. End Sub. Сама по себе подпрограмма не возвращает никакого значения, а просто выполняет прописанные в ней команды.

Функции – также блок кода, но прописанный в конструкцию Function … End Function. После выполнения функции возвращается определенное значение, доступ к которому можно получить через имя VBA функции.

Помимо этого, стоит упомянуть про обработку событий (нажатие кнопки клавиатуры или перемещение мыши) и доступ к объектам, но это отдельная тема.

VBA процедуры типа Sub – подпрограммы

После того как вы добавили в проект новый модуль, для объявления процедуры VBA нужно ее заключить в специальную конструкцию:

Sub ИмяПодпрограмм([аргументы])
Операторы
[Exit Sub]
операторы
End Sub

После ключевого слова Sub следует имя подпрограммы, в круглых скобках можно указывать или не указывать аргументы. Аргументы – это переменные (параметры), значение которых может обрабатываться, аргументы разделяются запятыми. Конструкция Exit Sub также не является обязательной, она говорит том, что нужно произвести выход из подпрограммы и продолжить выполнение кода, следующего после выражения End Sub.

Вызов VBA процедуры осуществляется с помощью ключевого слова call, например, Call MySub.

Давайте напишем простой пример: добавьте в проект новую форму и новый модуль. На поверхность формы добавьте два текстовых поля (TextBox), одну метку (Label) и одну кнопку (CommandButton). Создайте связь между формой и модулем, прописав в редакторе кода для модуля:

Sub SubModule() SubForm.ShowEnd Sub

Я назвал форму SubForm, а модуль – SubModule, за имя отвечает свойство Name.

Теперь в редакторе кода для формы пропишите:

‘************************************’ Вычисление гипотенузы’************************************’ процедура VBA принимает два параметраSub Hipotenuze(a, b)Dim c ‘ Проверка, если значения равны нулю If TextBox1.Text = 0 Or TextBox2.Text = 0 Then a = 1: b = 1 End If ‘ вычисление гипотенузы c = Sqr(a ^ 2 + b ^ 2) Label1.Caption = «Гипотенуза: » & cEnd Sub’ Обработка нажатия на кнопкуPrivate Sub CommandButton1_Click()Dim Ta, Tb Ta = TextBox1.Text Tb = TextBox2.Text ‘ vba вызов процедуры Hipotenuze Call Hipotenuze(Ta, Tb)End Sub’ Настройка свойств при запуске формыPrivate Sub UserForm_Initialize() Label1.Caption = «» Label1.FontSize = 15 Label1.ForeColor = vbBlue CommandButton1.Caption = «Найти» TextBox1.Text = 5 TextBox2.Text = 5End Sub

Тут все предельно просто, вначале мы объявили процедуру Hipotenuze, которой будут передаваться два аргумента, далее происходит проверка на нулевые значения. Вызов происходит при нажатии на кнопку, находящуюся на форме, параметрами будут значения, хранящиеся в текстовых полях TextBox1 и TextBox2. Результат отображается в метке Label1.

Вызов процедуры VBA может осуществляться и без использования ключевого слова Call, в таком случае, параметры не надо заключать в круглые скобки. Так же, при определении аргументов можно явно указать тип данных, например:

Sub MySub (a As Integer, b As String) … End Sub

Static – данное ключевое слово, прописанное перед ключевым словом Sub позволяет сохранять в памяти значения всех переменных после выполнения процедуры. Его мы рассматривали в с статье – переменные VBA.

ParamArray – данное ключевое слово позволяет передавать процедуре переменное количество параметров, оно может использоваться только для последнего элемента в списке аргументов.

ParamArray нельзя использовать вместе со словами ByRef, ByVal или Optional, например:

‘************************************’ Передача параметров’************************************’ процедура VBA принимает два параметраSub MyArguments(a As Integer, ParamArray b())Dim elem, s As String Label1.Caption = a For Each elem In b s = s & elem & » » Next Label2.Caption = sEnd Sub’ Обработка нажатия на кнопкуPrivate Sub CommandButton1_Click() MyArguments 1, 5, 6, 100, «строка»End Sub’ Настройка свойств при запуске формыPrivate Sub UserForm_Initialize() Label1.Caption = «» Label1.FontSize = 15 Label1.ForeColor = vbBlue Label2.Caption = «» Label2.FontSize = 15 Label2.ForeColor = vbRed CommandButton1.Caption = «Вывести»End Sub

Как видим, мы фактически с помощью ParamArray показываем, что передаем массив, для его обработки мы использовали оператор For …. Each. Тут мы передали при вызове VBA процедуры пять параметров, при этом, первый будет храниться в аргументе a, а остальные в аргументе b, который обрабатывается как массив.

Optional – позволяет указать, что аргумент не является обязательным и одновременно задать значение по умолчанию.

‘************************************’ Передача параметров’************************************Sub MyArguments(Optional a As Integer = 5, Optional b As String = » плюс «, Optional c As Integer = 10) Label1.Caption = a & b & cEnd SubPrivate Sub CommandButton1_Click() MyArgumentsEnd SubPrivate Sub CommandButton2_Click() MyArguments 100, » минус «, 50End SubPrivate Sub CommandButton3_Click() MyArguments 20, , 30End SubPrivate Sub UserForm_Initialize() Label1.Caption = «» Label1.FontSize = 15 Label1.ForeColor = vbBlue CommandButton1.Caption = «Вариант 1» CommandButton2.Caption = «Вариант 2» CommandButton3.Caption = «Вариант 3″End Sub

В данном примере на поверхности формы находится всего одна метка и три кнопки. Каждая из кнопок будет производить VBA вызов процедуры MyArguments с различными значениями.

Передача параметров по ссылке и по значению – по умолчанию, при вызове процедуры все параметры ей передаются по ссылке. Передача по ссылке – в простом варианте, это передача адреса по которому хранится значение. При передаче параметра по ссылке, передается не адрес, а копия значения.

Что бы все стало понятно, рассмотрим следующий пример:

‘************************************’ Передача параметров’************************************Sub MySub1()Dim MyVar MyVar = 100 Call MySumm1(MyVar) Label1.Caption = «Передача по ссылке » & MyVarEnd SubSub MySub2()Dim MyVar MyVar = 100 Call MySumm2(MyVar) Label2.Caption = «Передача по значению » & MyVarEnd SubSub MySumm1(ByRef a) a = a + 100End SubSub MySumm2(ByVal a) a = a + 100End SubPrivate Sub CommandButton1_Click() MySub1 MySub2End SubPrivate Sub UserForm_Initialize() Label1.Caption = «» Label1.FontSize = 15 Label1.ForeColor = vbBlue Label2.Caption = «» Label2.FontSize = 15 Label2.ForeColor = vbRed CommandButton1.Caption = «Проверить»End Sub

MySub1 – тут происходит объявление переменной MyVar и присвоение ей значения 100, далее в теле происходит вызов VBA процедуры MySumm1, ей в качестве параметры мы передаем значение переменной MyVar – 100. Сама процедура MySumm принимает значение по ссылке, на что указывает ключевое слово ByRef, к принятому значению прибавляется число 100. Стоит обратить внимание, что ByRef можно было и не писать. После VBA вызова процедуры MySumm1 происходит запись значения переменной MyVar в свойство Caption объекта Label1, в итоге, отобразится число 200.

MySub2 – аналог предыдущей процедуры, но тут происходит вызов MySumm2, в которой происходит передача параметров по значению, о чем говорит ключевое слово ByVal, в итоге, значение переменной MyVar не изменится.

VBA процедуры типа Function – функции

Пользовательским функциям языка VBA присущи практически те же правила, что и подпрограммам. Общая структура функции:

Function ИмяФункции ([аргументы]) [As ТипДанных]
Операторы
[Exit Function]
Операторы
[ИмяФункции=Выражение]
End Function

Видим, что тут при объявлении функции можно указать ее тип, данный тип будет содержать возвращаемое значение. Что бы функция возвращала значение, в конце нужно его присвоить переменной с именем функции, например:

Function Summ(a As Integer, b As Integer) As Integer Summ = a + bEnd FunctionPrivate Sub CommandButton1_Click() Label1.Caption = «Сумма 10 и 20: » & Summ(10, 20)End SubPrivate Sub UserForm_Initialize() Label1.Caption = «» Label1.FontSize = 15 Label1.ForeColor = vbBlue CommandButton1.Caption = «Сумма»End Sub

Источник

VBA Sub Procedure

In this Article

This tutorial will explain VBA Sub Procedures in Excel.

What are Sub Procedures?

Sub procedure are one of the major cornerstones of VBA. A Sub procedure does things. They perform actions such as formatting a table or creating a pivot table. The majority of procedures written are Sub procedures. All macros are Sub procedures. A sub procedure begins with a Sub statement and ends with an End Sub statement. The procedure name is always followed by parentheses.

A Sub Procedure in VBA can be created by the Macro Recorder or directly in the Visual Basic Editor (VBE).

Creating a Sub Procedure with the Macro Recorder

In the Ribbon, select View > Macros > Record Macro.

Developer > Visual Basic > Record Macro

Note: If you don’t see the Developer Ribbon, you’ll need to enable it. You can learn how to do that here.

1) Type in the name for your macro, and then 2) Select where to store the macro. This can be in the Personal Macro workbook, the workbook you are currently editing or a new workbook entirely.

Once you have clicked OK, you can follow the steps that you want in your macro (for example bolding a cell, changing the color of the text, etc.), and then click the stop button at the bottom of the screen to stop recording the macro.

To view your macro, in the Ribbon, select View > Macros > View Macros.

Developer > Visual Basic >Macros

Click on the Macro in the Macro name list, and then click on Edit.

This will open the VBE and jump you into the VBA Code.

A VBA Project has now automatically been created for your workbook, and within this project, a module (Module 1) has also been created. The Sub Procedure (macro) is contained within this new module on the right hand side.

Creating a Sub Procedure in the VBE Window

To create a new procedure, we first need to insert a module into our VBA Project or make sure you are clicked in the module in which you wish to store the procedure. To insert a new module into your code, click on the Insert option on the menu bar, and click Module. Or, click on the Insert Module button which you will find on the standard ribbon. Once you have selected your module, the easiest way to create a procedure is by typing directly into the Module Window. If you type the word Sub followed by the name of the procedure, the End Sub will be automatically added to the code for you. Alternatively, you can go to Insert > Procedure instead: The following dialog box will appear:

  1. Type the name of your new procedure in the name box – this must start with a letter of the alphabet and can contain letters and number and be a maximum of 64 characters.
  2. You can have a Sub procedure, a Function procedure or a Property procedure. (Properties are used in Class modules and set properties for ActiveX controls that you may have created). To create a Sub procedure, make sure that option is selected.
  3. You can make the scope of the procedure either Public or Private. If the procedure is public (default), then it can be used by all the modules in the project while if the procedure is private, it will only be able to be used by this module.
  4. You can declare local variables in this procedure as Statics (this is to do with the Scope of the variable and makes a local procedure level variable public to the entire module). We will not use this option.

When you have filled in all the relevant details, click on OK.

You then type your code between the Sub and End Sub statements.

The code above will switch off the gridlines in the active window if they are on, but if they are off, it will switch them on!

Calling a Sub Procedure from Another Sub-Procedure

Often we write code that can then be used repetitively throughout the VBA Project. We might have a macro that format a cell for example – perhaps makes the text bold and red, and then in a different macro, we also want to format the cell, as well as do some other stuff to the cell. In the second procedure, we can CALL the first procedure, and then continue with our additional code.

Firstly, we create the first procedure:

Then, in a second procedure, we can refer to the first procedure to run that procedure as well.

So while the first procedure will make a cell bold and the text red, the second one will in addition to the first one, add italic and make the background of the cell green.

Adding an Argument to a Sub Procedure

We can further control how our code works by adding an argument or arguments to our Sub-Procedure.

Consider the following:

Our sub-procedure TestFormat, is calling the procedure AdditionalFormatCell. Although we have an argument for that procedure, we have marked it as Optional. An optional argument means that you do not have to pass the value to the procedure.

Due to the fact that we are not passing a value, the value of i will be zero – therefore the procedure FormatCell2 will be called instead of FormatCell. If we have passed a value to i – as long as that value was 1, then FormatCell would have been called instead.

Assigning a Button in Excel to a Sub Procedure

Once we have created a macro in Excel VBA, we can create a button on the worksheet to run the macro. We need the Developer tab switched on to do this.

In the Ribbon, select Developer > Insert > Form Controls > Button.

Click and drag in the worksheet to create a button. As soon as you release the mouse button, the assign macro dialog box will appear.

Select the macro you wish to assign to the button, and click OK.

Right click on the button, and select Edit Text to change the text on the button.

Click on the button to run the macro.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Creating a Function to Return a Value

A Function procedure differs from a Sub Procedure in that it will return a value. It can have multiple arguments, and the value it returns can be defined by a data type (eg: Text, Number, Date etc).

We can then create 2 Sub Procedures to use this function. One to convert from pounds to kilos and the other from kilos to pounds.

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Понравилась статья? Поделить с друзьями:
  • What is present value in excel
  • What is precise word choice
  • What is ppmt in excel
  • What is powerpoint word used for
  • What is powerpivot for excel 2013