Introduction
Data has become one of the essential things for an individual in today's modern world. You must have filled out your information on the application or website.
However, if a person wishes to learn how to handle data in the form of tables, they may do so using Excel. Excel is a powerful tool or software that we have at our ease. It may be used to create tables, computations, sheets, etc.
Functions and Subs are essential tools used to perform multiple tasks. Today we will discuss them in brief.
So, without wasting any more time, let's get to the point of our discussion. First, we'll look at Excel's functions and how they work.
What is a Function?
A function is a predefined formula already implemented in Excel, or you may define your function.
Functions carry out different calculations in a specific order based on the values specified as arguments or parameters.
If you expect a result from the Excel VBA, you can use a function. Place a function into the code (Click Insert, Module) in the Visual Basic Editor. For example, the function with the name prod(Product).
Function Prod(x As Double, y As Double) As Double
Prod = x * y
End Function
Let's understand how this works. This method takes two parameters (of type Double). It returns a value of type Double (the part after As also of type Double). You can use the function name (Prod) in your code to specify which result you wish to return (here x * y).
You can now make a call to this function from any stage in your code by simply using the name or Alias of the function and giving a value for each argument.
Press the command button on your worksheet and add the following line of code:
dim multiply As Double //Declaration of variable(using Dim)
multiply = Prod(2, 6) + 11
MsgBox multiply // Display the result(Using MsgBox)
The function returns a value which is the product of 2,6, and after that, 11 is added, giving a value which is 23, so you have to 'catch' this value in your code. You can declare another variable (multiply) for this. Next, you perform the addition of another value to this variable (not necessary). Finally, display the value using a MsgBox.
When you press the command button on the sheet, the following is displayed:
If you want to perform a task that returns a result (such as the sum of a group of numbers), you would typically use a Function procedure.
I hope you understand how we deal with functions; now, coming to the second part of our discussion, Sub. Let's get straight into it.