Vba
Top 22 VBA Interview Questions & Answers
Download PDF 1) Explain what is VBA or Visual Basic for Applications? VBA stands for Visual Basic...
A function is a piece of code that performs a specific task and returns a result. Functions are mostly used to carry out repetitive tasks such as formatting data for output, performing calculations, etc.
Suppose you are developing a program that calculates interest on a loan. You can create a function that accepts the loan amount and the payback period. The function can then use the loan amount and payback period to calculate the interest and return the value.
Why use functions
The advantages of using functions are the same as the ones in the above section on why use subroutines.
Rules of naming functions
The rules for naming functions as the same as the ones in the above section on rules for naming subroutines.
Private Function myFunction (ByVal arg1 As Integer, ByVal arg2 As Integer)
myFunction = arg1 + arg2
End Function
HERE in the syntax,
| Code | Action |
|---|---|
|
|
|
|
|
|
|
|
Function demonstrated with Example:
Functions are very similar to the subroutine. The major difference between a subroutine and a function is that the function returns a value when it is called. While a subroutine does not return a value, when it is called. Let's say you want to add two numbers. You can create a function that accepts two numbers and returns the sum of the numbers.
Step 1) User interface
Add a command button to the worksheet as shown below
Set the following properties of CommanButton1 to the following.
| S/N | Control | Property | Value |
|---|---|---|---|
| 1 | CommandButton1 | Name | btnAddNumbers |
| 2 | Caption | Add Numbers Function |
Your interface should now appear as follows
Step 2) Function code.
Private Function addNumbers(ByVal firstNumber As Integer, ByVal secondNumber As Integer)
addNumbers = firstNumber + secondNumber
End Function
HERE in the code,
| Code | Action |
|---|---|
|
|
|
|
|
|
Step 3) Write Code that calls the function
Private Sub btnAddNumbersFunction_Click()
MsgBox addNumbers(2, 3)
End SubHERE in the code,
| Code | Action |
|---|---|
| "MsgBox addNumbers(2,3)" |
|
Step 4) Run the program, you will get the following results
Download Excel containing above code
Summary:
Download PDF 1) Explain what is VBA or Visual Basic for Applications? VBA stands for Visual Basic...
What is a Subroutine in VBA? A Subroutine in VBA is a piece of code that performs a specific task...
VBA Comparison Operators These are operators that are used to compare values. Comparison operators...
What is VBA Array? An array is defined as a memory location capable of storing more than one...
Download PDF Following are frequently asked questions in interviews for freshers as well...
This Excel VBA tutorial for beginners covers in-depth lessons to learn VBA Excel and VBA basics....