Vba Excel 3
Vba Excel 3
Constant is a named memory location used to hold a value that CANNOT be changed during the
script execution. If a user tries to change a Constant value, the script execution ends up with an
error. Constants are declared the same way the variables are declared.
Syntax
In VBA, we need to assign a value to the declared Constants. An error is thrown, if we try to change
the value of the constant.
MsgBox "Integer is " & MyInteger & Chr(10) & "myDate is "
& myDate & Chr(10) & "myDay is " & myDay
End Sub
Output
Upon executing the script, the output will be displayed as shown in the following screenshot.
VBA - Operators
An Operator can be defined using a simple expression - 4 + 5 is equal to 9. Here, 4 and 5 are called
operands and + is called operator. VBA supports following types of operators −
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Concatenation Operators
Show Examples
% Modulus operator and the remainder after an integer division B % A will give 0
Show Examples
Checks if the value of the two operands are equal or not. If yes, then
= (A = B) is False.
the condition is true.
Checks if the value of the two operands are equal or not. If the values
<> (A <> B) is True.
are not equal, then the condition is true.
Checks if the value of the left operand is greater than the value of the
> (A > B) is False.
right operand. If yes, then the condition is true.
Checks if the value of the left operand is less than the value of the
< (A < B) is True.
right operand. If yes, then the condition is true.
Checks if the value of the left operand is greater than or equal to the
>= (A >= B) is False.
value of the right operand. If yes, then the condition is true.
Checks if the value of the left operand is less than or equal to the
<= (A <= B) is True.
value of the right operand. If yes, then the condition is true.
Show Examples
Show Examples
VBA - Decisions
Decision making allows the programmers to control the execution flow of a script or one of its
sections. The execution is governed by one or more conditional statements.
Following is the general form of a typical decision making structure found in most of the
programming languages.
VBA provides the following types of decision making statements. Click the following links to
check their details.
VBA - Loops
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Following
is the general form of a loop statement in VBA.
VBA provides the following types of loops to handle looping requirements. Click the following
links to check their detail.
for loop
1
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
for ..each loop
2
This is executed if there is at least one element in the group and reiterated for each element
in a group.
3 while..wend loop
This tests the condition before executing the loop body.
do..while loops
4
The do..While statements will be executed as long as the condition is True.(i.e.,) The Loop
should be repeated till the condition is False.
do..until loops
5
The do..Until statements will be executed as long as the condition is False.(i.e.,) The Loop
should be repeated till the condition is True.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all the remaining statements in the loop are NOT executed.
VBA supports the following control statements. Click the following links to check their detail.
VBA - Strings
Strings are a sequence of characters, which can consist of either alphabets, numbers, special
characters, or all of them. A variable is said to be a string if it is enclosed within double quotes " ".
Syntax
variablename = "string"
Examples
str1 = "string" ' Only Alphabets
str2 = "132.45" ' Only Numbers
str3 = "!@#$;*" ' Only Special Characters
Str4 = "Asc23@#" ' Has all the above
String Functions
There are predefined VBA String functions, which help the developers to work with the strings very
effectively. Following are String methods that are supported in VBA. Please click on each one of
the methods to know in detail.
1 InStr
Returns the first occurrence of the specified substring. Search happens from the left to the
right.
InstrRev
2
Returns the first occurrence of the specified substring. Search happens from the right to the
left.
Lcase
3
Returns the lower case of the specified string.
Ucase
4
Returns the upper case of the specified string.
Left
5
Returns a specific number of characters from the left side of the string.
Right
6
Returns a specific number of characters from the right side of the string.
Mid
7
Returns a specific number of characters from a string based on the specified parameters.
Ltrim
8
Returns a string after removing the spaces on the left side of the specified string.
Rtrim
9
Returns a string after removing the spaces on the right side of the specified string.
Trim
10
Returns a string value after removing both the leading and the trailing blank spaces.
Len
11
Returns the length of the given string.
Replace
12
Returns a string after replacing a string with another string.
Space
13
Fills a string with the specified number of spaces.
StrComp
14
Returns an integer value after comparing the two specified strings.
String
15
Returns a string with a specified character for specified number of times.
16 StrReverse
Returns a string after reversing the sequence of the characters of the given string.
Date Functions
Sr.No. Function & Description
Date
1
A Function, which returns the current system date.
CDate
2
A Function, which converts a given input to date.
DateAdd
3
A Function, which returns a date to which a specified time interval has been added.
DateDiff
4
A Function, which returns the difference between two time period.
DatePart
5
A Function, which returns a specified part of the given input date value.
DateSerial
6
A Function, which returns a valid date for the given year, month, and date.
FormatDateTime
7
A Function, which formats the date based on the supplied parameters.
IsDate
8
A Function, which returns a Boolean Value whether or not the supplied parameter is a date.
Day
9
A Function, which returns an integer between 1 and 31 that represents the day of the
specified date.
Month
10
A Function, which returns an integer between 1 and 12 that represents the month of the
specified date.
Year
11
A Function, which returns an integer that represents the year of the specified date.
12 MonthName
A Function, which returns the name of the particular month for the specified date.
WeekDay
13
A Function, which returns an integer(1 to 7) that represents the day of the week for the
specified day.
WeekDayName
14
A Function, which returns the weekday name for the specified day.
Time Functions
Sr.No. Function & Description
Now
1
A Function, which returns the current system date and time.
Hour
2
A Function, which returns an integer between 0 and 23 that represents the hour part of the
given time.
Minute
3
A Function, which returns an integer between 0 and 59 that represents the minutes part of
the given time.
Second
4
A Function, which returns an integer between 0 and 59 that represents the seconds part of
the given time.
Time
5
A Function, which returns the current system time.
Timer
6
A Function, which returns the number of seconds and milliseconds since 12:00 AM.
TimeSerial
7
A Function, which returns the time for the specific input of hour, minute and second.
TimeValue
8
A Function, which converts the input string to a time format.
VBA - Arrays
Array Declaration
Arrays are declared the same way a variable has been declared except that the declaration of an
array variable uses parenthesis. In the following example, the size of the array is mentioned in the
brackets.
'Method 1 : Using Dim
Dim arr1() 'Without Size
• Although, the array size is indicated as 5, it can hold 6 values as array index starts from
ZERO.
• Array Index cannot be negative.
• VBScript Arrays can store any type of variable in an array. Hence, an array can store an
integer, string, or characters in a single array variable.
The values are assigned to the array by specifying an array index value against each one of the
values to be assigned. It can be a string.
Example
When you execute the above function, it produces the following output.
Arrays are not just limited to a single dimension, however, they can have a maximum of 60
dimensions. Two-dimensional arrays are the most commonly used ones.
Example
In the following example, a multi-dimensional array is declared with 3 rows and 4 columns.
When you execute the above function, it produces the following output.
ReDim statement is used to declare dynamic-array variables and allocate or reallocate storage
space.
Syntax
ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
Parameter Description
• Preserve − An optional parameter used to preserve the data in an existing array when you
change the size of the last dimension.
• Varname − A required parameter, which denotes the name of the variable, which should
follow the standard variable naming conventions.
• Subscripts − A required parameter, which indicates the size of the array.
Example
In the following example, an array has been redefined and then the values preserved when the
existing size of the array is changed.
Note − Upon resizing an array smaller than it was originally, the data in the eliminated elements
will be lost.
When you execute the above function, it produces the following output.
XYZ
41.25
22
3
4
5
6
7
Array Methods
There are various inbuilt functions within VBScript which help the developers to handle arrays
effectively. All the methods that are used in conjunction with arrays are listed below. Please click
on the method name to know about it in detail.
LBound
1
A Function, which returns an integer that corresponds to the smallest subscript of the given
arrays.
UBound
2
A Function, which returns an integer that corresponds to the largest subscript of the given
arrays.
Split
3
A Function, which returns an array that contains a specified number of values. Split based
on a delimiter.
Join
4
A Function, which returns a string that contains a specified number of substrings in an array.
This is an exact opposite function of Split Method.
Filter
5
A Function, which returns a zero based array that contains a subset of a string array based on
a specific filter criteria.
6 IsArray
A Function, which returns a boolean value that indicates whether or not the input variable is
an array.
Erase
7
A Function, which recovers the allocated memory for the array variables.
Apart from inbuilt functions, VBA allows to write user-defined functions as well. In this chapter,
you will learn how to write your own functions in VBA.
Function Definition
A VBA function can have an optional return statement. This is required if you want to return a
value from a function.
For example, you can pass two numbers in a function and then you can expect from the function to
return their multiplication in your calling program.
Note − A function can return multiple values separated by a comma as an array assigned to the
function name itself.
Before we use a function, we need to define that particular function. The most common way to
define a function in VBA is by using the Function keyword, followed by a unique function name
and it may or may not carry a list of parameters and a statement with End Function keyword,
which indicates the end of the function. Following is the basic syntax.
Syntax
Function Functionname(parameter-list)
statement 1
statement 2
statement 3
.......
statement n
End Function
Example
Add the following function which returns the area. Note that a value/values can be returned with the
function name itself.
To invoke a function, call the function using the function name as shown in the following
screenshot.
The output of the area as shown below will be displayed to the user.
• Sub procedures DO NOT Return a value while functions may or may not return a value.
• Sub procedures CAN be called without a call keyword.
• Sub procedures are always enclosed within Sub and End Sub statements.
Example
Sub Area(x As Double, y As Double)
MsgBox x * y
End Sub
Calling Procedures
To invoke a Procedure somewhere in the script, you can make a call from a function. We will not
be able to use the same way as that of a function as sub procedure WILL NOT return a value.
Now you will be able to call the function only but not the sub procedure as shown in the following
screenshot.
The result cell displays ZERO as the area value is NOT returned from the function. In short, you
cannot make a direct call to a sub procedure from the excel worksheet.
VBA - Events
VBA, an event-driven programming can be triggered when you change a cell or range of cell values
manually. Change event may make things easier, but you can very quickly end a page full of
formatting. There are two kinds of events.
• Worksheet Events
• Workbook Events
Worksheet Events
Worksheet Events are triggered when there is a change in the worksheet. It is created by performing
a right-click on the sheet tab and choosing 'view code', and later pasting the code.
The user can select each one of those worksheets and choose "WorkSheet" from the drop down to
get the list of all supported Worksheet events.
Following are the supported worksheet events that can be added by the user.
Upon double-clicking on any cell, the message box is displayed to the user as shown in the
following screenshot.
Workbook Events
Workbook events are triggered when there is a change in the workbook on the whole. We can add
the code for workbook events by selecting the 'ThisWorkbook' and selecting 'workbook' from the
dropdown as shown in the following screenshot. Immediately Workbook_open sub procedure is
displayed to the user as seen in the following screenshot.
Following are the supported Workbook events that can be added by the user.
Let us say, we just need to display a message to the user that a new sheet is created successfully,
whenever a new sheet is created.
Upon creating a new excel sheet, a message is displayed to the user as shown in the following
screenshot.
Syntax errors, also called as parsing errors, occur at the interpretation time for VBScript. For
example, the following line causes a syntax error because it is missing a closing parenthesis.
Function ErrorHanlding_Demo()
dim x,y
x = "Tutorialspoint"
y = Ucase(x
End Function
Runtime errors
Runtime errors, also called exceptions, occur during execution, after interpretation.
For example, the following line causes a runtime error because here the syntax is correct but at
runtime it is trying to call fnmultiply, which is a non-existing function.
Function ErrorHanlding_Demo1()
Dim x,y
x = 10
y = 20
z = fnadd(x,y)
a = fnmultiply(x,y)
End Function
Function fnadd(x,y)
fnadd = x + y
End Function
Logical Errors
Logical errors can be the most difficult type of errors to track down. These errors are not the result
of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives
your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of logic
you want to put in your program.
For example, dividing a number by zero or a script that is written which enters into infinite loop.
Err Object
Assume if we have a runtime error, then the execution stops by displaying the error message. As a
developer, if we want to capture the error, then Error Object is used.
Example
In the following example, Err.Number gives the error number and Err.Description gives the error
description.
VBA enables an error-handling routine and can also be used to disable an error-handling routine.
Without an On Error statement, any run-time error that occurs is fatal: an error message is
displayed, and the execution stops abruptly.
GoTo line
1 Enables the error-handling routine that starts at the line specified in the required line
argument. The specified line must be in the same procedure as the On Error statement, or a
compile-time error will occur.
GoTo 0
2
Disables the enabled error handler in the current procedure and resets it to Nothing.
GoTo -1
3
Disables the enabled exception in the current procedure and resets it to Nothing.
Resume Next
4 Specifies that when a run-time error occurs, the control goes to the statement immediately
following the statement where the error occurred, and the execution continues from that
point.
Example
Public Sub OnErrorDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x, y, z As Integer
x = 50
y = 0
z = x / y ' Divide by ZERO Error Raises