Open In App

Function and Sub in Excel VBA

Last Updated: 30 Oct, 2022

R

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In Visual Basic, the functions and sub-procedures play similar roles but have different or unique characteristics. However, both perform a programmed task. They utilize a set or group of commands to deliver the required results. The key difference between the sub and the functions is that a sub-procedure generally does not return a result whereas functions tend to return a result. Hence if there is a need for having a value post execution of tasks, then place the VBA code under a function or otherwise place the code under a sub-procedure. In Excel, there is the availability of large numbers of VBA functions that could be utilized in the development of new VBA codes. Such functions are referred to as Built-in functions. With the increase in the size of a VBA program, both Functions and Sub-procedures play a crucial role in the management and performance of VBA code.

Functions in VBA

A function in VBA can be defined as a procedure that executes a piece of code or instructions and post-execution, it returns the value of the tasks performed. A function is hence invoked using a variable. Functions are directly called in the spreadsheets by using excel based formulas. An excel VBA function is not of executable nature. They help in performing a set of repetitive tasks. Following is the syntax for the VBA function: –

Function <Function name>  (Parameters) as variable type

Piece of codes

End function.

Here is a small example of the VBA function: 

Function CalcArea(a As Double, b As Double) As Double

CalcArea = a * b

End Function

In an excel spreadsheet, place the formula in range A1 as shown below:

Calcarea-formula-added

 

The following would be the output in range A1 of the excel spreadsheet as shown below: 

Output-in-cell-A1-obtained

 

The above code is a very simple example of how to program or develop custom functions. A VBA programmer can develop as many custom functions’ basis the need of the program. He can insert a new module and start developing a new function just by naming it by a new unique function name.

Sub in VBA

A sub-procedure in VBA can be defined as a procedure that executes a piece of code or instructions, but post-execution does not return the value of the tasks performed. A sub-procedure, therefore, does not require a variable for getting invoked. An excel VBA sub-routine or a sub-procedure is of executable nature and can be assigned as a macro to any excel based object. Like functions, they help in performing a set of repetitive tasks. Following is the syntax for the VBA sub-procedure: 

Sub  <sub name>  (Parameters) 

Piece of codes

End sub

Here is a small example of a VBA sub-routine: 

sub CalcArea() 

Dim a As Double, b As Double

c = a * b

Sheet3.activate

Sheet3.range(“A1”).value=c

End sub

In an excel module, select run sub/user form present under the Run option:

Selecting-sub/user-form

 

The following would be the output in range A1 of the excel spread sheet as shown below:

Output-in-cell-A1-obtained

 

The above code is like functions but the only difference is that in this program, the values are hard coded in the sub-procedure itself whereas, in functions, the values are to be passed by the end user. The following things should be followed when creating a sub-routine: 

  • It should not have any spaces.
  • It should not begin with any number or special character. It can however begin with an underscore or a simple letter.
  • The name of the sub-procedure should not be the same as that of the reserved keywords present in the excel VBA.

To Summarize, the following are the differences between a function and a sub in VBA: 

Function In VBA

Sub In VBA

Functions always return a value after it completes their required set of instructions. Sub does not return a value after it completes its required set of instructions.
Functions do not have any alternate nomenclature in VBA In VBA, Subs are referred to as subprocedures as well as subroutines
To Execute Function, it is to be passed on to the excel sheet beginning with equal to sign. In Short, they are invoked as excel based formulas. To execute a sub in VBA, it can be run or could be executed through Project explorer or by assigning it as a macro on excel objects.


R

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

Sub Procedure in Excel VBA

article_img
A Sub Procedure is an action that is written in VBA code. It starts with a Sub statement and ends with an End Sub statement. It is used to manipulate the data in an Excel sheet which includes a table present in an Excel sheet or a pivot table present in the Excel sheet. The name of the procedure should be followed by parentheses. Let's learn why to use sub procedure: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesIn a program, we have to access the database frequently. In this case, instead of writing the code again and again we can simply create a function to access the database. Reusability of code can be done.Naming Rules of Sub ProcedureIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subprocedure cannot be a keyword like Private, Sub, End, etc. Syntax Sub name_procedure () End Sub Let's discuss different ways to create Sub Procedure: Creating a Sub Procedure with Macro Step 1: Select View in the Ribbon then click on Macros to select Record Macro Step 2: Change the Macro name accord
Read More

How to Debug a User Defined Function in Excel VBA

article_img
Debugging a User Defined Function (UDF) in Excel VBA can feel like a detective mission where you search for clues to fix issues in your code. When a custom function doesn’t deliver the expected results, it can disrupt your workflow and lead to frustration. Fortunately, debugging tools in VBA make it possible to identify exactly what's going wrong and why. In this article you will learn the effective techniques to debug your UDFs, helping you find errors, understand how your code runs, and ensure your functions work seamlessly. Whether you're a beginner or an experienced user, mastering these debugging skills can save you time and turn coding headaches into problem-solving victories.Table of ContentWhat is a User Defined Function in Excel What is Debugging in Excel VBA How to Create a User-Defined Function in Excel VBAHow to Debug a User-Defined Function in Excel VBACommon Debugging Tools in Excel VBAUDF works in debug mode but it doesn't give value into the cell: 9 Best ways to ResolveHow to Debug a Custom Function in ExcelWhat is a User Defined Function in Excel A User Defined Function (UDF) in Excel VBA is a custom function created by users to perform specific tasks or calculatio
Read More

How to Create a User Defined Function in Excel VBA

article_img
A function is a collection of code.  As a developer, we very often need a custom function (User-defined function) in our projects. These functions can be used as normal functions in Excel. These are helpful when the existing functions are not enough. In such cases, the user can create his own custom user-defined function to fulfil the need.  What are User Defined FunctionsUser Defined Function(UDF) is the custom function that is created by the user to perform a specific task in VBA(Virtual basic application) which is a programming language in Excel. Function Vs. Subroutine in VBA In VBA, a 'Subroutine' lets you run a group of commands, while a 'Function' provides a result. For example, consider a list of numbers, some positive and some negative. With a subroutine, you can scan each cell and mark negative ones by changing their colour. The subroutine modifies the cell properties. On the other hand, a custom function can be used in a separate column. It returns TRUE for negative values and FALSE for positive ones. Functions can't change cell properties directly but can be used with conditional formatting for the same effect. When you create a User Defined Function (UDF) in VBA, you c
Read More

InputBox Function in Excel VBA

article_img
Input Box is one of the most frequently used functions in VBA Macro. The dialogue box that appears asks for input from the user and returns a constant/code/number/text. For example, if you want to create a log-in form in VBA, you will require an input box function. Let's learn how to create an input box in VBA. InputBox FunctionInput Box is a dialogue box that helps users to take value, and do later computations according to the entered value. The input box is similar to the message box, but the message box is used to display the data while the input box is used to enter the data. By default, a message box shows only the OK button in its dialogue box but the input box shows both the OK and Cancel buttons in its dialogue box. You can choose the return type of the data to be entered. The automated data analysis includes entering and displaying the data, which can be achieved if we are using the input box and message box simultaneously. Syntax: InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile, context]) Temporary and Permanent Arguments in Input BoxArguments of the Input box, help customize your input box by changing the title, fixing the position, adding help buttons, etc
Read More

VBA Find Function in Excel

article_img
In an Excel sheet subset of cells represents the VBA Range which can be single cells or multiple cells. The find function will help to modify our search within its Range object. A specific value in the given range of cells is to search with the help of the Find function. Excel VBA provides different parameters in the Find function so that we can search according to the search order or direction and also we can make a case-sensitive search which will be discussed further in this article. Excel VBA Find FunctionAs we know about the Find Function in Excel, we can use the Shortcut key "Ctrl+F" to find the content that you are looking for. The FIND function of VBA searches for a specified value in the range that is defined by the user. A VBA code is written by entering arguments of the FIND function. Below is the syntax given for using the find function in VBA, Syntax: Find(What, [After], [LookIn], [LookAt], [SearchOrder], [SearchDirection AsXlSearchDirection = xlNext], [MatchCase], [MatchByte], [SearchFormat]) As Range Parameter Required Description WhatRequiredThe value for which we are searchingAfterOptionalRange of cells from where the search will startLookinOptionalFunction search
Read More

Variables and Data Types in VBA Excel

article_img
In a computer system, variables and data types are almost used in every program to store and represent data. Similarly, Excel VBA also has variables and data types to store and represent data and its type. In this article, we will learn about VBA variables, their scope, data types, and much more. VBA Variables VBA(Visual Basic for Application) variables are similar to other programming languages variables, they act as a container that is used to store data(integer, string, floats, etc). We can use the variables in the code at multiple places and executer the programs. Defining Variables In VBA VBA gives permission to define variables in two ways: Implicitly - In VBA, we can implicitly declare variables using the assignment(=) operator. All the variables that are implicitly declared in VBA are of type "Variant". The variant type variables required more memory space than usual variables. Example: label="gfg"Explicitly - Explicitly we can declare variables using "Dim" keyword. Explicit variable also reduces the naming conflicts and spelling mistakes. Example: Num as password Syntax For VBA Variables // macro definition Sub VBA_Variable_Example () Dim <name> End Sub VBA V
Read More

VBA Date and Time Functions in Excel

article_img
Date and Time Functions are the inbuilt functions that give us the opportunity to see the date or time according to the user's need. Suppose a user needs to see the month or the day or the year then it can be easily seen by different date functions. Similarly, for the time function, also we can manipulate it according to the need of the user. Date and Time functions are used to interconvert date and time in different formats. In this article, we will learn about the most commonly used date and time functions. VBA Date Functions There are fifteen-plus different date functions in VBA, but here we will talk about some of the most commonly used date functions. VBA Date Function The Date() function returns the current date. The Date() function does not require any arguments. For example, declare a variable name date_1 of Date data type, call the Date() function, and store the return value in date_1, then print the date_1 in the console. Syntax of the function: Date() VBA DateAdd Function The DateAdd() function is used to add an interval of date/time to the respective date or time. The function will return the resulting date or time. The function takes three arguments, Interval, Nu
Read More

How to Declare and Initialize String Array in Excel VBA?

article_img
A string array is an array where we can store only string values in the array, with the help of a string array, we can store more than one string value. We can declare the string array in many ways like declaring a static string array, declaring a variant size array of string using the Array function, and a string array using the split function which we will discuss in this article Declaring a Static String Array A static Array is an array whose size is fixed and it can be declared in two ways one is declared implicitly and another one is explicit. The following code is to declare a string array implicitly. The following code is to declare a string array explicitly. Declaring a Variant Size Array of String using Array Function In the following code an array is declared with variant size and string values are initialized using the array function: If we want to access the strings in the array then we have to write, Declaring a String Array using Split Function The following code is to declare an array without any fixed size and a split function is used to assign the string values. If we want to access the strings in the array then we have to write, By default, the lower bound
Read More

How to Insert and Run VBA Code in Excel?

article_img
In Excel VBA stands for (Visual Basic for Application Code) where we can automate our task with help of codes and codes that will manipulate(like inserting, creating, or deleting a row, column, or graph) the data in a worksheet or workbook. With the help of VBA, we can also automate the task in excel to perform all these tasks we need to insert and run the VBA code properly which we will discuss in this article. Steps to Insert and Run VBA Code in Excel To use the VBA code properly in Excel we need to change the default macro security settings of excel for that we need to follow further steps Step 1: Click on the "File" menu at the left top of the excel tab. Step 2: Select "Options" to get the "Excel Options" window. Step 3: Select "Customized Ribbon" in the "Excel Options" Window and then select the "Developer" check box in the "Main Tabs". Step 4: Then return to the main Excel window to select the "Developer" ribbon and then click on "Macro Security" in the "Code" group. Step 5: Click on "Macro Settings" to select "Disable all macros except digitally signed macros". Now, to insert and run the VBA in Excel so that we can write codes we need to follow further steps: Ste
Read More
three90RightbarBannerImg