VBA Macros
VBA Macros
Table of Contents
• VBA Disadvantages
– Difficulty of learning a programming language
– You cannot assume that your VBA program works always correctly under all
circumstances. Check macro settings
– There are issues with different versions of excel 2000, 2003, 2007 etc., You
need to catch up with latest.
Starting with Macros
Visual Basic Macros Tool Bar Open and study this Macro code
Using Visual Basic Editor -ALT+F11 in Module1
ALT+F11 acts as toggle switch between VB editor
Setting security level of Macros and Excel WB
Record Macro Recording Macro could be used to capture some of
1. Open CreditBankding.xls, Spend sheet the Code in your VBA code writing
Tool Bar
Code Window
Project Explorer
Window
Module contains
Declarations of variables
Sub procedures(marco) to perform
Properties actions
Window Functions to return values
Immediate Window
Project Explorer, Modules-> Module1 VBA code could be run on any of the objects of workbook.
You can insert/remove modules like standard module, class module contain you own objects,
user forms
Properties of the object
Creating Modules –Insert-Module standard modules or code modules.
Writing good code
Code indentation & Comments
Use Immediate window to experiment any code
Starting with Macros - Observations
Range(“A1:D10”).Select - selection of cells
Some of the VBA Statements and you get run time errors
for buggy code
With Selection.Font ‘ font selection Macros can be recorded using relative addressing using
developer->code->Relative addressing
.Name=“Tahoma” ‘ to Tahoma with
Size=11 ‘ size 11
Strikethrough=False
???????
?????
End With
Selection.Font.Bold=true ‘Fonts are made Bold
End Sub ‘ End of the sub procedure
Another Example
Sub Exercise()
ActiveCell.FormulaR1C1.value = "=2"
End Sub
Macros can be recorded using relative addressing
Object Oriented Programming
Visual Basic for Applications (VBA) is a structured programming language where sentences
(called statements) are constructed of building blocks such as Class, objects, methods, and
properties and Events. These VBA statements are grouped in larger blocks called
procedures. A procedure is a set of VBA statements that performs a specific task or
calculates a specific result. The first step to learning how to create procedures is to learn
about the building blocks. Objects are instances of Class. Ex. Chair is class Godrej Model
chair ME100 an object & an instance of class chair .
VBA Procedure
Interest = Application.workbooks(“exampleExcel.xlsx”).worksheet(“Sheet1”).Range(“A1”).value
Objects and Collections
Objects:
VBA is an object-oriented programming language, which means the statements you create in VBA act on
specific objects rather than begin general commands. Excel is made of objects that you can manipulate
through the VBA statements. Objects have properties like .value, methods like clearcontents
The Fields in the object capture their state. Customer
Class can contain customernumber, loyalty status etc., Workbook
Worksheet
Objects in Excel
Range
Cell
Collections: Many objects belong to collections related in hierarchical or tree structure.
For example, a workbook is a collection of all the objects it contains like ex. sheets, cells, ranges, charts,
VBA modules, etc.. City is collection of buildings which is collection of floors which is collection of rooms
Rows
Worksheets
Collection of Objects
Cells
Workbooks
Workbooks(“Sales.xls”).WorkSheets(“Sheet1”).Range(“A1”)
Objects in Excel are Collections – Top one is Application. Objects are arranged in
Hierarchy and they act as containers. Each hierarchy is separated by dot(.)
Workbook Application.Workbooks(“Sales.xls”)
Pivot
Chart Range
Table
Application.Workbooks(“Sales.xls”).WorkS
heets(“Sheet1”).Range(“A1”)
Events:
Objects respond to Events. Event is an action initiated by other users or procedures like Application.sheetactivate event
occurs when any sheet is activated. A mouse click on a command button then you need to write appropriate code to
respond click, double click, focus etc., All form, Activex controls can respond to events.
Examples:
Object.Method
Ball.kick, Book.read, Book.write, Water.Drink, Food.Eat
Balls(“soccer”).kick
Balls(“soccer”).kick Direction:=Left, Force:=Hard, Elevation:=High
wordart.Add Left:=10,Top:=20,width:=100, Height:=200
Worksheets.Add Before:=Worksheets(1)
Set MyWorksheet = Worksheets.Add (Before:=Worksheets(1))
Object.property –
ActiveCell.Interior.ColorIndex = 30 --- (Color the Cell Yellow)
Object.Event - Workbook.open
What is Variable ?
Use Object Browser-F2
Object Browser is valuable tool for discovering the fields, properties, methods and events applicable to Excel objects.
It is a centralized location for exploring all the classes and their constituent members.
Type workbook in search box and press find binoculars
Then workbook related class is displayed along with its
members.
You can also look at help Excel object reference model.
Immediate window
it is used to test the code . Just enter the code and press return. That VB statement is executed some samples are
'fill first column with 1 to 10 number from Row 1 column 1 IF <condition> then
Sub Ten() statement
Dim a As Integer Elseif <condition2>
Dim rowi As Integer statement
Dim coli As Integer Else
a=0 statement
rowi = 0 ' for row number Endif
coli = 1 ' for column number Case Statement
Do While a < 10 ‘ execute when condition is true While .. Wend like do while
a=a+1 ‘ whereas do until execute when condition is false Do .. Until executes when condition is false
rowi = rowi + 1 For variable =1 to x
Sheet1.Cells(rowi, coli).Value = a Statements
'MsgBox ("vaue of A " & a) ' coded for debugging purpose Next variable
Loop 'end for do Exit do, for
End Sub With .. End with
Arrays
Form or Active-X controls
Enumeration variables are variables declared with an Enum type. Both variables and parameters
can be declared with an Enum type. The elements of the Enum type are initialized to constant
values within the Enum statement. The assigned values can't be modified at run time and can
include both positive and negative numbers. For example:
Enum SecurityLevel
IllegalEntry = -1
SecurityLevel1 = 0
SecurityLevel2 = 1
End Enum
Types of Variables – scope and life time of variables
Local Variables are declared inside sub whereas global variables are declared outside sub
A local variable is one that is declared inside a procedure. This variable is only available to the code inside the procedure
and can be declared using the Dim statements as given below. Dim <variableName> as datatype. Default is variant type
Static Variables
Static variables are not reinitialized each time a procedure is invoked and therefore retains or preserves value even when
a procedure ends. A static variable is declared as given below.
You need to use various data conversion functions like Cbyte, Cint, clng, csng,cdbl, ccur
You can use operations like =, & for string concatenation , +, -, *, \ for integer division , / for
Decimal division, ^ for exponentiation, mod for reminder, and bitwise operations
Sub Examplefunctioncall()
CallMe
End Sub
Property Procedures
A property procedure is used to create and manipulate custom properties. It is
used to create read only properties for Forms, Standard modules and Class
modules. Visual Basic provides three kind of property procedures-Property Let
procedure that sets the value of a property, Property Get procedure that returns
the value of a property, and Property Set procedure that sets the references to
an object.
Procedures
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an underscore(_), and the event name.
The following syntax represents the event procedure for a Form_Load event. The various events are click, dblclick
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a good programming
practice to write common statements in a separate procedure (general procedure) and then call them in the event
procedure..
Data Types
1. Numeric
I. Byte - Store integer values in the range of 0 - 255
II. Integer - Store integer values in the range of (-32,768) - (+ 32,767)
III. Long - Store integer values in the range of (- 2,147,483,468) - (+ 2,147,483,468)
IV. Single - Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)
V. Double - Store large floating value which exceeding the single data type value
VI. Currency - store monetary values. It supports 4 digits to the right of decimal point and 15 digits to the left
2. String – Use to store alphanumeric values. A variable length string can store approximately 4 billion characters
3. Date – Use to store date and time values. A variable declared as date type can store both date and time values and it
can store date values 01/01/0100 up to 12/31/9999
4. Boolean – Boolean data types hold either a true or false value. These are not stored as numeric values and cannot be
used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true
5. Variant – Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a variable
without any data type by default the data type is assigned as default.
Shortcuts
Range(“D5”) [D5]
Range(“A1:D5”) [A1:D5]
Range(“A1:D5”,”G6:I17”) [A1:D5,G6:I17]
Range(“MyRange”) [MyRange]
Full reference is
Application.workbooks(“evba.xlsm”).worksheets(“sheet1”).range(“a1”).value
MessageBox Function
Displays a message in a dialog box and wait for the user to click a button, and returns an integer indicating which button
the user clicked.
Syntax :
MsgBox ( Prompt [,icons+buttons ] [,title ] )
memory_variable = MsgBox ( prompt [, icons+ buttons] [,title] )
Prompt – String expressions displayed as the message in the dialog box. If prompt consist of more than one line, you can
separate the lines using the vbrCrLf constant.
Icons + Buttons – Numeric expression that is the sum of values specifying the number and type of buttons and icon to
display.
Title – String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the
title bar.
Sub inputval()
Following is an expanded InputBox ‘ To accept a value , add with 1 and display it
Dim a As Integer
a = InputBox("give the value of A ", “INavalue", Default)
a=a+1
MsgBox ("the value of A " & a)
End Sub
Syntax :
memory_variable = InputBox (prompt[,title][,default])
memory_variable is a variant data type but typically it is declared as string, which accept the message input by the users.
The arguments are explained as follows:
Prompt – String expression displayed as the message in the dialog box. If prompt consists of more than one line, you can
separate the lines using the vbCrLf constant
Title – String expression displayed in the title bar of the dialog box. If you omit the title, the application name is displayed
in the title bar
default-text – The default text that appears in the input field where users can use it as his intended input or he may
change to the message he wish to key in.
x-position and y-position – the position or the coordinate of the input box.
Following example demonstrates the use of InputBox function
• Open a new project and save the Form as InputBox.frm and save the Project as InputBox.vbp
• Design the application as shown below.
Referencing Ranges with Other Sheets
WorkSheets(“Sheet1”).Range(“A1”)
Workbooks(“InvoiceData.xls”).Worksheets(“Sheet1”).Range(“A1”)
WorksheetFunction.Sum(Worksheets(“Sheet2”).Range(Range(“A1”),Range(“A7”))) – Wrong
WorksheetFunction.Sum(Worksheets(“Sheet2”).Range(Worksheets(“Sheet2”).Range(“A1”),
Worksheets(“Sheet2”).Range(“A7”)))
With Worksheets(“Sheets2”)
WorksheetFunction.Sum(Range(Range(“A1”), range(“A7”)))
End With
Cells Property to Select Range
Cell Item Property
Cells.Item(Row,Column)
Cells.Item(5,”c”) or Cells.Item(5,3)
Enables to change the size of range based off the location of active cell
Sub try()
End Sub
Range(“A1”).Offset(Colunmoffset:=1) or Range(“A1”).Offset(,1)
Range(“A1”).Offset(Rowoffset:=1) or Range(“A1”).Offset(-1)
Sub try1()
Set Rng = Range("B1:B16").Find(What:="0", Lookat:=xlWhole, LookIn:=xlValues)
Rng.Offset(, 1).Value = "Low"
End Sub
Cereals 45
Dals 0
Noodles 15
Masala 10
Biscuits 60
Union Method to Join Multiple Ranges
Application.Union(argument1, argument2,…..)
-- this code joins two named ranges on the sheet, inserts the =RAND() formulas,
and bolds them
Sub OpenAWorkbook()
Dim IsOpen As Boolean
Dim Bookname As String
Bookname = "Excel_Macros1.xls"
IsOpen = BookOpen(Bookname)
If IsOpen Then
MsgBox Bookname & "is Already Open"
Else
Workbooks.Open (Bookname)
End If
End Sub
More Examples…
Sub Count()
mycount = Selection.Rows.Count ‘count the rows and columns that are selected
count columns
MsgBox mycount
End Sub
Count2()
‘count number of sheets
mycount = Application.Sheets.Count
MsgBox mycount
End Sub
Sub CopyRange()
‘Copy selected cell to a destination
Range("A1:A3").Copy Destination:=ActiveCell
End Sub
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is tested; if condition is True,
then the statements are executed. When it gets to the Loop it goes back to the Do and tests condition again. If condition is
False on the first pass, the statements are never executed
Do Loop while
The programs executes the statements between Do and Loop While structure in any case. Then it determines whether the
counter is less than 201. If so, the program again executes the statements between Do and Loop While else exits the
Loop.
Do until
Do Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loop structure tests a condition for
falsity. Statements in the body of a Do Until...Loop are executed repeatedly as long as the loop-continuation test
evaluates to False.
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.
For Next …
Dim x As Integer
For x = 1 To 50
Cells(x,2) = x
Next
In order to count the numbers from 1 to 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Cells(x,2) = x
Next
In the output instead of number 4 you will get the "This is number 4".
Examples function sales commission
Function Comm(Sales_V As Variant) as Variant
If Sales_V <500 Then
Comm=Sales_V*0.03
Elseif Sales_V>=500 and Sales_V<1000 Then
Comm=Sales_V*0.06
Elseif Sales_V>=1000 and Sales_V<2000 Then
Comm=Sales_V*0.09
Elseif Sales_V>=200 and Sales_V<5000 Then
Comm=Sales_V*0.12
Elseif Sales_V>=5000 Then
Comm=Sales_V*0.15 /’Subject to certain changes in Form1 statement’/
End If
End Function Private Sub addName()
Dim studentName(10) As String
Dim num As Integer
For num = 1 To 10
studentName(num) = InputBox("Enter the student name",
"Enter Name", "", 1500, 4500)
If studentName(num) <> "" Then
Form1.Print studentName(num)
Else
End
End If
Next
End Sub
Examples try for loop
Ex 1:
Sub tryloop()
For I = 1 to 10
cells(i,i).value = I
Next I
End Sub
For I = 2 to 10
if cells(I,6).value >0 then
Cells(I,8).value = “service revenue”
Cells(I,1).resize(1,8).interior. Colorindex = 4
End if
Next i
FinalRow = Cells(65536,1).end(xlup).row
For I = FinalRow to Step -1
if Cells(I,3).value = “s54” then
Cells(I,1).EntireRow.Delete
End if
Next I
Ex: Looks for row in dataset where service rev in column F is positive and product
Rev in Column E is 0.
There are two types of controls 1) form controls 2) activex controls. Form controls are old generation and Activex are new
and rich in features and driven by properties. Once you right click form controls, it gives assign macro, Activex show the
properties. Form controls can respond to single predefined events whereas Activex controls can respond to many events
like mouse click, double click, key press on keyboard etc., When you right click a control, if you get assign macro, it is form
control otherwise it is activex control with properties.
In addition to properties and events, methods can also be used to manipulate controls from code. For instance, the move
method can be used with some controls to change their location and size.
Objects' properties are very important as it can help you to write a good program to respond to various events so better
to spend some time with each object and its properties. Object Browser will help you to explore objects.
Here are some important points about setting up the properties
• You should set the Caption Property of a control clearly so that a user knows
what to do with that command. For example, in the calculator program, all the
captions of the command buttons such as +, - , MC, MR are commonly found in
an ordinary calculator, a user should have no problem in manipulating the
buttons
• A lot of programmers like to use a meaningful name for the Name Property may
be because it is easier for them to write and read the event procedure and easier
to debug or modify the programs later. However, it is not a must to do that as
long as you label your objects clearly and use comments in the program
whenever you feel necessary
• One more important property is whether the control is enabled or not Using
Visible Property . You can control visible or invisible at runtime, or when
should it become visible or invisible
• There are various events to respond and you need to write code for each event
you are interested in like click, double click etc.,
Control Properties
TabIndex property of Controls
(the order of the controls focus is managed with TabIndex property it starts from zero)
Visual Basic uses the TabIndex property to determine the control that would receive the focus next when a tab key is
pressed. Every time a tab key is pressed, Visual Basic looks at the value of the TabIndex for the control that has focus and
then it scans through the controls searching for the next highest TabIndex number. When there are no more controls with
higher TabIndex value, Visual Basic starts all over again with 0 and looks for the first control with TabIndex of 0 or higher
that can accept keyboard input.
By default, Visual Basic assigns a tab order to control as we draw the controls on the Form, except for Menu, Timer, Data,
Image, Line and Shape controls, which are not included in tab order. At run time, invisible or disabled controls also cannot
receive the focus although a TabIndex value is given. Setting the TabIndex property of controls is compulsory in
development environment.
To run code, switch back to the worksheet, turn off design mode, and click the command button.
It stops highlighting design mode button.
Object Browser
Press F2 in Visual Basic Editor . Any object with code will appear in bold .
• Displays all of the available classes in the library or project selected in the Project/Libraries box. If there is code
written for a class, that class appears in bold. The list always begins with <globals>, a list of globally accessible
members.
• If you select a Class and do not specify a member, you will get the default member if one is available. The default
member is identified by an asterisk (*) or by the default icon specific to the member.
Members list
Displays the elements of the class selected in the Classes pane by group and then alphabetically within each group.
Methods, properties, events, or constants that have code written for them appear bold. You can change the order of this
list with the Group Members command on the Object Browser shortcut menu.
Methods
Events
Properties
Enumeration objects
Text Box
Text Box Property of Controls
A TextBox control is an edit field or edit control, displays information entered at design time, entered by the user, or
assigned to the control using code at run time. Default event is change() and default property is value.
• In order to work with the part of a text in a text box, the text can be selected using three properties:
SelStart – Returns or sets the starting point of selected text. When no text is selected, SelStart indicates the position of
the inserted point.
SelText – Returns or sets the string containing the currently selected text. If no text is selected, SelText consists of a zero-
length string.
Using a CommandButton
We can begin, interrupt or end a process using the CommandButton control
Example
Open a new Standard EXE project and the save the Form as Option.frm and save the project as Option.vbp
The application responds to the following events
The click event of the optWithoutMeal displays the amount of 2500 in txtAmount.
The click event of the optWithMeal displays the amount of 3500 in txtAmount.
The click event of the optLuxuty displays the amount of 5000 in txtAmount.
The click event of the cmdExit terminates the program
Following code is typed in the click events of the option buttons and the Exit button.
The Application is run by pressing F5 or clicking on the Run icon in the tool bar. By pressing the Exit button the program
is terminated.
Private Sub OptionButton1_Click() ‘ create male and female two option buttons
If OptionButton1.Value = True Then
MsgBox "I am Male "
Else
End If
End Sub
Private Sub OptionButton2_Click()
If OptionButton2.Value = True Then
MsgBox "I am Female“
End If
End Sub
List Box and Combo Box
ListBox and ComboBox controls present a set of choices that are displayed vertically in a column. If the number of items
exceed the value that be displayed, scroll bars will automatically appear on the control. These scroll bars can be scrolled
up and down or left to right through the list.
The following Fig lists some of the common ComboBox properties and methods.
Run Time : The AddItem method is used to add items to a list at run time. The AddItem method uses the following syntax.
Object.AddItemitem, Index The item argument is a string that represents the text to add to the list
The index argument is an integer that indicates where in the list to add the new item. Not giving the index is not a
problem, because by default the index is assigned.
Following is an example to add item to a combo box. The code is typed in the Form_Load event
The Simple Combo box displays an edit area with an attached list box always visible immediately below the edit area. A
simple combo box displays the contents of its list all the time. The user can select an item from the list or type an item in
the edit box portion of the combo box. A scroll bar is displayed beside the list if there are too many items to be displayed in
the list box area.
The Dropdown Combo box first appears as only an edit area with a down arrow button at the right. The list portion stays
hidden until the user clicks the down-arrow button to drop down the list portion. The user can either select a value from the
list or type a value in the edit area.
The Dropdown list combo box turns the combo box into a Dropdown list box. At run time , the control looks like the
Dropdown combo box. The user could click the down arrow to view the list. The difference between Dropdown combo &
Dropdown list combo is that the edit area in the Dropdown list combo is disabled. The user can only select an item and
cannot type anything in the edit area. Anyway this area displays the selected item.
Example
This example is to Add , Remove, Clear the list of items and finally close the application.
Open a new Standard EXE project is opened an named the Form as Listbox.frm and save the project as Listbox.vbp
Design the application as shown below.
The following event procedures are entered for the TextBox and CommandButton controls.
The click event of the Add button adds the text to the list box that was typed in the Text box. Then the text box is cleared
and the focus is got to the text box. The number of entered values will is increased according to the number of items
added to the listbox.
Command Buttons
Remove button removes the selected item from the list as soon as you pressed the Remove button. The number of items
is decreased in the listbox and the value is displayed in the label.
The code for the clear button clears the listbox when you press it. And the number of items shown in the label becomes 0.
Using ScrollBar Control
The ScrollBar is a commonly used control, which enables the user to select a value by positioning it at the desired location.
It represents a set of values. The Min and Max property represents the minimum and maximum value. The value property
of the ScrollBar represents its current value, that may be any integer between minimum and maximum values assigned.
Following example illustrates the ScrollBar control
• Open a new Standard EXE project and name the form as ScrollBar.frm and name the project as ScrollBar.vbp
• When the thumb's position of the ScrollBar is changed the value has to displayed in the TextBox.
• Design the application as shown below.
The following codes are entered in the vsb1_Change( ) and cmdExit_Click( ) procedures.
Save the project and run the application by pressing F5 or clicking the Run icon in the ToolBar. We can see the value
changes as soon as you move the thumb's position of the vertical scroll bar.
Retaining Value in other procedures using public or static in sub reentry
A Variable declared in one procedure is called private and the value exist only in that procedure. If you want to use the
value of variable in other sub or function, you need to declare it as public. Static retains its value when it reenters sub.
Option Explicit
Public pv As Variant ' declared as public variable so value could be used anywhere
Public Sub pass()
pv = InputBox("give your value")
Call othersub ' the value given to pv could be used in othersub
End Sub
Sub othersub()
Static fn 'this may not be useful as you are not reentering into this sub subsequently
MsgBox ("PV value in othersub is " & pv)
pv = pv + 10
MsgBox ("new PV value" & pv)
fn = mul(pv, 50)
fn = mul(pv, 100)
Call fnval
For pv = 1 To 10 'when global variable value is change it is changed in all references wherever it is referred.
Call fnval
Next pv
End Sub
Function mul(pv, fn) As Integer 'fn is purely local variable nothing to do with fn in sub fnval()
mul = pv * fn 'this fn is nothing to do with fn declared in other modules
MsgBox ("mul value " & mul)
End Function
Sub fnval()
Static fn 'first entry fn value is empty when it reenters , it retains its computed value
MsgBox ("fnvalue " & fn & " pv value" & pv)
fn = fn + 10 'as fn is static , it retains its value when it reenters this sub in for loop of othersub() procedure
End Sub
Control Arrays
A control array is a group of controls that share the same name type and the same event procedures. Adding controls with
control arrays uses fewer resources than adding multiple control of same type at design time.
The following code is entered in the cmd_Click( ) (Control Array) event procedure
The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMultiply, cmdDevide controls respectively.
To print the result on the text box, the following code is entered in the cmdEqual_Click ( ) event procedure.
Save and run the project. On clicking digits of user's choice and an operator button, the output appears.
Using a CheckBox control
The CheckBox control is similar to the option button, except that a list of choices can be made using check boxes where
you cannot choose more than one selection using an OptionButton. By ticking the CheckBox the value is set to True. The
following example illustrates the use of CheckBox
• Open a new Project and save the Form as CheckBox.frm and save the Project as CheckBox.vbp
• Design the Form as shown below and type the code in module1
Using Userforms
When you want to get lot of information, then userforms are better tool. In VBE Editor, insert ->Userform
Add controls to user form , if controls are not visible , use view->toolbox to see the controls
User properties window to change the properties for controls like caption, name etc., use F4
Write event handler procedures for the controls like click , double click etc., use F7 to view the code , shift +F7 to see the
control
Wirite the procedure to display this user form like the following
Sub ckbx()
UserForm1.Show
UserForm1.Hide
Unload userform1
End Sub
Using CheckBoxes and option buttons
Following code is typed in the Click() events of the CheckBoxes and option buttons
option Explicit
Private Sub ChkBold_change()
If ChkBold.Value = True Then
TxtDisplay.FontBold = True
Else
TxtDisplay.FontBold = False
End If
End Sub
Private Sub ChkItalic_Click()
If ChkItalic.Value = True Then
TxtDisplay.FontItalic = True
Else
TxtDisplay.FontItalic = False
End If
End Sub
Private Sub ChkUnderline_Click()
If ChkUnderline.Value = True Then
TxtDisplay.FontUnderline = True
Else
TxtDisplay.FontUnderline = False
End If
End Sub
Syntax :
memory_variable = InputBox (prompt[,title][,default])
memory_variable is a variant data type but typically it is declared as string, which accept the message input by the users.
The arguments are explained as follows:
Prompt – String expression displayed as the message in the dialog box. If prompt consists of more than one line, you can
separate the lines using the vbCrLf constant
Title – String expression displayed in the title bar of the dialog box. If you omit the title, the application name is displayed
in the title bar
default-text – The default text that appears in the input field where users can use it as his intended input or he may
change to the message he wish to key in.
x-position and y-position – the position or the coordinate of the input box.
Following example demonstrates the use of InputBox function
• Open a new project and save the Form as InputBox.frm and save the Project as InputBox.vbp
• Design the application as shown below.
Write code for cmdOK click
Following code is entered in cmdOK_Click ( ) event
Private Sub cmdok_Click()
Dim ans As String
ans = InputBox("Enter something to be displayed in the label", "Testing", 0)
If ans = "" Then
lbl2.Caption = "No message"
Else
lbl2.Caption = ans
End If
End Sub
Save and run the application. As soon as you click the OK button you will
get the following InputBox
Here I have entered "Hello World" in text field. As soon as you click OK the output is shown as shown below
MessageBox Function
Displays a message in a dialog box and wait for the user to click a button, and returns an integer indicating which button
the user clicked.
Syntax :
MsgBox ( Prompt [,icons+buttons ] [,title ] )
memory_variable = MsgBox ( prompt [, icons+ buttons] [,title] )
Prompt – String expressions displayed as the message in the dialog box. If prompt consist of more than one line, you can
separate the lines using the vbrCrLf constant.
Icons + Buttons – Numeric expression that is the sum of values specifying the number and type of buttons and icon to
display.
Title – String expression displayed in the title bar of the dialog box. If you omit title, the application name is placed in the
title bar.
End If
End If
End If
End Sub
Following code is entered in the cmdExit_Click ( ) event
Private Sub cmdExit_Click()
answer = MsgBox("Do you want to quit?", vbExclamation + vbYesNo, "Confirm")
If answer = vbYes Then
End
Else
MsgBox "Action canceled", vbInformation, "Confirm"
End If
End Sub
Save and run the application. You can notice the different type of message box types are used to perform an action
User defined Functions
All the Excel functions are available in Fx (insert Function) , if these functions are not able to meet your requirement, you
You can create your own User defined functions . They reduce the complexity of worksheet and could be used by all
the people in the organization thus increasing the productivity due to reuse.
How much will the investment be worth at the end of three years? There are two ways to find the amount:
Suppose you have invested 50,000/- rs for 8% interst how much will it be after 5 years ?
The formula is Interest + principle = FD Amount (1+interst rate / 100)^ no. of years invested
=Yearly_Rate(A1,A2,A3) store FD amount in A1 50,000, interest rate in A2 =8/100, no. of years to invest in A3 =5 . You
get 73466.4 and only interest is 23466.4 after subtracting 50000/-
End Function
UDF for CentrigradetoFahrenheit , if conversion flag (cflag=1) it will convert from centigrade to Fahrenheit otherwise Fto C
UDFs can call other functions or subroutines but they cannot be used to change the structure or moving or copying the
cells
UDFs are not as efficient as built in Excel functions so the recalculation time is more for UDFs
You can use built in Excel functions using worksheetfunction.vlookup(Product, table, 2) but not all functions could be used
. You need to use VBA equivalent functions or mathematical operators to carry out same calculation.
Error-Handling and Debugging
No matter how hard we try, errors do creep into our programs. These errors can be grouped into three categories:
• Syntax errors
• Run-time errors
• Logic errors
– Syntax errors occur when you mistype a command or leave out an expected phrase or argument. Visual Basic detects
these errors as they occur and even provides help in correcting them. You cannot run a Visual Basic program until all
syntax errors have been corrected
– Run-time errors are usually beyond your program's control. Examples include: when a variable takes on an unexpected
value (divide by zero), when a drive door is left open, or when a file is not found. Visual Basic allows you to trap such
errors and make attempts to correct them
– Logic errors are the most difficult to find. With logic errors, the program will usually run, but will produce incorrect or
unexpected results. The Visual Basic debugger is an aid in detecting logic errors
– Design your application carefully. More design time means less debugging time
– Use comments where applicable to help you remember what you were trying to do
– Use consistent and meaningful naming conventions for your variables, objects, and procedures
Run-Time Error Trapping and Handling
• Run-time errors are trappable. That is, Visual Basic recognizes an error has occurred and enables you to trap it and take
corrective action. If an error occurs and is not trapped, your program will usually end in a rather unceremonious manner
• Error trapping is enabled with the On Error statement: On Error GoTo errlabel. Yes, this uses the dreaded GoTo
statement! Any time a run-time error occurs following this line, program control is transferred to the line labeled errlabel.
Recall a labeled line is simply a line with the label followed by a colon (:)
The best way to explain how to use error trapping is to look at an outline of an example procedure with error trapping.
Sub SubExample()
[Procedure code]
Exit Sub
HandleErrors:
End Sub
Once you have set up the variable declarations, constant definitions, and any other procedure preliminaries, the On Error
statement is executed to enable error trapping. Your normal procedure code follows this statement. The error handling
code goes at the end of the procedure, following the HandleErrors statement label. This is the code that is executed if an
error is encountered anywhere in the Sub procedure. Note you must exit (with Exit Sub) from the code before reaching the
HandleErrors line to avoid inadvertent execution of the error handling code.
• Since the error handling code is in the same procedure where an error occurs, all variables in that procedure are
available for possible corrective action. If at some time in your procedure, you want to turn off error trapping, that is done
with the following statement: On Error GoTo 0
• Once a run-time error occurs, we would like to know what the error is and attempt to fix it. This is done in the error
handling code
• Visual Basic offers help in identifying run-time errors. The Err object returns, in its Number property (Err.Number), the
number associated with the current error condition. (The Err function has other useful properties that we won’t cover
here - consult on-line help for further information.) The Error() function takes this error number as its argument and
returns a string description of the error. Consult on-line help for Visual Basic run-time error numbers and their
descriptions
• Once an error has been trapped and some action taken, control must be returned to your application. That control is
returned via the Resume statement. There are three options:
–Resume Lets you retry the operation that caused the error. That is, control is returned to the line where the error
occurred. This could be dangerous in that, if the error has not been corrected (via code or by the user), an infinite loop
between the error handler and the procedure code may result
–Resume Next Program control is returned to the line immediately following the line where the error occurred
–Resume label Program control is returned to the line labeled label
• Be careful with the Resume statement. When executing the error handling portion of the code and the end of the
procedure is encountered before a Resume, an error occurs. Likewise, if a Resume is encountered outside of the error
handling portion of the code, an error occurs
General Error Handling Procedure
• Development of an adequate error handling procedure is application dependent. You need to know what type of errors
you are looking for and what corrective actions must be taken if these errors are encountered. For example, if a 'divide
by zero' is found, you need to decide whether to skip the operation or do something to reset the offending denominator
• What we develop here is a generic framework for an error handling procedure. It simply informs the user that an error
has occurred, provides a description of the error, and allows the user to Abort, Retry, or Ignore. This framework is a good
starting point for designing custom error handling for your applications.
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
Let’s look at what goes on here. First, this routine is only executed when an error occurs. A message box is displayed,
using the Visual Basic provided error description [Error(Err.Number)] as the message, uses a critical icon along with the
Abort, Retry, and Ignore buttons, and uses the error number [Err.Number] as the title. This message box returns a
response indicating which button was selected by the user.
If Abort is selected, we simply exit the procedure. (This is done using a Resume to the line labeled ExitLine. Recall all
error trapping must be terminated with a Resume statement of some kind.)
If Retry is selected, the offending program line is retried (in a real application, you or the user would have to
change something here to correct the condition causing the error).
If Ignore is selected, program operation continues with the line following the error causing line.
To use this generic code in an existing procedure, you need to do three things:
Copy and paste the error handling code into the end of your procedure.
Place an Exit Sub line immediately preceding the HandleErrors labeled line.
Place the line, On Error GoTo HandleErrors, at the beginning of your procedure.
For example, if your procedure is the SubExample seen earlier, the modified code will look like this:
Sub SubExample()
.
. [Declare variables, ...]
.
On Error GoTo HandleErrors
.
. [Procedure code]
.
Exit Sub
HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
End Sub
Again, this is a very basic error-handling routine. You must determine its utility in your applications and make
any modifications necessary. Specifically, you need code to clear error conditions before using the Retry option.
• One last thing. Once you've written an error handling routine, you need to test it to make sure it works properly. But,
creating run-time errors is sometimes difficult and perhaps dangerous. Visual Basic comes to the rescue! The Visual
Basic Err object has a method (Raise) associated with it that simulates the occurrence of a run-time error. To cause an
error with value Number, use:
Err.Raise Number
• We can use this function to completely test the operation of any error handler we write. Don’t forget to remove the Raise
statement once testing is completed, though! And, to really get fancy, you can also use Raise to generate your own
‘application-defined’ errors. There are errors specific to your application that you want to trap
• To clear an error condition (any error, not just ones generated with the Raise method), use the method Clear:
Err.Clear
Command1:
Caption - Generate Error
Default - True
Name - cmdGenError Enter this code in module 1
Sub ergen()
Text1: frmerror.Show
Name - txtError frmerror.Hide
Text - [Blank] End Sub
Option Explicit
In this code, we simply generate an error using the number input in the text box. The generic error handler then displays a
message box which you can respond to in one of three ways.
Error codes and description
4. Save your application. Try it out using some of these typical error numbers (or use numbers found with on-line help).
Notice how program control changes depending on which button is clicked.
6 Overflow
9 Subscript out of range
11 Division by zero
13 Type mismatch
16 Expression too complex
20 Resume without error
52 Bad file name or number
53 File not found
55 File already open
61 Disk full
70 Permission denied
92 For loop not initialized
Debugging Visual Basic Programs
• We now consider the search for, and elimination of, logic errors. These are errors that don’t prevent an application from
running, but cause incorrect or unexpected results. Visual Basic provides an excellent set of debugging tools to aid in
this search. Debugging a code is an art, not a science. There are no prescribed processes that you can follow to
eliminate all logic errors in your program. The usual approach is to eliminate them as they are discovered.
• What we’ll do here is present the debugging tools available in the Visual Basic environment (several of which appear as
buttons on the toolbar) and describe their use with an example. You, as the program designer, should select the
debugging approach and tools you feel most comfortable with.
• The interface between your application and the debugging tools is via three different debug windows: the Immediate
Window, the Locals Window, and the Watch Window. These windows can be accessed from the View menu (the
Immediate Window can be accessed by pressing Ctrl+G). Or, they can be selected from the Debug Toolbar (accessed
using the Toolbars option under the View menu):
All debugging using the debug windows is done when your application is in break mode. You can enter break mode by
setting breakpoints, pressing Ctrl+Break, or the program will go into break mode if it encounters an untrapped error or a
Stop statement.
Once in break mode, the debug windows and other tools can be used to:
Determine values of variables
Set breakpoints
Set watch variables and expressions
Manually control the application
Determine which procedures have been called
Change the values of variables and properties
Example – Debugging
1. Unlike other examples, we’ll do this one as a group. It will be used to demonstrate use of the debugging tools.
2. The example simply has a form with a single command button. The button is used to execute some code. We won’t be
real careful about proper naming conventions and such in this example.
3. The code attached to this button’s Click event is a simple loop that evaluates a function at several values.