0% found this document useful (0 votes)
17 views

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.

Uploaded by

ae.wongkene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

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.

Uploaded by

ae.wongkene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

VBA - Constants

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.

Following are the rules for naming a constant.

• You must use a letter as the first character.


• You can't use a space, period (.), exclamation mark (!), or the characters @, &, $, # in the
name.
• Name can't exceed 255 characters in length.
• You cannot use Visual Basic reserved keywords as variable name.

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.

Const <<constant_name>> As <<constant_type>> = <<constant_value>>


Example

Let us create a button "Constant_demo" to demonstrate how to work with constants.

Private Sub Constant_demo_Click()


Const MyInteger As Integer = 42
Const myDate As Date = #2/2/2020#
Const myDay As String = "Sunday"

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

The Arithmatic Operators

Following arithmetic operators are supported by VBA.

Assume variable A holds 5 and variable B holds 10, then −

Show Examples

Operator Description Example

+ Adds the two operands A + B will give 15

- Subtracts the second operand from the first A - B will give -5

* Multiplies both the operands A * B will give 50

/ Divides the numerator by the denominator B / A will give 2

% Modulus operator and the remainder after an integer division B % A will give 0

^ Exponentiation operator B ^ A will give 100000

The Comparison Operators

There are following comparison operators supported by VBA.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

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.

The Logical Operators

Following logical operators are supported by VBA.

Assume variable A holds 10 and variable B holds 0, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the conditions are True,


AND a<>0 AND b<>0 is False.
then the Expression is true.

Called Logical OR Operator. If any of the two conditions are


OR a<>0 OR b<>0 is true.
True, then the condition is true.

Called Logical NOT Operator. Used to reverse the logical state of


NOT its operand. If a condition is true, then Logical NOT operator will NOT(a<>0 OR b<>0) is false.
make false.

Called Logical Exclusion. It is the combination of NOT and OR


XOR Operator. If one, and only one, of the expressions evaluates to (a<>0 XOR b<>0) is true.
be True, the result is True.

The Concatenation Operators

Following Concatenation operators are supported by VBA.

Assume variable A holds 5 and variable B holds 10 then −

Show Examples

Operator Description Example

+ Adds two Values as Variable. Values are Numeric A + B will give 15

& Concatenates two Values A & B will give 510

Assume variable A = "Microsoft" and variable B = "VBScript", then −

Operator Description Example

+ Concatenates two Values A + B will give MicrosoftVBScript

& Concatenates two Values A & B will give MicrosoftVBScript


Note − Concatenation Operators can be used for both numbers and strings. The output depends on
the context, if the variables hold numeric value or string value.

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.

Sr.No. Statement & Description


if statement
1
An if statement consists of a Boolean expression followed by one or more statements.
if..else statement

2 An if else statement consists of a Boolean expression followed by one or more statements.


If the condition is True, the statements under If statements are executed. If the condition is
false, the Else part of the script is executed.
if...elseif..else statement

3 An if statement followed by one or more ElseIf statements, that consists of Boolean


expressions and then followed by an optional else statement, which executes when all the
condition become false.
nested if statements
4
An if or elseif statement inside another if or elseif statement(s).
switch statement
5
A switch statement allows a variable to be tested for equality against a list of values.

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.

Sr.No. Loop Type & Description

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.

S.No. Control Statement & Description

Exit For statement


1
Terminates the For loop statement and transfers the execution to the statement immediately
following the loop
Exit Do statement
2
Terminates the Do While statement and transfers the execution to the statement immediately
following the loop

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.

Sr.No. Function Name & Description

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.

VBA - Date-Time Function


VBScript Date and Time Functions help the developers to convert date and time from one format to
another or to express the date or time value in the format that suits a specific condition.

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

'Method 2 : Mentioning the Size


Dim arr2(5) 'Declared with size of 5

'Method 3 : using 'Array' Parameter


Dim arr3
arr3 = Array("apple","Orange","Grapes")

• 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.

Assigning Values to an Array

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

Add a button and add the following function.

Private Sub Constant_demo_Click()


Dim arr(5)
arr(0) = "1" 'Number as String
arr(1) = "VBScript" 'String
arr(2) = 100 'Number
arr(3) = 2.45 'Decimal Number
arr(4) = #10/07/2013# 'Date
arr(5) = #12.45 PM# 'Time

msgbox("Value stored in Array index 0 : " & arr(0))


msgbox("Value stored in Array index 1 : " & arr(1))
msgbox("Value stored in Array index 2 : " & arr(2))
msgbox("Value stored in Array index 3 : " & arr(3))
msgbox("Value stored in Array index 4 : " & arr(4))
msgbox("Value stored in Array index 5 : " & arr(5))
End Sub

When you execute the above function, it produces the following output.

Value stored in Array index 0 : 1


Value stored in Array index 1 : VBScript
Value stored in Array index 2 : 100
Value stored in Array index 3 : 2.45
Value stored in Array index 4 : 7/10/2013
Value stored in Array index 5 : 12:45:00 PM
Multi-Dimensional Arrays

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.

Private Sub Constant_demo_Click()


Dim arr(2,3) as Variant ' Which has 3 rows and 4 columns
arr(0,0) = "Apple"
arr(0,1) = "Orange"
arr(0,2) = "Grapes"
arr(0,3) = "pineapple"
arr(1,0) = "cucumber"
arr(1,1) = "beans"
arr(1,2) = "carrot"
arr(1,3) = "tomato"
arr(2,0) = "potato"
arr(2,1) = "sandwitch"
arr(2,2) = "coffee"
arr(2,3) = "nuts"

msgbox("Value in Array index 0,1 : " & arr(0,1))


msgbox("Value in Array index 2,2 : " & arr(2,2))
End Sub

When you execute the above function, it produces the following output.

Value stored in Array index : 0 , 1 : Orange


Value stored in Array index : 2 , 2 : coffee
ReDim Statement

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.

Private Sub Constant_demo_Click()


Dim a() as variant
i = 0
redim a(5)
a(0) = "XYZ"
a(1) = 41.25
a(2) = 22

REDIM PRESERVE a(7)


For i = 3 to 7
a(i) = i
Next

'to Fetch the output


For i = 0 to ubound(a)
Msgbox a(i)
Next
End Sub

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.

Sr.No. Function & Description

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.

VBA - User Defined Functions


A function is a group of reusable code which can be called anywhere in your program. This
eliminates the need of writing the same code over and over again. This enables the programmers to
divide a big program into a number of small and manageable functions.

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

Add a button and add the following function.

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.

Function findArea(Length As Double, Optional Width As Variant)


If IsMissing(Width) Then
findArea = Length * Length
Else
findArea = Length * Width
End If
End Function
Calling a Function

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.

VBA - Sub Procedure


Sub Procedures are similar to functions, however there are a few differences.

• 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.

Function findArea(Length As Double, Width As Variant)


area Length, Width ' To Calculate Area 'area' sub proc is called
End Function

Now you will be able to call the function only but not the sub procedure as shown in the following
screenshot.

The area is calculated and shown only in the Message box.

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.

Private Sub Worksheet_Activate()


Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As
Boolean)
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Private Sub Worksheet_Calculate()
Private Sub Worksheet_Change(ByVal Target As Range)
Private Sub Worksheet_Deactivate()
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Example

Let us say, we just need to display a message before double click.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As


Boolean)
MsgBox "Before Double Click"
End Sub
Output

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.

Private Sub Workbook_AddinUninstall()


Private Sub Workbook_BeforeClose(Cancel As Boolean)
Private Sub Workbook_BeforePrint(Cancel As Boolean)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Private Sub Workbook_Deactivate()
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Private Sub Workbook_Open()
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As
Range, Cancel As Boolean)
Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As
Range, Cancel As Boolean)
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As
Hyperlink)
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As
Range)
Private Sub Workbook_WindowActivate(ByVal Wn As Window)
Private Sub Workbook_WindowDeactivate(ByVal Wn As Window)
Private Sub Workbook_WindowResize(ByVal Wn As Window)
Example

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.

Private Sub Workbook_NewSheet(ByVal Sh As Object)


MsgBox "New Sheet Created Successfully"
End Sub
Output

Upon creating a new excel sheet, a message is displayed to the user as shown in the following
screenshot.

VBA - Error Handling


There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c)
Logical Errors.
Syntax errors

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.

Err.Raise 6 ' Raise an overflow error.


MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
Err.Clear ' Clear the error.
Error Handling

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.

On Error { GoTo [ line | 0 | -1 ] | Resume Next }


Sr.No. Keyword & Description

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

ErrorHandler: ' Error-handling routine.


Select Case Err.Number ' Evaluate error number.
Case 10 ' Divide by zero error
MsgBox ("You attempted to divide by zero!")
Case Else
MsgBox "UNKNOWN ERROR - Error# " & Err.Number & " : " &
Err.Description
End Select
Resume Next
End Sub

You might also like