Você está na página 1de 86

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

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, 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 With Selection.Font .Name=Tahoma Size=11 Strikethrough=False ??????? ????? End With Selection.Font.Bold=true End Sub Another Example Sub Exercise() ActiveCell.FormulaR1C1.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

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

Objects

Methods

Properties

Events

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 Workbook Class can contain customernumber, loyalty status etc.,

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(.)

Application

Application.belowobjects like Workbooks, worksheets,range,cells

Workbook

Application.Workbooks(Sales.xls)

Application.Workbooks(Sales.xls ).WorkSheets(Sheet1)

Worksheet

Add-ins

Chart

Pivot Table

Range

Application.Workbooks(Sales.xls).WorkS heets(Sheet1).Range(A1) Every object (ex. Cell ) has a property like value Every object has even method too like Cells(3,1).clearcontents

Cells
Workbooks(Sales.xls).WorkSheets(Sheet 1).cells(3,1).value to refer to row 3 and column A contents using value property

Properties: Properties are used to describe an object. Some properties are read-only, while others are read/write. These properties describe Excel objects. For example, an Excel workbook has a particular path on your hard drive or network where it is saved. That path is a property of the workbook. That path is read-only as it cannot be changed without saving the file to a different location. Properties are separated from objects by periods just as methods are. The following sentence will display the current path of the Training.xls file in an onscreen message box: Msgbox Workbooks(Training.xls).Path Activecell.columnwidth=20 to change the width property. workbooks(sales.xls).worksheets(Datainput).range(a4).value=10 Methods: A method is an action that can be performed on an object sometimes change the properties. Excel VBA objects are separated from their methods by a period. For example, 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.xls).Save, Range(A3).select , Range(A1:E6).copy , Activesheet.paste destination:=range(c5) parameter is given with := 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

Properties , Methods & Events for the objectsUse Object Browser-F2

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 workbooks.Add to open empty workbooks workbooks.Close to close all workbooks workbooks.Open filename:="d:\test.xls to open a excel file workbooks.Close filenam:="d:\test.xls to close the file workbooks("test.xls").Worksheets("sheet2").cells(2,3).value=45 to set value 45 worksheets("sheet2").activate ?cells(2,3).value to display the contents of cell 45 activecell.Value="this is active cells to push values in active cell

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.Cells(rowi, coli).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 .. Until executes when condition is false For variable =1 to x Statements Next variable Exit do, for With .. 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.

Ex. Write a program for 2 multiplication table upto 100

Variables and Constants


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

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. 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 e.g.: Dim sum As Integer or dim sum%, 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. A static variable is declared as given below. e.g.: Static tot As long or static tot & Module level Variables A module level variable is available to all the procedures in the module. They are declared using the Public or the Private keyword instead of Dim. Public is available even outside the module. e.g.: 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, 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

Option Explicit is equivalent to > Tools , options -> Editor -> require variable declaration

Procedures
Sub Procedures A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the statements between Sub and End Sub are executed. 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, except they return a value to the calling procedure. They are especially useful for taking one or more pieces of data, called arguments and performing some tasks with them. 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. call me Function CallMe(request as string) As String Const mynumber=9848912345 CallMe = request & , & mynumber End Function 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 Private Sub Form_Load() ....statement block End Sub

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.

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

Referencing
Range : Top-Left Bottom- Right Selection Range( A1:B5 ).Select Range( A1 , B5 ).Select Range( A1 , ActiveCell ).Select Range( Activecell , ActiveCell.Offset (5,2) ).Select

Shortcuts Range(D5) Range(A1:D5) Range(A1:D5,G6:I17) Range(MyRange) [D5] [A1:D5] [A1:D5,G6:I17] [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. Ex. Code to display value of A A=1 Msgbox(the value of A is & A)

Visual Basic Functions, InputBox Function


Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box. Sub inputval() 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

Following is an expanded InputBox

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. End With


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) Cells property is especially useful to loop through rows and columns Ex: FinalRow = Range (A65536).End(xlup).Row For i=1 to Finalrow Range(A &i & :E &i).Font.Bold = True Next i FinalRow = Range (A65536).End(xlup).Row For i=1 to Finalrow Cells(i,A).Resize(,5).Font.Bold = True Next i Cells Property in Range Property Range(Cells(1,1),Cells(5,5)) useful to specify variables with parameters as in looping

Resize Property to Change Size of Range


Enables to change the size of range based off the location of active cell Syntax: Range.Resize(Rowsize, Columnsize) To create a range B3:D13, Range(B3). Resize(11,3) Range(B3).Resize(,2) --- only Column Range(B3).Resize(2) ---- only Row Ex: Cells(i,1).resize(1,8).interior. Colorindex = 4 Sub try() Cells(1, 1).Resize(1, 8).Interior.ColorIndex = 4 End Sub

Column and Row Properties to select Range


FinalRow = Range(A65536).End(xlUp).Row

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

Functions convert week number into date


Function Myname() As String Myname = ThisWorkbook.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,4),1,1) FirstMon = FirstMon FirstMon Mod 7 + 2 Tstr = Right(Str, Len(Str) 5) Week = Left(TStr, Instr(1,Tstr, ,1)+ 0 ConvertWeekDay = FirstMon + (Week -1) * 7 End Function

Conditional Statements - IF
If...Then selection structure Syntax of the If...Then selection If <condition> Then statement End If e.g.: If A3>75 Then Range(B3).value = "A" End If Nested If...Then...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...Else selection structure Syntax of the If...Then...Else selection If <condition > Then statements Else statements End If e.g.: If A3>50 Then Range(B3).value = "Pass" Else Range(B3).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

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

Do while & While Wend


Do While... Loop Statement The Do While...Loop is used to execute statements until a certain condition is met. The following Do Loop counts from 1 to 100. Dim number As Integer number = 1 Do While number <= 100 Cells(number,1) = Company name number = number + 1 Loop 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 While... Wend Statement A While...Wend statement behaves like the Do While...Loop statement. The following While...Wend counts from 1 to 100 Dim number As Integer number = 1 While number <=100 Cells(number,1) = xlMacros number = number + 1 Wend

Do Loop while

Do...Loop While Statement The Do...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,1) = Advanced Excel number = number + 1 Loop While number < 201 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. An example for Do Until...Loop statement. Dim number As Long number=0 Do Until number > 10 number = number + 1 Cells(number,1) = Successfully executed Loop Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command button.

For Next
The For...Next Loop The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition structure handles all the details of counter-controlled repetition. The following loop counts the numbers from 1 to 100: 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 The following loop counts numbers as 1, 3, 5, 7..etc

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

Exit Loops
A For...Next loop condition can be terminated by an Exit For statement. Consider the following statement block. Dim x As Integer For x = 1 To 10 Cells(x,2) = x If x = 5 Then Cells(x,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. The Exit For statement is executed and it terminates the For...Next loop. The Following statement block containing Do...While loop is terminated using Exit Do statement. Dim x As Integer Do While x < 10 Cells(x,2) = x x=x+1 If x = 5 Then Cells(x,3) = "The program is exited at x=5" Exit Do End If Loop

With. End With

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

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 /Subject to certain changes in Form1 statement/ Comm=Sales_V*0.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", "", 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=2 to FinalRow 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

Example delete all rows where Column C has value s54


Delete all rows where column C has value s54 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. FinalRow = Cells(65536, 1).end(xlup).row ProblemFound = False For I = 2 to FinalRow if Cells(I,6).value >0 then if Cells(I,5).value = 0 then Cells(I,6).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

Arrays

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

Array Declaration

Declaring arrays Arrays occupy space in memory. 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. Arrays may be declared as Public (in a code module), module or local. 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 must be declared explicitly with keyword "As". 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. Dynamic array : The size of the array can be changed at the run time- size changes during the program execution.

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

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

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

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. Controls have properties that define aspects their appearance, such as position, size and colour, and aspects of their behavior, such as their response to the user input. They can respond to events initiated by the user or set off by the system. For instance, a code could be written in a CommandButton control's click event procedure that would load a file or display a result. 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 . There are Classes 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. 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, set the MultiLine property to True To customize the scroll bar combination on a TextBox, 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, you can set the alignment using the Alignment property. The test is left-justified by default. If the MultiLine property is et to False, then setting the Alignment property has no effect In order to work with the part of a text in a text box, the text can be selected using three properties: SelLength Returns or sets the number of characters selected. 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 zerolength string. Private Sub TextBox1_Change() If TextBox1.Value = "" Then MsgBox "it is blank" End If If TextBox1.Value = "I am great" Then MsgBox "I am great is the message" End If End Sub

Label , Properties
Using a Label Its a graphical control user can use to display uneditable text. 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. We can also use a label to identify a control, such as TextBox control, 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, interrupt or end a process using the CommandButton control Properties of a CommandButton control To display text on a CommandButton control, set its caption property An event can be activated by clicking on the CommandButton To set the background colour of the CommandButton, 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, 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, double click the button at design time, which adds a subroutine like the one given below Private Sub Command1_Click( ) .................. End Sub

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. The code is to assign it to True Option1.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. You can use the Visible property to make the option button visible to invisible. The following example contains a Label, TextBox, CommandButton and three OptionButton controls. 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

Removing Items from a List The RemoveItem method is used to remove an item from a list. The syntax for this is given below. Object.RemoveItem index The following code verifies that an item is selected in the list and then removes the selected item from the list.

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. Using the ComboBox A ComboBox combines the features of a TextBox and a ListBox. This enables the user to select either by typing text into the ComboBox or by selecting an item from the list. There are three types of ComboBox styles that are represented as shown below. 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. 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.

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. Setting the Index property to a value that is not null

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. Index % is the value of the index in the array. The control array to be added must be an element of the existing array created at design time with an index value of 0. When a new element of a control array is loaded, most of the property settings are copied from the lowest existing element in the array. Following example illustrates the use of the control array. Open a Standard EXE project and save the Form as Calculator.frm and save the Project as Calculater.vbp Design the form as shown below

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

Examples
The below code is entered in the cmdNeg_Click( ) 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 You can refer the userform objects like userform1.checkbox1.value=true

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 Private Sub optblue_Click() TxtDisplay.ForeColor = vbBlue End Sub Private Sub optgreen_Click() TxtDisplay.ForeColor = vbGreen End Sub Private Sub OptRed_Click() TxtDisplay.ForeColor = vbRed End Sub Private Sub TxtDisplay_Change() End Sub Run the program by pressing F5. Check the

program by clicking on OptionButtons and CheckBoxes.

Visual Basic Functions, InputBox Function


Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box.

Following is an expanded InputBox

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. Ex. Code to display value of A A=1 Msgbox(the value of A is & A)

Message Box code


Following code is entered in the txtName_Change ( ) event Private Sub txtName_Change() If Len(txtName.Text) > 0 Then cmdAdd.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?", vbExclamation + vbYesNo, "Add Confirm") If answer = vbYes Then lstName.AddItem txtName.Text txtName.Text = "" txtName.SetFocus cmdAdd.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.ListIndex If remove < 0 Then MsgBox "No names is selected", vbInformation, "Error" Else

answer = MsgBox("Are you sure you want to delete " & vbCrLf & "the selected name?",_ vbCritical + vbYesNo, "Warning") If answer = vbYes Then If remove >= 0 Then lstName.RemoveItem remove txtName.SetFocus MsgBox "Selected name was deleted", vbInformation, "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?", 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/In Module1 , enter the following code.. Function Yearly_Rate(PV As Double, R As Double, N As Double) As Double Yearly_Rate = PV * (1 + R) ^ N 'Performs computation End Function UDF for CentrigradetoFahrenheit , 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 - 32) * 5 / 9 End If End Function

User defined Functions


UDF s will work only for a cell and they will not work for changing the structure of worksheet. 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.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 Some ways to minimize 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() [Declare variables, ...] On Error GoTo HandleErrors [Procedure code] Exit Sub HandleErrors: Error handling code] 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 wont 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. The generic code (begins with label HandleErrors) is: 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 Lets 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. Dont 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

Example Simple Error Trapping


1. Start a new project. Add a text box and a command button. 2. Set the properties of the form and each control: Form1: BorderStyle - 1-Fixed Single Caption - Error Generator Name frmError Command1: Caption - Generate Error Default - True Name - cmdGenError Text1: Name - txtError Text - [Blank] The form should look something like this:

Enter this code in module 1 Sub ergen() frmerror.Show frmerror.Hide End Sub

3. Attach this code to the cmdGenError_Click event. Option Explicit Private Sub CmdGenError_Click() On Error GoTo HandleErrors Err.Raise Val(txterror.Text) Err.Clear Exit Sub HandleErrors: Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number)) Case vbAbort Debug.Print ("VBAbort") Resume ExitLine Case vbRetry Debug.Print ("error vbretry") Case vbIgnore Debug.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. 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. 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

Debugging Visual Basic Programs


We now consider the search for, and elimination of, logic errors. These are errors that dont 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 well 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, well 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 wont be real careful about proper naming conventions and such in this example.

3. The code attached to this buttons Click event is a simple loop that evaluates a function at several values. Private Sub Command1_Click() Dim X As Integer, 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. It then increments X by 1 and repeats the Loop. It continues looping While X is less than or equal to 20. The function Fcn is computed using: Function Fcn(X As Integer) As Integer Fcn = CInt(0.1 * X ^ 2) End Function Admittedly, this code doesnt do much, especially without any output, but it makes a good example for looking at debugger use. Set up the application and get ready to try debugging.

Thank You

Você também pode gostar