Excel ± VBA / Macros

Table of Contents
‡ Starting with Macros - Recording and Running a Macro ‡ Introduction to Visual Basic Concepts of Object Oriented Programming ‡ Data Types, Variables, Procedures & Operators ‡ Range Selection ‡ Control Statements ± If« Then ± With« End With ± For... Next ± Do« Loop ± Do« Until ± Do While« Loop ± While« Wend ± Select Case ‡ Arrays and Counter ‡ String Handling ‡ Input Box and Message Box Functions ‡ Working with Controls ± Text Box, Label, Scroll Bar and Check box ‡ A User-Defined Function for Calculating Interest ‡ Error Handling and Debugging

‡

VBA advantages
± Excel VBA executes in the same way consistently without errors. ± Someone who does not know anything about excel can do complex tasks using VBA. ± Boring, time consuming are relatively easy

‡

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 Setting security level of Macros Record Macro 1. Open CreditBankding.xls, Spend sheet 2. Go to View Ribbon select Macros ± Record macro 3. Fill in the required details in Macros dialog box. 4. Select cells A1 to D10 5. Apply the following formats to selected cells 6. Change font to Tahoma and font size to 12 7. Right align and bold 8. Change font color to red and fill color to yellow 9. Stop recording Macro Study this macro and Re-Run Macro on other sheets using F5 Comments start with apostrophe µ
Open and study this Macro code Using Visual Basic Editor -ALT+F11 in Module1 ALT+F11 acts as toggle switch between VB editor and Excel WB Recording Macro could be used to capture some of the Code in your VBA code writing

user forms Properties of the object Creating Modules ±Insert-Module standard modules or code modules. Modules-> Module1 VBA code could be run on any of the objects of workbook.MS Visual Basic Interface (ALT + F11) Menu Bar Tool Bar Code Window Project Explorer Window Properties Window Immediate Window Module contains Declarations of variables Sub procedures(marco) to perform actions Functions to return values Project Explorer. Writing good code Code indentation & Comments Use Immediate window to experiment any code . class module contain you own objects. You can insert/remove modules like standard module.

value = "=2" End Sub Macros can be recorded using relative addressing µFonts are made Bold µ End of the sub procedure µ font selection µ to Tahoma with µ size 11 Some of the VBA Statements and you get run time errors for buggy code Macros can be recorded using relative addressing using developer->code->Relative addressing .Font .Select .Starting with Macros .Font.FormulaR1C1.Observations Range(³A1:D10´).Bold=true End Sub Another Example Sub Exercise() ActiveCell.Name=³Tahoma´ Size=11 Strikethrough=False ??????? ????? End With Selection.selection of cells With Selection.

The first step to learning how to create procedures is to learn about the building blocks. objects.worksheet(³Sheet1´). and properties and Events.workbooks(³exampleExcel. methods.value .Range(³A1´).xlsx´). VBA Procedure Objects Methods Properties Events Interest = Application. Chair is class Godrej Model chair ME100 an object & an instance of class chair . Ex. Objects are instances of Class. 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.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.

Range(³A1´) . loyalty status etc.. cells. sheets. charts.value. VBA modules. ranges. 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. Worksheet Objects in Excel Range Cell Collections: Many objects belong to collections related in hierarchical or tree structure. City is collection of buildings which is collection of floors which is collection of rooms Rows Worksheets Collection of Objects Cells Workbooks Workbooks(³Sales.. For example. Customer Workbook Class can contain customernumber. a workbook is a collection of all the objects it contains like ex. methods like clearcontents The Fields in the object capture their state.WorkSheets(³Sheet1´). etc.Objects and Collections Objects: VBA is an object-oriented programming language. Objects have properties like .xls´).

Workbooks(³Sales.WorkSheets(³Sheet1´) Worksheet Add-ins Chart Pivot Table Range Application.cells Workbook Application.Workbooks(³Sales.range.1).xls ´).belowobjects like Workbooks.) Application Application.WorkSheets(³Sheet 1´). worksheets.1).xls´).xls´) Application. Objects are arranged in Hierarchy and they act as containers.cells(3.Workbooks(³Sales.clearcontents Cells Workbooks(³Sales.WorkS heets(³Sheet1´).value to refer to row 3 and column A contents using value property .Range(³A1´) Every object (ex. Cell ) has a property like value Every object has even method too like Cells(3.Objects in Excel are Collections ± Top one is Application. Each hierarchy is separated by dot(.xls´).

Interior. All form. Some properties are read-only. That path is a property of the workbook.xls´).ColorIndex = 30 --. Food. Force:=Hard. Height:=200 Worksheets.Add (Before:=Worksheets(1)) Object. if you wanted to save a particular file as part of a VBA program you could include the following sentence in the code: Workbooks(³Training.value=10 Methods: A method is an action that can be performed on an object sometimes change the properties.Event .select .paste destination:=range(³c5´) parameter is given with := Events: Objects respond to Events.width:=100.Workbook.Path Activecell.kick Balls(³soccer´). while others are read/write.Drink. Properties are separated from objects by periods just as methods are. an Excel workbook has a particular path on your hard drive or network where it is saved.property ± ActiveCell.Method Ball. Book. focus etc.xls file in an onscreen message box: Msgbox Workbooks(³Training.kick Direction:=Left.kick. Excel VBA objects are separated from their methods by a period. Water. double click.columnwidth=20 to change the width property.. Event is an action initiated by other users or procedures like Application.Properties: Properties are used to describe an object. That path is read-only as it cannot be changed without saving the file to a different location. Activesheet.worksheets(³Datainput´). Methods & Events for the objects±Use Object Browser-F2 What is Variable ? .range(³a4).write.Add Left:=10. The following sentence will display the current path of the Training.Save.sheetactivate event occurs when any sheet is activated.Top:=20.read. For example.xls´).open Properties .Add Before:=Worksheets(1) Set MyWorksheet = Worksheets. A mouse click on a command button then you need to write appropriate code to respond click. Range(³A3´). Range(³A1:E6´). These properties describe Excel objects. workbooks(³sales.Eat Balls(³soccer´). Examples: Object.xls´). For example. Activex controls can respond to events.copy . Elevation:=High wordart.(Color the Cell Yellow) Object. Book.

xls³ µ to open a excel file workbooks.xls"). That VB statement is executed some samples are workbooks.activate ?cells(2.Value="this is active cells³ µ to push values in active cell .Use Object Browser-F2 Object Browser is valuable tool for discovering the fields.Worksheets("sheet2").cells(2. methods and events applicable to Excel objects.value µ to display the contents of cell 45 activecell. You can also look at help Excel object reference model. Just enter the code and press return.value=45 µ to set value 45 worksheets("sheet2").3).Close µ to close all workbooks workbooks. properties.xls³ µ to close the file workbooks("test.3). It is a centralized location for exploring all the classes and their constituent members.Close filenam:="d:\test. Immediate window it is used to test the code . Type workbook in search box and press find binoculars Then workbook related class is displayed along with its members.Add µ to open empty workbooks workbooks.Open filename:="d:\test.

. Ex. End with Arrays Form or Active-X controls Good Programming conventions ‡ Need to use better coding standards ‡ Use indentation (Spacing) ‡ Use comments proper human communication and maintainability µ or REM ‡ Use Variable names meaningful like yearlyInterst ‡ Insert proper debugging statements like test points in hardware board to check the signal or voltages. Until executes when condition is false For variable =1 to x Statements Next variable Exit do...Value = a 'MsgBox ("vaue of A " & a) ' coded for debugging purpose Loop 'end for do End Sub Other Programming Constructs IF <condition> then statement Elseif <condition2> statement Else statement Endif Case Statement While . Wend like do while Do . for With .Cells(rowi.Basic Hands on Start a sample Program VBA is close akin to Visual Basic programming language 'fill first column with 1 to 10 number from Row 1 column 1 Sub Ten() Dim a As Integer Dim rowi As Integer Dim coli As Integer a=0 rowi = 0 ' for row number coli = 1 ' for column number Do While a < 10 µ execute when condition is true a=a+1 µ whereas do until execute when condition is false rowi = rowi + 1 Sheet1. coli). Write a program for 2 multiplication table upto 100 .

call. &. It should not contain any special character like %. "Add Company Name to Footer") With ActiveSheet. date .RightHeader = "" .RightFooter = "&N" 'for printing Page number in right footer End With End Sub Constants Like a variable.Variables and Constants Variables Variables are the memory locations which are used to store values temporarily. Constants must be declared. Sub Add_Footerinput() Dim coname As Variant 'for accepting the company name in footer coname = InputBox("Name your Company?". loop.PageSetup .CenterHeader = "" . a constant is a temporary holding place for some information that is used in a procedure.LeftFooter = coname 'left footer .CenterHeader = "" . A variable name must begin with an alphabet letter or _ and should not exceed 255 characters. !. end. function. case.LeftHeader = "" .PageSetup .LeftFooter = coname 'left footer .LeftHeader = "" .RightFooter = "&N" 'for printing Page number in right footer End With End Sub . with. integer select. @ and should not VB Key words like sub .CenterFooter = "" .CenterFooter = "" . if. do etc.. #. However.RightHeader = "" . elseif. as the name implies a constant never changes. A declaration statement in a VBA macro is used to define the value of a constant. It must be unique within the same scope. Sub Add_Footerconst() Const coname = "Analytics Training Institute Hyderabad " 'for accepting the µcompany name in footer With ActiveSheet. A defined naming strategy has to be followed while naming a variable.

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.Reserved Keywords can not used for Variable names And (Bitwise) ByVal CDbl Date ElseIf Function Lib New Or (Condition) Select Sub vbTab And (Condition) Call CInt Dim End Get Long Next Private Set Then With As Case CLng Do EndIf GoTo Loop Not Public Single To While Boolean CBool Const Double Error If Me Nothing ReDim Static True Xor ByRef CByte CSng Each False Integer Mid Option REM Step Until Byte CDate CStr Else For Let Mod Or (Bitwise) Resume String vbCrLf You can declare Arrays also Enumeration variables are variables declared with an Enum type. For example: Enum SecurityLevel IllegalEntry = -1 SecurityLevel1 = 0 SecurityLevel2 = 1 End Enum .

e.g. and bitwise operations Option Explicit is equivalent to > Tools .: Public ans As double or Public ans! Private Temp As currency or Private temp@ Sub test() End sub You need to use various data conversion functions like Cbyte.: Static tot As long or static tot & Module level Variables A module level variable is available to all the procedures in the module. e. & for string concatenation . Default is variant type e. mod for reminder. Public is available even outside the module. They are declared using the Public or the Private keyword instead of Dim. tot as integer Static Variables Static variables are not reinitialized each time a procedure is invoked and therefore retains or preserves value even when a procedure ends. Dim <variableName> as datatype.: Dim sum As Integer or dim sum%. csng.cdbl.g.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. / for Decimal division. *. options -> Editor -> require variable declaration . A static variable is declared as given below. +. clng. Cint. This variable is only available to the code inside the procedure and can be declared using the Dim statements as given below.g. ccur You can use operations like =. ^ for exponentiation. \ for integer division . -.

They are especially useful for taking one or more pieces of data.´ & mynumber End Function Sub Examplefunctioncall() CallMe End Sub Property Procedures A property procedure is used to create and manipulate custom properties. Visual Basic provides three kind of property procedures-Property Let procedure that sets the value of a property.Procedures Sub Procedures A sub procedure can be placed in standard. . It is used to create read only properties for Forms. You can use Call procedurename(arglist) or procedurename(arglist) The syntax for a sub procedure is as follows: [Private | Public] [Static] Sub Procedurename [( arglist)] [ statements] End Sub Function Procedures Functions are like sub procedures. Then the functions returns a value that indicates the results of the tasks complete within the function. let us suppose request variable has string value ³ pl. Standard modules and Class modules. call me´ Function CallMe(request as string) As String Const mynumber=³9848912345´ CallMe = request & ³. called arguments and performing some tasks with them. Each time the procedure is called. Property Get procedure that returns the value of a property. the statements between Sub and End Sub are executed. and Property Set procedure that sets the references to an object. except they return a value to the calling procedure. class and form modules.

and the event name.. an underscore(_). dblclick Private Sub Form_Load() . .statement block End Sub General Procedures A general procedure is declared when several event procedures perform the same actions. The various events are click.Procedures Event Procedures An event procedure is a procedure block that contains the control's actual name. The following syntax represents the event procedure for a Form_Load event.. It is a good programming practice to write common statements in a separate procedure (general procedure) and then call them in the event procedure...

Double . Variant ± Stores any type of data and is the default Visual Basic data type.Store integer values in the range of 0 . Single . Numeric I.(+ 32.483.483. Long .4x1038) V.(+ 3. 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.Store integer values in the range of (. String ± Use to store alphanumeric values. A variable length string can store approximately 4 billion characters 3.2.store monetary values.468) .Store floating point value in the range of (-3.147.Data Types 1. Currency .4x10-38) . These are not stored as numeric values and cannot be used as such. Integer .767) III.147. Date ± Use to store date and time values.768) . Character $ % & ! # @ The function must return A string An integral value between -32768 and 32767 An integer of small or large scale dim finalrow& or dim I as long A decimal number with single precision A decimal number with double precision A monetary value . Boolean ± Boolean data types hold either a true or false value.255 II.468) IV.Store integer values in the range of (-32. In Visual Basic if we declare a variable without any data type by default the data type is assigned as default.Store large floating value which exceeding the single data type value VI. Byte . It supports 4 digits to the right of decimal point and 15 digits to the left 2.(+ 2. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true 5.

Select Range( Activecell .Referencing Range : Top-Left Bottom.Right Selection Range( ³A1:B5´ ).Select Shortcuts Range(³D5´) Range(³A1:D5´) Range(³A1:D5´.range(³a1´). ActiveCell ).xlsm´).´G6:I17´) Range(³MyRange´) [D5] [A1:D5] [A1:D5.value .Select Range( ³A1´ .worksheets(³sheet1´).Select Range( ³A1´ .workbooks(³evba.Offset (5.2) ).G6:I17] [MyRange] Full reference is Application. ´B5´ ). ActiveCell.

title ] ) memory_variable = MsgBox ( prompt [.title] ) Prompt ± String expressions displayed as the message in the dialog box. Code to display value of A A=1 Msgbox(³the value of A is ³ & A) . you can separate the lines using the vbrCrLf constant. If you omit title. If prompt consist of more than one line. Title ± String expression displayed in the title bar of the dialog box. Ex. the application name is placed in the title bar. and returns an integer indicating which button the user clicked. Syntax : MsgBox ( Prompt [.icons+buttons ] [. icons+ buttons] [. Icons + Buttons ± Numeric expression that is the sum of values specifying the number and type of buttons and icon to display.MessageBox Function Displays a message in a dialog box and wait for the user to click a button.

you can separate the lines using the vbCrLf constant Title ± String expression displayed in the title bar of the dialog box. Following example demonstrates the use of InputBox function ‡ Open a new project and save the Form as InputBox.vbp ‡ Design the application as shown below. InputBox Function Displays a prompt in a dialog box. x-position and y-position ± the position or the coordinate of the input box. and returns a String containing the contents of the text box. . waits for the user to input text or click a button. Default) a=a+1 MsgBox ("the value of A " & a) End Sub Following is an expanded InputBox Syntax : memory_variable = InputBox (prompt[. Sub inputval() µ To accept a value .title][. ³INavalue". which accept the message input by the users. add with 1 and display it Dim a As Integer a = InputBox("give the value of A ".default]) memory_variable is a variant data type but typically it is declared as string.Visual Basic Functions. 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. If prompt consists of more than one line. The arguments are explained as follows: Prompt ± String expression displayed as the message in the dialog box. If you omit the title.frm and save the Project as InputBox.

Sum(Worksheets(³Sheet2´).Range(³A7´))) With«.Range(Range(³A1´).Range(³A1´) Workbooks(³InvoiceData.Range(Worksheets(³Sheet2´). range(³A7´))) End With .xls´). Worksheets(³Sheet2´).Range(³A1´). End With With Worksheets(³Sheets2´) WorksheetFunction.Worksheets(³Sheet1´).Sum(Worksheets(³Sheet2´).Range(³A7´))) ± Wrong WorksheetFunction.Referencing Ranges with Other Sheets WorkSheets(³Sheet1´).Sum(Range(Range(³A1´).Range(³A1´) WorksheetFunction.

End(xlup).5)) ± useful to specify variables with parameters as in looping .Row For i=1 to Finalrow Cells(i.Font.Item(5.Bold = True Next i Cells Property in Range Property Range(Cells(1.Bold = True Next i FinalRow = Range (³A65536´).Row For i=1 to Finalrow Range(³A´ &i & ³:E´ &i).Item(5.5).Item(Row.´c´) or Cells.´A´).Resize(.Font.3) Cells property is especially useful to loop through rows and columns Ex: FinalRow = Range (³A65536´).Cells(5.1).Column) Cells.Cells Property to Select Range Cell Item Property Cells.End(xlup).

Resize(2) ---.Resize(Rowsize.3) Range(³B3´).8). 8).only Column Range(³B3´).Resize(.interior. Colorindex = 4 Sub try() Cells(1. Range(³B3´).End(xlUp).only Row Ex: Cells(i. 1).resize(1.2) --.1). Resize(11.Row .Interior.Resize Property to Change Size of Range Enables to change the size of range based off the location of active cell Syntax: Range. Columnsize) To create a range B3:D13.Resize(1.ColorIndex = 4 End Sub Column and Row Properties to select Range FinalRow = Range(³A65536´).

Offset Property to Refer to Range
Range.Offset (RowOffset, ColumnOffset) To affect cell F5 from cell A1, Range(³A1´).Offset(4,5) ------ The count starts at A1, but does not include A1 Range(³A1´).Offset(Colunmoffset:=1) or Range(³A1´).Offset(,1) Range(³A1´).Offset(Rowoffset:=1) or Range(³A1´).Offset(-1) Ex: Sub try() Cells(1, 1).Offset(1, 8).Interior.ColorIndex = 4 End Sub Sub try1() Set Rng = Range("B1:B16").Find(What:="0", Lookat:=xlWhole, LookIn:=xlValues) Rng.Offset(, 1).Value = "Low" End Sub

Cereals Dals Noodles Masala Biscuits

45 0 15 10 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 Set UnionRange = Union(Range(³A1´), Range(³B4´)) With UnionRange .Formula = ³=RAND()´ .Font.Bold = True End With

Exercise Day 1:
Procedure to find if a certain workbook is open Function BookOpen(Bk As String) As Boolean Dim T As Excel.Workbook Err.Clear On Error Resume Next Set T = Application.Workbooks(Bk) BookOpen = Not T Is Nothing Err.Clear On Error GoTo 0 End Function 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 Procedure to Find Sum of two numbers: Sub addition() Dim total As Integer total = Add(1, 10) MsgBox "The answer is : " & total End Sub Function Add(Number1, Number2) As Integer Add = Number1 + Number2 End Function

More Examples«
Sub Count() mycount = Selection.Rows.Count count columns MsgBox mycount End Sub µcount the rows and columns that are selected

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 Sub MyPosition() µ display the selected column and row numbers myRow = ActiveCell.Row myCol = ActiveCell.Column MsgBox myRow & "," & myCol End Sub

Len(Str) ± 5) Week = Left(TStr.Functions ± convert week number into date Function Myname() As String Myname = ThisWorkbook.4).1)+ 0 ConvertWeekDay = FirstMon + (Week -1) * 7 End Function .Name End Function Function MyFullName() As String MyFullName = ThisWorkbook.FullName End Function Convert Week number into Date Function ConvertWeekDay(Str As String) As Date Dim Week as Long Dim FirstMon As Date Dim TStr As String FirstMon = DateSerial(Right(Str.1. Instr(1.1) FirstMon = FirstMon ± FirstMon Mod 7 + 2 Tstr = Right(Str.´ ³.Tstr.

g..value = "Fail" End If Method 2 If < condition 1 > Then statements Else If < condition 2 > Then statements Else If < condition 3 > Then statements Else Statements End If End If EndIf .Conditional Statements ..: If A3>75 Then Range(³B3´).Else selection structure Syntax of the If..Else selection structure Method 1 If < condition 1 > Then statements ElseIf < condition 2 > Then statements ElseIf < condition 3 > Then statements Else Statements End If If...Then selection If <condition> Then statement End If e...Then.Then selection structure Syntax of the If.Then..IF If..g..: If A3>50 Then Range(³B3´)..value = "Pass" Else Range(³B3´).Else selection If <condition > Then statements Else statements End If e...value = "A" End If Nested If.Then....

Case Statement Select.Case selection structure Syntax of the Select....Case selection structure Select Case Index Case 0 Statements Case 1 Statements End Select Example: Function testcase(x As Integer) Select Case x Case 1 testcase = "1st entry" Case 2 testcase = "2nd entry" Case 3 testcase = "3rd entry" Case 4 testcase = "4th entry" Case Else testcase = "invalid entry" End Select End Function ..

Loop is used to execute statements until a certain condition is met. Dim number As Integer number = 1 Do While number <= 100 Cells(number..Wend counts from 1 to 100 Dim number As Integer number = 1 While number <=100 Cells(number...Do while & While Wend Do While. When it gets to the Loop it goes back to the Do and tests condition again.....Wend statement behaves like the Do While.1) = ³Company name´ number = number + 1 Loop A variable number is initialized to 1 and then the Do While Loop starts..Loop statement. If condition is False on the first pass. the condition is tested.. The following While. Loop Statement The Do While. First.1) = ³xlMacros´ number = number + 1 Wend .. the statements are never executed While. if condition is True.. Wend Statement A While. then the statements are executed.. The following Do Loop counts from 1 to 100.

. ..Loop While statement first executes the statements and then test the condition after each execution. The following program block illustrates the structure: Dim number As Long number = 0 Do Cells(number. the program again executes the statements between Do and Loop While else exits the Loop.Loop While Statement The Do..1) = ³Advanced Excel´ number = number + 1 Loop While number < 201 The programs executes the statements between Do and Loop While structure in any case.. If so.Do Loop while Do. Then it determines whether the counter is less than 201.

. An example for Do Until..Loop are executed repeatedly as long as the loop-continuation test evaluates to False.. Loop structure tests a condition for falsity...1) = ³Successfully executed´ Loop Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.Loop Statement Unlike the Do While. ... Dim number As Long number=0 Do Until number > 10 number = number + 1 Cells(number. the Do Until.Loop and While..Do until Do Until. Statements in the body of a Do Until.Wend repetition structures....Loop statement..

.. 3.Next Loop The For.. For..etc ...2) = x Next The following loop counts numbers as 1. 7.. the following loop can be used For x = 1 To 50 Step 2 Cells(x.2) = x Next In order to count the numbers from 1 to 50 in steps of 2. 5.Next repetition structure handles all the details of counter-controlled repetition.Next Loop is another way to make loops in Visual Basic.For Next « The For. The following loop counts the numbers from 1 to 100: Dim x As Integer For x = 1 To 50 Cells(x.

Following example is a For. .Next repetition structure which is with the If condition used..3) ..3) = number End If Next In the output instead of number 4 you will get the "This is number 4". Dim number As Integer For number = 1 To 10 If number = 4 Then Cells(number.value= "This is number 4" Else Cells(number.

.2) = x x=x+1 If x = 5 Then Cells(x.3) = "The program is exited at x=5" Exit Do End If Loop . Dim x As Integer For x = 1 To 10 Cells(x. Dim x As Integer Do While x < 10 Cells(x.Next loop condition can be terminated by an Exit For statement. The Exit For statement is executed and it terminates the For.2) = x If x = 5 Then Cells(x. The Following statement block containing Do.Exit Loops A For...Next loop.... Consider the following statement block.1) = "The program exited at x=5" Exit For End If Next x The preceding code increments the value of x by 1 until it reaches the condition x = 5.While loop is terminated using Exit Do statement.

Height = 230 ..Size = 14 .Font. With Worksheets(³Sheet1´).Range(³A10:A20´) .With«.. The concept can be clearly understood with following example.Text = "Hello World" End With . End With When properties are set for objects or methods are called.End With statement.Font. It is easier to read the code by implementing the With..ForeColor = vbRed .End With statement.Bold = True . The code is executed more quickly and efficiently as the object is evaluated only once.. a lot of coding is included that acts on the same object. Multiple properties can be set and multiple methods can be called by using the With.

Examples function sales commission Function Comm(Sales_V As Variant) as Variant If Sales_V <500 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. 1500.12 Elseif Sales_V>=5000 Then /¶Subject to certain changes in Form1 statement¶/ Comm=Sales_V*0.Print studentName(num) Else End End If Next End Sub . "".03 Elseif Sales_V>=500 and Sales_V<1000 Then Comm=Sales_V*0. 4500) If studentName(num) <> "" Then Form1.15 End If Private Sub addName() End Function Dim studentName(10) As String Dim num As Integer For num = 1 To 10 studentName(num) = InputBox("Enter the student name". "Enter Name".

resize(1.value = ³service revenue´ Cells(I.Examples try for loop Ex 1: Sub tryloop() For I = 1 to 10 cells(i.interior.8). Colorindex = 4 End if Next i .value = ³service revenue´ Cells(I. 1).8).value >0 then Cells(I.6).row For i=2 to FinalRow if cells(I.end(xlup).resize(1.8).1).8).value = I Next I End Sub For I = 2 to 10 if cells(I.interior.i). Colorindex = 4 End if Next i FinalRow = Cells(65536.1).6).value >0 then Cells(I.

5).1).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. FinalRow = Cells(65536.6).EntireRow.3).Example ± delete all rows where Column C has value s54 µDelete all rows where column C has value s54 FinalRow = Cells(65536.end(xlup). 1).end(xlup).1).6).value >0 then if Cells(I.row ProblemFound = False For I = 2 to FinalRow if Cells(I.row For I = FinalRow to Step -1 if Cells(I.value = ³s54´ then Cells(I.select ProblemFound = True Exit For End if End if Next i If ProblemFound then MsgBox ³There is a problem at row´ & I Exit Sub End if .value = 0 then Cells(I.

Arrays have upper and lower bounds and the elements have to lie within those bounds.Arrays An array is a consecutive group of memory locations that all have the same name and the same type. user-defined types and object variables. To refer to a particular location or element in the array. Each index number in an array is allocated individual memory space and therefore users must evade declaring arrays of larger size than required. we specify the array name and the array element position number. We can declare an array of any of the basic data types including variant. . The individual elements of an array are all of the same data type.

Module arrays are declared in the general declarations using keyword Dim or Private. Local arrays are declared in a procedure using Dim or Static.Array Declaration Declaring arrays Arrays occupy space in memory. Dynamic array : The size of the array can be changed at the run time. Arrays may be declared as Public (in a code module). Array must be declared explicitly with keyword "As". .size changes during the program execution. module or local. There are two types of arrays in Visual Basic namely: Fixed-size array : The size of array always remains the same-size doesn't change during the program execution. The programmer specifies the array type and the number of elements required by the array so that the compiler may reserve the appropriate amount of memory.

Declaring a fixed-array Dim numbers(5) As Integer In the above illustration. An example for this is given below. an array of 10 elements is declared but with indexes running from 1 to 6. and the number 6 included in the parentheses is the upper limit of the array. numbers is the name of the array. then the parentheses should include both the lower and upper limit along with the To keyword. Public numbers(5) As Integer . If we want to specify the lower limit. A public array can be declared using the keyword Public instead of Dim as shown below. Dim numbers (1 To 6 ) As Integer In the above statement. The above declaration creates an array with 6 elements. The upper limit should always be within the range of long data type. a Fixed-array is created. with index numbers running from 0 to 5.Fixed-sized Arrays When an upper bound is specified in the declaration.

The following statement declares a two-dimensional array 50 by 50 array within a procedure. To identify a particular table element. Dim AvgMarks ( 50. Visual Basic supports at least 60 array dimensions. Note that multidimensional arrays can have more than two dimensions. but most people will need to use more than two or three dimensional-arrays. A common use of multidimensional arrays is to represent tables of values consisting of information arranged in rows and columns. Tables or arrays that require two indexes to identify a particular element are called two dimensional arrays. An example for this is given here. 1 To 100) An example for three dimensional-array with defined lower limits is given below.Multidimensional Arrays Arrays can have multiple dimensions. 1 To 100. we must specify two indexes: The first (by convention) identifies the element's row and the second (by convention) identifies the element's column. Dim Details( 101 To 200. Dim Marks ( 101 To 200. 50) It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays. 1 To 100) .

ReDim dynArray ( x + 1 ) Each time on executing the ReDim statement. we have to use the Preserve keyword with the ReDim statement.g.Dynamic Arrays There will be a situation when the user may not know the exact size of the array at design time. This is shown in the example given below. Module dynamic arrays are declared using keyword Dim or Private. because they can be resized anytime to accommodate new data. e. x. But if we want to change the size of the array without losing the previous data. a dynamic array can be initially declared and can add elements when needed instead of declaring the size of the array at design time. This example allocates the number of elements in the array based on the value of the variable. Dynamic arrays are more flexible than fixed-arrays. Local dynamic arrays are declared with either Dim or Static.: Dim dynArray ( ) The actual number of elements can be allocated using a ReDim statement. ReDim Preserve dynArray ( 50 To 200) . the current data stored in the array is lost and the default value is set. module or local scope. Like fixed-sized arrays. Under such circumstances. dynamic arrays have either Public (in code modules).

Activex show the properties. Form controls can respond to single predefined events whereas Activex controls can respond to many events like mouse click.. 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 instance. 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 . . . methods can also be used to manipulate controls from code. it gives assign macro. double click etc. Once you right click form controls. all the captions of the command buttons such as +. MC. They can respond to events initiated by the user or set off by the system. In addition to properties and events. Form controls are old generation and Activex are new and rich in features and driven by properties. For instance. in the calculator program. such as their response to the user input. double click. 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. and aspects of their behavior. such as position. There are two types of controls 1) form controls 2) activex controls. size and colour. Object Browser will help you to explore objects. the move method can be used with some controls to change their location and size. a code could be written in a CommandButton control's click event procedure that would load a file or display a result.. key press on keyboard etc.Controls Creating and Using Controls A control is an object that can be drawn on a Form object to enable or enhance user interaction with an application. However.. MR are commonly found in an ordinary calculator. For example. 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. Controls have properties that define aspects their appearance. 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. if you get assign macro. it is form control otherwise it is activex control with properties. When you right click a control.

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. and click the command button. Data. which are not included in tab order. except for Menu. invisible or disabled controls also cannot receive the focus although a TabIndex value is given. turn off design mode. Image. 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. Timer. To run code. Every time a tab key is pressed. .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. When there are no more controls with higher TabIndex value. It stops highlighting design mode button. Setting the TabIndex property of controls is compulsory in development environment. Visual Basic assigns a tab order to control as we draw the controls on the Form. At run time. By default. Line and Shape controls. switch back to the worksheet.

a list of globally accessible members. properties. Methods.Object Browser Press F2 in Visual Basic Editor . that class appears in bold. If there is code written for a class. Methods Events Properties Enumeration objects . Any object with code will appear in bold . you will get the default member if one is available. The list always begins with <globals>. events. If you select a Class and do not specify a member. ‡ Members list Displays the elements of the class selected in the Classes pane by group and then alphabetically within each group. You can change the order of this list with the Group Members command on the Object Browser shortcut menu. There are Classes ‡ Displays all of the available classes in the library or project selected in the Project/Libraries box. The default member is identified by an asterisk (*) or by the default icon specific to the member. or constants that have code written for them appear bold.

set the ScrollBars property ‡ Scroll bars will always appear on the TextBox when it's MultiLine property is set to True and its ScrollBars property is set to anything except None(0) ‡ If you set the MultilIne property to True.Value = "I am great" Then MsgBox "I am great is the message" End If End Sub . or assigned to the control using code at run time. SelText ± Returns or sets the string containing the currently selected text. The test is left-justified by default. If no text is selected.Value = "" Then MsgBox "it is blank" End If If TextBox1. you can set the alignment using the Alignment property. Default event is change() and default property is value.Text Box Text Box Property of Controls A TextBox control is an edit field or edit control. the text can be selected using three properties: SelLength ± Returns or sets the number of characters selected. set the MultiLine property to True ‡ To customize the scroll bar combination on a TextBox. Private Sub TextBox1_Change() If TextBox1. If the MultiLine property is et to False. SelStart indicates the position of the inserted point. Setting properties to a TextBox ‡ Text can be entered into the text box by assigning the necessary string to the text property of the control ‡ If the user needs to display multiple lines of text in a TextBox. entered by the user. SelStart ± Returns or sets the starting point of selected text. When no text is selected. SelText consists of a zerolength string. displays information entered at design time. then setting the Alignment property has no effect ‡ In order to work with the part of a text in a text box.

That doesn't have its own Caption property ‡ The Autosize and WordWrap properties should be set if the user wants the Label properly display variable-length lines varying numbers of lines Using a CommandButton We can begin. Properties Using a Label Its a graphical control user can use to display uneditable text...... select a colour in the BackColor property ‡ To set the text colour set the Forecolor property ‡ Font for the CommandButton control can be selected using the Font property ‡ To enable or disable the buttons set the Enabled property to True or False ‡ To make visible or invisible the buttons at run time. interrupt or end a process using the CommandButton control Properties of a CommandButton control ‡ To display text on a CommandButton control.... Properties of a Label Control ‡ We can write code that changes the caption property displayed by a Label control in response to events at run time. double click the button at design time. which adds a subroutine like the one given below Private Sub Command1_Click( ) ....Label . set the Visible property to True or False ‡ Tooltips can be added to a button by setting a text to the Controltip property of the CommandButton ‡ A button click event is handled whenever a command button is clicked. To add a click event handler. End Sub ..... set its caption property ‡ An event can be activated by clicking on the CommandButton ‡ To set the background colour of the CommandButton. such as TextBox control.. We can also use a label to identify a control..

frm and save the project as Option. The click event of the optLuxuty displays the amount of 5000 in txtAmount. The code is to assign it to True Option1. 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.Option Button Using OptionButton Control OptionButon provides a set of choices from which a user can select only one button by Clicking it at run time Assigning the value of the OptionButton in to True. CommandButton and three OptionButton controls. The click event of the optWithMeal displays the amount of 3500 in txtAmount. TextBox. You can use the Visible property to make the option button visible to invisible.vbp The application responds to the following events The click event of the optWithoutMeal displays the amount of 2500 in txtAmount.Value = True Using the shortcut keys specified in the Caption of a Label You can disable or enable the option button by setting the Enabled property to True os False.Value = True Then MsgBox "I am Female³ End If End Sub . The following example contains a Label. Example Open a new Standard EXE project and the save the Form as Option. 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. The Application is run by pressing F5 or clicking on the Run icon in the tool bar.

If the number of items exceed the value that be displayed. The following Fig lists some of the common ComboBox properties and methods. . These scroll bars can be scrolled up and down or left to right through the list. scroll bars will automatically appear on the control.List Box and Combo Box ListBox and ComboBox controls present a set of choices that are displayed vertically in a column.

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.RemoveItem index The following code verifies that an item is selected in the list and then removes the selected item from the list. The code is typed in the Form_Load event Removing Items from a List The RemoveItem method is used to remove an item from a list.Run Time : The AddItem method is used to add items to a list at run time. Following is an example to add item to a combo box. The syntax for this is given below. Not giving the index is not a problem. Object. . The AddItem method uses the following syntax. Object.AddItemitem. because by default the index is assigned.

At run time . Clear the list of items and finally close the application. Open a new Standard EXE project is opened an named the Form as Listbox. Example This example is to Add . . Remove. Using the ComboBox A ComboBox combines the features of a TextBox and a ListBox. The user could click the down arrow to view the list. the control looks like the Dropdown combo box.vbp Design the application as shown below. A simple combo box displays the contents of its list all the time. The user can either select a value from the list or type a value in the edit area.Using comboBox Sorting the List The Sorted property is set to True to enable a list to appear in alphanumeric order and False to display the list items in the order which they are added to the list. A scroll bar is displayed beside the list if there are too many items to be displayed in the list box area. The user can select an item from the list or type an item in the edit box portion of the combo box. The user can only select an item and cannot type anything in the edit area. Anyway this area displays the selected item. The list portion stays hidden until the user clicks the down-arrow button to drop down the list portion. The Dropdown Combo box first appears as only an edit area with a down arrow button at the right. The Dropdown list combo box turns the combo box into a Dropdown list box. This enables the user to select either by typing text into the ComboBox or by selecting an item from the list. The difference between Dropdown combo & Dropdown list combo is that the edit area in the Dropdown list combo is disabled. There are three types of ComboBox styles that are represented as shown below.frm and save the project as Listbox. Dropdown Combo (style 0) Simple Combo (style 1) Dropdown List (style 2) The Simple Combo box displays an edit area with an attached list box always visible immediately below the edit area.

The number of entered values will is increased according to the number of items added to the listbox.The following event procedures are entered for the TextBox and CommandButton controls. Then the text box is cleared and the focus is got to the text box. The click event of the Add button adds the text to the list box that was typed in the Text box. .

Command Buttons Remove button removes the selected item from the list as soon as you pressed the Remove button. The code for the clear button clears the listbox when you press it. And the number of items shown in the label becomes 0. . The number of items is decreased in the listbox and the value is displayed in the label.

‡ Design the application as shown below.vbp ‡ When the thumb's position of the ScrollBar is changed the value has to displayed in the TextBox. The Min and Max property represents the minimum and maximum value. which enables the user to select a value by positioning it at the desired location. that may be any integer between minimum and maximum values assigned. .frm and name the project as ScrollBar. It represents a set of values. Following example illustrates the ScrollBar control ‡ Open a new Standard EXE project and name the form as ScrollBar. The value property of the ScrollBar represents its current value.Using ScrollBar Control The ScrollBar is a commonly used control.

. We can see the value changes as soon as you move the thumb's position of the vertical scroll bar. Save the project and run the application by pressing F5 or clicking the Run icon in the ToolBar.The following codes are entered in the vsb1_Change( ) and cmdExit_Click( ) procedures.

you need to declare it as public.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. Static retains its value when it reenters sub. 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 value when it reenters this sub in for loop of othersub() procedure End Sub . If you want to use the value of variable in other sub or function. 50) fn = mul(pv. it retains its computed value MsgBox ("fnvalue " & fn & " pv value" & pv) fn = fn + 10 'as fn is static . Call fnval Next pv End Sub Function mul(pv. 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. 100) Call fnval For pv = 1 To 10 'when global variable value is change it is changed in all references wherever it is referred.

Creating Control Arrays at Design Time: There are three ways to create a control array at design time: ‡ Assigning the same name in the Name property for more than one control ‡ Copying an existing control and then pasting it to the Form. Adding controls with control arrays uses fewer resources than adding multiple control of same type at design time.Control Arrays A control array is a group of controls that share the same name type and the same event procedures. ‡ Setting the Index property to a value that is not null .

most of the property settings are copied from the lowest existing element in the array. Index % is the value of the index in the array. When a new element of a control array is loaded. Following example illustrates the use of the control array. ‡ Open a Standard EXE project and save the Form as Calculator. The control array to be added must be an element of the existing array created at design time with an index value of 0.vbp ‡ Design the form as shown below .frm and save the Project as Calculater.Adding a Control Array at Run Time Control arrays can be created at run time using the statements Load object (Index %) Unload object (Index %) Where object is the name of the control to add or delete from the control array.

The following variables are declared inside the general declaration The following code is entered in the cmd_Click( ) (Control Array) event procedure The following code is entered in the cmdAC_Click ( ) event procedure .

. cmdMultiply.Examples The below code is entered in the cmdNeg_Click( ) procedure The following code is entered in the click events of the cmdPlus. cmdMinus. cmdDevide controls respectively.

On clicking digits of user's choice and an operator button. . the output appears.To print the result on the text box. Save and run the project. the following code is entered in the cmdEqual_Click ( ) event procedure.

except that a list of choices can be made using check boxes where you cannot choose more than one selection using an OptionButton.Using a CheckBox control The CheckBox control is similar to the option button. By ticking the CheckBox the value is set to True.vbp ‡ Design the Form as shown below and type the code in module1 .frm and save the Project as CheckBox. The following example illustrates the use of CheckBox ‡ Open a new Project and save the Form as CheckBox.

.Using Userforms When you want to get lot of information.value=true Sub ckbx() UserForm1. insert ->Userform Add controls to user form . double click etc. use view->toolbox to see the controls User properties window to change the properties for controls like caption.Hide Unload userform1 End Sub . In VBE Editor. if controls are not visible . name etc. use F4 Write event handler procedures for the controls like click .checkbox1. shift +F7 to see the control Wirite the procedure to display this user form like the following You can refer the userform objects like userform1.. then userforms are better tool.Show UserForm1. use F7 to view the code .

FontUnderline = False End If End Sub Private Sub optblue_Click() TxtDisplay.FontBold = True Else TxtDisplay.ForeColor = vbBlue End Sub Private Sub optgreen_Click() TxtDisplay.ForeColor = vbRed End Sub Private Sub TxtDisplay_Change() End Sub Run the program by pressing F5.FontBold = False End If End Sub Private Sub ChkItalic_Click() If ChkItalic.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.FontItalic = False End If End Sub Private Sub ChkUnderline_Click() If ChkUnderline. .Value = True Then TxtDisplay.FontUnderline = True Else TxtDisplay.Value = True Then TxtDisplay.Value = True Then TxtDisplay. Check the program by clicking on OptionButtons and CheckBoxes.FontItalic = True Else TxtDisplay.ForeColor = vbGreen End Sub Private Sub OptRed_Click() TxtDisplay.

Following is an expanded InputBox Syntax : memory_variable = InputBox (prompt[.Visual Basic Functions. waits for the user to input text or click a button. x-position and y-position ± the position or the coordinate of the input box.vbp ‡ Design the application as shown below.title][. InputBox Function Displays a prompt in a dialog box. you can separate the lines using the vbCrLf constant Title ± String expression displayed in the title bar of the dialog box. If prompt consists of more than one line.frm and save the Project as InputBox. The arguments are explained as follows: Prompt ± String expression displayed as the message in the dialog box. . 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. and returns a String containing the contents of the text box. Following example demonstrates the use of InputBox function ‡ Open a new project and save the Form as InputBox. If you omit the title.default]) memory_variable is a variant data type but typically it is declared as string. which accept the message input by the users.

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". As soon as you click OK the output is shown as shown below . 0) If ans = "" Then 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.Caption = "No message" Else lbl2.

Ex. and returns an integer indicating which button the user clicked.MessageBox Function Displays a message in a dialog box and wait for the user to click a button. icons+ buttons] [.title ] ) memory_variable = MsgBox ( prompt [. Title ± String expression displayed in the title bar of the dialog box. If you omit title. Icons + Buttons ± Numeric expression that is the sum of values specifying the number and type of buttons and icon to display.icons+buttons ] [. Code to display value of A A=1 Msgbox(³the value of A is ³ & A) .title] ) Prompt ± String expressions displayed as the message in the dialog box. the application name is placed in the title bar. Syntax : MsgBox ( Prompt [. If prompt consist of more than one line. you can separate the lines using the vbrCrLf constant.

Text txtName. vbExclamation + vbYesNo.SetFocus cmdAdd.ListIndex If remove < 0 Then MsgBox "No names is selected". vbInformation.AddItem txtName.Enabled = True End If End Sub Following code has to be entered in the cmdAdd_Click ( ) event Private Sub cmdAdd_Click() answer = MsgBox("Do you want to add this name to the list box?". "Error" Else .Text = "" txtName.Text) > 0 Then cmdAdd. "Add Confirm") If answer = vbYes Then lstName.Enabled = False End If End Sub Following code is entered in the cmdDelete_Click ( ) event Private Sub cmdDelete_Click() Dim remove As Integer remove = lstName.Message Box code Following code is entered in the txtName_Change ( ) event Private Sub txtName_Change() If Len(txtName.

"Delete Confirm" 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?". vbInformation._ vbCritical + vbYesNo.answer = MsgBox("Are you sure you want to delete " & vbCrLf & "the selected name?". vbInformation. "Confirm" End If End Sub Save and run the application. vbExclamation + vbYesNo. You can notice the different type of message box types are used to perform an action . "Confirm") If answer = vbYes Then End Else MsgBox "Action canceled". "Warning") If answer = vbYes Then If remove >= 0 Then lstName.SetFocus MsgBox "Selected name was deleted".RemoveItem remove txtName.

. if these functions are not able to meet your requirement.User defined Functions All the Excel functions are available in Fx (insert Function) . of years invested =Yearly_Rate(A1. enter the following code. of years to invest in A3 =5 . 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.A2.4 after subtracting 50000/In Module1 . N As Double) As Double Yearly_Rate = PV * (1 + R) ^ N 'Performs computation End Function UDF for CentrigradetoFahrenheit . interest rate in A2 =8/100. no. You get 73466. you You can create your own User defined functions .000.A3) store FD amount in A1 50.4 and only interest is 23466.000/. Function Yearly_Rate(PV As Double.32) * 5 / 9 End If End Function . R As Double. They reduce the complexity of worksheet and could be used by all the people in the organization thus increasing the productivity due to reuse.rs for 8% interst how much will it be after 5 years ? The formula is Interest + principle = FD Amount (1+interst rate / 100)^ no. if conversion flag (cflag=1) it will convert from centigrade to Fahrenheit otherwise Fto C Function convertCentigrade_Fahrenheit(num As Double. cflag As Integer) As Double If cflag = 1 Then ' centrigrade to fahrenheit convertCentigrade_Fahrenheit = num * 9 / 5 + 32 Else ' fahrenheit to centigrade convertCentigrade_Fahrenheit = (num .

User defined Functions UDF s will work only for a cell and they will not work for changing the structure of worksheet. 2) but not all functions could be used . . You need to use VBA equivalent functions or mathematical operators to carry out same calculation.vlookup(Product. table. They cannot be used for copying or moving the cells 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.

Examples include: when a variable takes on an unexpected value (divide by zero). Visual Basic detects these errors as they occur and even provides help in correcting them. when a drive door is left open. the program will usually run. 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. and procedures . With logic errors.Error-Handling and Debugging No matter how hard we try. objects. or when a file is not found. You cannot run a Visual Basic program until all syntax errors have been corrected ± Run-time errors are usually beyond your program's control. The Visual Basic debugger is an aid in detecting logic errors ‡ Some ways to minimize errors: ± Design your application carefully. Visual Basic allows you to trap such errors and make attempts to correct them ± Logic errors are the most difficult to find. errors do creep into our programs. but will produce incorrect or unexpected results. 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.

If an error occurs and is not trapped. Visual Basic recognizes an error has occurred and enables you to trap it and take corrective action. Yes. Your normal procedure code follows this statement. . 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. your program will usually end in a rather unceremonious manner ‡ Error trapping is enabled with the On Error statement: On Error GoTo errlabel. this uses the dreaded GoTo statement! Any time a run-time error occurs following this line. following the HandleErrors statement label. the On Error statement is executed to enable error trapping.] On Error GoTo HandleErrors [Procedure code] Exit Sub HandleErrors: Error handling code] End Sub Once you have set up the variable declarations. and any other procedure preliminaries. That is.. The error handling code goes at the end of the procedure. This is the code that is executed if an error is encountered anywhere in the Sub procedure. constant definitions.Run-Time Error Trapping and Handling ‡ Run-time errors are trappable. Sub SubExample() [Declare variables. program control is transferred to the line labeled errlabel.. Note you must exit (with Exit Sub) from the code before reaching the HandleErrors line to avoid inadvertent execution of the error handling code. .

That is. Consult on-line help for Visual Basic run-time error numbers and their descriptions ‡ Once an error has been trapped and some action taken.Number). all variables in that procedure are available for possible corrective action. in its Number property (Err. if the error has not been corrected (via code or by the user). control is returned to the line where the error occurred. When executing the error handling portion of the code and the end of the procedure is encountered before a Resume. control must be returned to your application. Likewise.consult on-line help for further information. The Err object returns. This is done in the error handling code ‡ Visual Basic offers help in identifying run-time errors. if a Resume is encountered outside of the error handling portion of the code. the number associated with the current error condition.) The Error() function takes this error number as its argument and returns a string description of the error.‡ Since the error handling code is in the same procedure where an error occurs. There are three options: ±Resume Lets you retry the operation that caused the error. an error occurs . an error occurs. we would like to know what the error is and attempt to fix it. that is done with the following statement: On Error GoTo 0 ‡ Once a run-time error occurs. 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. (The Err function has other useful properties that we won¶t cover here . That control is returned via the Resume statement. you want to turn off error trapping. If at some time in your procedure. This could be dangerous in that.

. this routine is only executed when an error occurs.) If Retry is selected. using the Visual Basic provided error description [Error(Err. uses a critical icon along with the Abort. if a 'divide by zero' is found. vbCritical + vbAbortRetryIgnore. (This is done using a Resume to the line labeled ExitLine. Retry. you or the user would have to change something here to correct the condition causing the error). or Ignore.Number)) Case vbAbort Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub Let¶s look at what goes on here. Retry. This message box returns a response indicating which button was selected by the user.Number] as the title.Number)] as the message. If Ignore is selected.General Error Handling Procedure ‡ Development of an adequate error handling procedure is application dependent. and allows the user to Abort. First. the offending program line is retried (in a real application. and Ignore buttons. program operation continues with the line following the error causing line. A message box is displayed. and uses the error number [Err. we simply exit the procedure. "Error Number" + Str(Err.Number). 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. provides a description of the error. If Abort is selected. The generic code (begins with label HandleErrors) is: HandleErrors: Select Case MsgBox(Error(Err. This framework is a good starting point for designing custom error handling for your applications. Recall all error trapping must be terminated with a Resume statement of some kind. 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.

vbCritical + vbAbortRetryIgnore.. at the beginning of your procedure. [Declare variables.. if your procedure is the SubExample seen earlier. "Error Number" + Str(Err.Number). Place an Exit Sub line immediately preceding the HandleErrors labeled line. you need to do three things: Copy and paste the error handling code into the end of your procedure. Exit Sub HandleErrors: Select Case MsgBox(Error(Err. On Error GoTo HandleErrors . .Number)) Case vbAbort Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub End Sub Again.To use this generic code in an existing procedure. [Procedure code] .] . this is a very basic error-handling routine. . For example. . Specifically. On Error GoTo HandleErrors. you need code to clear error conditions before using the Retry option. Place the line. the modified code will look like this: Sub SubExample() . You must determine its utility in your applications and make any modifications necessary. .

1-Fixed Single Caption .[Blank] The form should look something like this: Enter this code in module 1 Sub ergen() frmerror. 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.Show frmerror. not just ones generated with the Raise method).Hide End Sub .True Name . use: Err.Raise Number ‡ We can use this function to completely test the operation of any error handler we write. to really get fancy. creating run-time errors is sometimes difficult and perhaps dangerous. To cause an error with value Number.Generate Error Default . 2. But.cmdGenError Text1: Name . Start a new project. Once you've written an error handling routine. though! And. use the method Clear: Err. you can also use Raise to generate your own µapplication-defined¶ errors. you need to test it to make sure it works properly.Error Generator Name frmError Command1: Caption . There are errors specific to your application that you want to trap ‡ To clear an error condition (any error.txtError Text . Set the properties of the form and each control: Form1: BorderStyle . Add a text box and a command button. Don¶t forget to remove the Raise statement once testing is completed.‡ One last thing.Clear Example ± Simple Error Trapping 1.

Option Explicit Private Sub CmdGenError_Click() On Error GoTo HandleErrors Err.Print ("error vbretry") Case vbIgnore Debug. .Number)) Case vbAbort Debug.Print ("VBAbort") Resume ExitLine Case vbRetry Debug.Raise Val(txterror. vbCritical + vbAbortRetryIgnore. Attach this code to the cmdGenError_Click event.Text) Err.Clear Exit Sub HandleErrors: Select Case MsgBox(Error(Err. "Error Number" + Str(Err.3.Number). The generic error handler then displays a message box which you can respond to in one of three ways.Print ("error vbignore") End Select ExitLine: Exit Sub End Sub In this code. we simply generate an error using the number input in the text box.

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.Error codes and description 4. Error Number 6 9 11 13 16 20 52 53 55 61 70 92 Error Description Overflow Subscript out of range Division by zero Type mismatch Expression too complex Resume without error Bad file name or number File not found File already open Disk full Permission denied For loop not initialized . Save your application.

These are errors that don¶t prevent an application from running. ‡ The interface between your application and the debugging tools is via three different debug windows: the Immediate Window. Or. should select the debugging approach and tools you feel most comfortable with. You can enter break mode by setting breakpoints. Once in break mode. There are no prescribed processes that you can follow to eliminate all logic errors in your program.Debugging Visual Basic Programs ‡ We now consider the search for. and elimination of. pressing Ctrl+Break. 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. logic errors. not a science. 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 . These windows can be accessed from the View menu (the Immediate Window can be accessed by pressing Ctrl+G). Debugging a code is an art. The usual approach is to eliminate them as they are discovered. You. and the Watch Window. Visual Basic provides an excellent set of debugging tools to aid in this search. ‡ 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. as the program designer. or the program will go into break mode if it encounters an untrapped error or a Stop statement. the Locals Window. but cause incorrect or unexpected results.

The example simply has a form with a single command button. The code attached to this button¶s Click event is a simple loop that evaluates a function at several values. 2. Private Sub Command1_Click() Dim X As Integer. The button is used to execute some code. . we¶ll do this one as a group.Example ± Debugging 1. but it makes a good example for looking at debugger use. Unlike other examples. Y As Integer X=0 Do Y = Fcn(X) X=X+1 Loop While X <= 20 End Sub This code begins with an X value of 0 and computes the Y value using the general integer function Fcn. this code doesn¶t do much. It then increments X by 1 and repeats the Loop. especially without any output. It continues looping While X is less than or equal to 20. Set up the application and get ready to try debugging. We won¶t be real careful about proper naming conventions and such in this example. 3.1 * X ^ 2) End Function Admittedly. The function Fcn is computed using: Function Fcn(X As Integer) As Integer Fcn = CInt(0. It will be used to demonstrate use of the debugging tools.

Thank You .