Chapter 1: Introduction To VBA: Common Uses of VBA
Chapter 1: Introduction To VBA: Common Uses of VBA
Project window
Properties
window
Immediat
e window
Chapter 2: Data types in VBA
Variables: Variables are entities that hold data. In VBA, variables are areas
allocated by the computer memory to hold data.
The following are the variables naming rules in VBA:
1) A variable name must start with a letter and not a number. Numbers
can be included within the name, but not as the first character.
2) A variable name can be no longer than 250 characters.
3) A variable name cannot be the same as keywords.
4) No blank space allowed. You can separate words by using the
underscore( _ ) for eg. Roll_no
Declaring variable:
To declare a variable we use the word “Dim” (short for dimension) followed
by our chosen variable name then the word “as” followed by the variable
type. For ex. Dim n As integer.
You may also combine more variables to be declared in one line, separating
each variable with a comma, as follows: Dim first_name As String,
joining_date As Date, pay As Integer
Keywords: Keywords in Excel VBA are words that Excel has set aside to
use in the execution of code. This means we cannot use them for any other
purpose. For example: select, active, sub, end, function etc. are all keywords.
Some of the reserved keywords as shown in table 1.
Example:
Sub result( )
MsgBox ("Congradulations")
End Sub
This displays the message box as shown in fig.
Constant Description
vbOKOnly It displays a single OK button
vbOKCancel It displays two buttons OK and Cancel
vbYesNoCancel It displays three buttons Yes, No and Cancel.
vbYesNo It displays two buttons Yes and No.
vbQuestion It displays a query icon.
vbExclamation It displays a warning message icon.
vbDefaultButton1 First button is treated as default.
vbDefaultButton2 Second button is treated as default.
vbDefaultButton3 Third button is treated as default.
vbMsgBoxHelpButton This adds a Help button to the message box.
VBA msgbox function returns a value based on the user input. These values
can be anyone of the ones as shown in table.
Value Description
1 Specifies that OK button is clicked.
2 Specifies that Cancel button is clicked.
3 Specifies that Abort button is clicked.
4 Specifies that Retry button is clicked.
5 Specifies that Ignore button is clicked.
6 Specifies that Yes button is clicked.
7 Specifies that No button is clicked.
Sub result( )
Dim n As Integer
n = MsgBox("Did you score more then 50%", vbYesNo,
"Printing file")
If n = 6 Then
MsgBox ("Congratulations")
Else
MsgBox ("Better luck next time")
End If
End Sub
Input box
For accepting the input from the user the input box is used in two ways- the
input box method and the input box function.
The input box method
The input box method differs from the input box function in that it allows
selective validation of the user’s input, and it can be used with Microsoft
excel objects, error values and formulas.
Its syntax is:
Inputbox (prompt,title,default,left,top,helpfile,helpcontextid,type)
Type that allows specifying the type of data we are going to collect. These
are as shown below:
Type:=0 A formula
Type:=1 A number
Type:=2 Text(a string)
Type:=4 A logical values(true or False)
Type:=8 A cell reference, as a Range object
Type:=16 An error value, such as #N/A
Type:=64 An array of values
For eg:
Sub test( )
Dim n As Integer
n = Application.InputBox("Enter your age:", "Personal
details", , , , , , 1)
If (n > 60) Then
MsgBox "you are eligible for senior citizen's concession"
Else
MsgBox "no concession"
End If
End Sub
Syntax:
If condition then
‘ code if the condition is met
Else
‘code if the condition is not met
End if
Eg:
Sub test( )
Dim income as long
Income=application.inputbox(“Enter you Taxxable income”)
If income<25000 then
Msgbox ”you need not pay any income tax”
Else
Msgbox ” you must pay income tax”
End if
End sub
Using multiple if statements
Sometimes the condition being tested is to be evaluated not just for returning
“True” or “False” based on one condition, but for multiple conditions too. In
such cases the multiple if then …. Else statements can be used.
Select …Case
Select…case statements can be used to easily evaluate the same variable
multiple times and then take a particular action depending on the evaluation.
Syntax:
Select case variable
Case value1
‘code to run if variable equals value1
Case value2
‘code to run if variable equals value2
Case value3
‘code to run if variable equals value3
Case else
‘code to run for remaining cases
End select
Eg:
Sub players()
Dim game As String
game = InputBox("Enter the name of the game")
Select Case game
Case "tennis"
Debug.Print "2 players"
Case "cricket"
Debug.Print "11 players"
Case "baseball"
Debug.Print "9 players"
Case Else
Debug.Print "I have no idea."
End Select
End Sub
The do while…loop
The do while…loop repeats a statement or group of statements as long as the
condition is true.
Like the do until loop, a do while loop can be also be used in two ways.
Eg:
Sub dowhileloop( )
Dim n As Integer
n=1
n < 10
n=n+1
Debug.Print n
Loop
End Sub
Do…loop while
In a do…loop while, a set of statements in the loop are executed once, then
the condition is checked. The code in the loop is executed only if the
condition is met.
Eg:
Sub doloopwhile()
Dim row As Integer
row = 0
Do
row = row + 1
Debug.Print row
Loop While row < 10
End Sub
Len( )function
Returns an integer containing either the number of characters in a string.
Syntax: len(string)
Eg:
Sub strcat()
Dim a As String
a = "Computer Operator and Programming Assistant"
Debug.Print "the length of the string is " & Len(a)
End Sub
Left( )
Returns a string containing a specified number of characters from the left side
of a string.
Syntax: left( string,Int)
Right( )
Returns a string containing a specified number of characters from the right
side of a string.
Syntax: right(string,Int)
Mid( )
Returns a string that contains all the characters starting from a specified
position in a string
Syntax: mid(string,int) or mid(string,int,int)
Examples:
1) Sub stringpro( )
Dim a As String
s = "Indian Army"
Debug.Print Left(s, 5)
End Sub
2) Sub stringpro( )
Dim a As String
s = "Computer"
Debug.Print Right(s, 5)
End Sub
3) Sub stringpro( )
Dim s As String
s = "wholehearted"
Debug.Print Mid(s, 6)
End Sub
4) Sub stringpro( )
Dim s As String
s = "wholehearted"
Debug.Print Mid(s, 6, 4)
End Sub
Ltrim( )
Returns a string containing a copy of a specified string with no leading spaces
Syntax: Ltrim(string)
Rtrim( )
Returns as string containing a copy of a specified string with no trailing
spaces.
Syntax: Rtrim(String)
Trim( )
Returns a string containing a copy of a specified string with no leading or
trailing spaces.
Syntax: Trim(String)
Example:
Sub stringpro()
Dim s As String
s = " Adjustment "
Debug.Print "For everyone" & LTrim(s) & "is a must"
Debug.Print "For everyone" & RTrim(s) & "is a must"
Debug.Print "For everyone" & Trim(s) & "is a must"
End Sub
Instr( )
Returns an integer specifying the start position of the first occurrence of one
string within another.
Syntax: instr([start,]string1,string2[,compare])
Eg:
Sub stringpro()
Dim a, b As String
a = "hairdresser"
b = "dress"
Debug.Print "The second string starts at position no.:" & InStr(1, a, b)
End Sub
Replace( )
The replace( ) function replaces a sequence of characters in a string with
another set of characters.
Eg:
Sub stringpro()
Debug.Print Replace("majority", "aj", "in", 1)
Debug.Print Replace("think and think", "i", "a", 1, 1)
End Sub
Val( )
The val( ) function accepts a string as input and returns the numbers found in
that string.
Syntax: val(string)
Eg:
Sub stringpro()
Dim s1, s2, s3 As String
s1 = "6 feet 1 inch is his height"
s2 = "5-6 kms is the distance to my office from here."
s3 = "0112222222 is my phone number"
Debug.Print Val(s1)
Debug.Print Val(s2)
Debug.Print Val(s3)
End Sub
The string conversion function
Lcase( )
Returns a string or character converted to Lowercase.
Syntax: Lcase(string)
Ucase( )
Returns a string or character converted to Uppercase.
Syntax: Ucase(string)
Eg:
Sub stringpro()
Dim a, b As String
a = "IF YOU FEAR YOU WILL BECOME WEAK"
b = "be a strong person"
Debug.Print LCase(a)
Debug.Print UCase(b)
End Sub
Asc( )
The Asc( ) function returns an integer value representing the ASCII code
corresponding to a character or the first character in a string.
Syntax: Asc(string)
Eg: Asc(“A”) will return 65
Chr( )
The chr( ) function returns the character associated with the specified ASCII
code.
Syntax:Chr(Integer)
Eg: Chr(68) will return the character “D”
Reverse String
StrReverse
Returns a string in which the character order of a specified string is reversed.
Syntax: StrReverse(string)
Eg:
Sub stringpro( )
Dim a As String
a = "desserts"
Debug.Print StrReverse(a)
End Sub
Introduction
VBA has a rich collection of built in functions that perform a variety of tasks
and calculations. Using the VBA built in functions will help coding much
easier for the user.
Math functions
Eg:
Dim a as integer
a=81
Debug.print sqr(a)
This will display the square root of 81 i.e.9
Logical functions
Eg:
Sub test()
Debug.Print DateDiff("yyyy", "1/12/1999", "31/1/2003")
End Sub
The result will be
4
Chapter 8: Arrays
Introduction
An array is a group of variables of the same data type and with the same
name.
Declaring an array
Dim students(10) as integer
Dim sname(3) as string
Eg:
Sub array_test()
Dim arr(5) As Integer
Dim n As Integer
arr(0) = 89
arr(1) = 83
arr(2) = 62
arr(3) = 99
arr(4) = 56
For n = 0 To 4
Debug.Print arr(n)
Next
End Sub
Types of arrays:
1. Static arrays
2. Dynamic arrays
Static array: A static array is an array that is sized in the Dim statement that
declares the array.
Eg:Dim staticarray(1 to 10) as long
You cannot change the size or data type of a static array.
Dynamic Array: A dynamic array is an array that is not sized in the dim
statement. Dynamic array variables are useful when we don’t know in
advance how many elements need to be stored in the array.
Eg: Dim DynamicArray( ) as long