This action might not be possible to undo. Are you sure you want to continue?
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
± 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
± 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
Writing good code Code indentation & Comments Use Immediate window to experiment any code . 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. class module contain you own objects.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. You can insert/remove modules like standard module.
Name=³Tahoma´ Size=11 Strikethrough=False ??????? ????? End With Selection.Starting with Macros .Bold=true End Sub Another Example Sub Exercise() ActiveCell.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 .Select .Font.Observations Range(³A1:D10´).Font .FormulaR1C1.selection of cells With Selection.
xlsx´).worksheet(³Sheet1´).value . A procedure is a set of VBA statements that performs a specific task or calculates a specific result. and properties and Events. Objects are instances of Class.Range(³A1´).workbooks(³exampleExcel. VBA Procedure Objects Methods Properties Events Interest = Application. methods. Chair is class Godrej Model chair ME100 an object & an instance of class chair . objects. Ex. These VBA statements are grouped in larger blocks called procedures. The first step to learning how to create procedures is to learn about the building blocks.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.
methods like clearcontents The Fields in the object capture their state. VBA modules..WorkSheets(³Sheet1´). a workbook is a collection of all the objects it contains like ex.xls´). sheets. Worksheet Objects in Excel Range Cell Collections: Many objects belong to collections related in hierarchical or tree structure. cells. ranges. For example. Objects have properties like .. which means the statements you create in VBA act on specific objects rather than begin general commands. Customer Workbook Class can contain customernumber.value. loyalty status 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. etc. Excel is made of objects that you can manipulate through the VBA statements. charts.Objects and Collections Objects: VBA is an object-oriented programming language.Range(³A1´) .
WorkSheets(³Sheet 1´).1).Range(³A1´) Every object (ex.xls´) Application.1).WorkS heets(³Sheet1´).value to refer to row 3 and column A contents using value property .cells(3. Each hierarchy is separated by dot(.Workbooks(³Sales.) Application Application.xls´). Objects are arranged in Hierarchy and they act as containers.WorkSheets(³Sheet1´) Worksheet Add-ins Chart Pivot Table Range Application.Objects in Excel are Collections ± Top one is Application. worksheets.belowobjects like Workbooks.Workbooks(³Sales.Workbooks(³Sales.cells Workbook Application. Cell ) has a property like value Every object has even method too like Cells(3.range.xls´).clearcontents Cells Workbooks(³Sales.xls ´).
kick.sheetactivate event occurs when any sheet is activated.Save. Elevation:=High wordart.xls´). Activesheet. For example. The following sentence will display the current path of the Training.Eat Balls(³soccer´). Food. That path is a property of the workbook.Top:=20. These properties describe Excel objects.Drink.xls´).xls file in an onscreen message box: Msgbox Workbooks(³Training. For example.Add Left:=10. Range(³A1:E6´). Methods & Events for the objects±Use Object Browser-F2 What is Variable ? . focus etc. Water.property ± ActiveCell.Path Activecell.. A mouse click on a command button then you need to write appropriate code to respond click.width:=100.kick Direction:=Left. Force:=Hard.Event .(Color the Cell Yellow) Object.range(³a4). Activex controls can respond to events. double click. while others are read/write. Some properties are read-only. That path is read-only as it cannot be changed without saving the file to a different location.worksheets(³Datainput´).columnwidth=20 to change the width property.Add (Before:=Worksheets(1)) Object.open Properties .kick Balls(³soccer´). Range(³A3´).Properties: Properties are used to describe an object. Excel VBA objects are separated from their methods by a period.Method Ball.ColorIndex = 30 --.read. 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. Properties are separated from objects by periods just as methods are.xls´). Book.value=10 Methods: A method is an action that can be performed on an object sometimes change the properties. All form.select .paste destination:=range(³c5´) parameter is given with := Events: Objects respond to Events. Book. an Excel workbook has a particular path on your hard drive or network where it is saved.Workbook.write. Height:=200 Worksheets. workbooks(³sales.copy .Interior.Add Before:=Worksheets(1) Set MyWorksheet = Worksheets. Event is an action initiated by other users or procedures like Application. Examples: Object.
Type workbook in search box and press find binoculars Then workbook related class is displayed along with its members.xls").xls³ µ to close the file workbooks("test.Close µ to close all workbooks workbooks. properties.value=45 µ to set value 45 worksheets("sheet2"). It is a centralized location for exploring all the classes and their constituent members.Add µ to open empty workbooks workbooks.Close filenam:="d:\test. You can also look at help Excel object reference model. That VB statement is executed some samples are workbooks. methods and events applicable to Excel objects.Open filename:="d:\test.Worksheets("sheet2"). Immediate window it is used to test the code .3). Just enter the code and press return.activate ?cells(2.cells(2.value µ to display the contents of cell 45 activecell.Use Object Browser-F2 Object Browser is valuable tool for discovering the fields.Value="this is active cells³ µ to push values in active cell .3).xls³ µ to open a excel file workbooks.
. coli). Wend like do while Do . Write a program for 2 multiplication table upto 100 .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 . 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...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. for With .
CenterHeader = "" . #..RightFooter = "&N" 'for printing Page number in right footer End With End Sub . end.PageSetup . A variable name must begin with an alphabet letter or _ and should not exceed 255 characters.CenterFooter = "" . Constants must be declared. elseif. if. do etc. with.LeftFooter = coname 'left footer . "Add Company Name to Footer") With ActiveSheet. case.RightHeader = "" . as the name implies a constant never changes.LeftFooter = coname 'left footer .RightHeader = "" . !. loop. Sub Add_Footerinput() Dim coname As Variant 'for accepting the company name in footer coname = InputBox("Name your Company?".Variables and Constants Variables Variables are the memory locations which are used to store values temporarily. @ and should not VB Key words like sub .LeftHeader = "" . Sub Add_Footerconst() Const coname = "Analytics Training Institute Hyderabad " 'for accepting the µcompany name in footer With ActiveSheet.LeftHeader = "" .CenterFooter = "" . call. It must be unique within the same scope.RightFooter = "&N" 'for printing Page number in right footer End With End Sub Constants Like a variable. However. A defined naming strategy has to be followed while naming a variable. &. a constant is a temporary holding place for some information that is used in a procedure. A declaration statement in a VBA macro is used to define the value of a constant. function. date .CenterHeader = "" . It should not contain any special character like %.PageSetup . integer select.
Both variables and parameters can be declared with an Enum type.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. 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 .
This variable is only available to the code inside the procedure and can be declared using the Dim statements as given below. / for Decimal division. 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. *.: 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.g. options -> Editor -> require variable declaration . ^ for exponentiation.: Dim sum As Integer or dim sum%. Public is available even outside the module. +. mod for reminder. and bitwise operations Option Explicit is equivalent to > Tools .cdbl. e. clng. ccur You can use operations like =.g. e. They are declared using the Public or the Private keyword instead of Dim. -. Cint.g. Default is variant type e. Dim <variableName> as datatype. \ for integer division .: Static tot As long or static tot & Module level Variables A module level variable is available to all the procedures in the module. A static variable is declared as given below. csng.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 string concatenation .
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. called arguments and performing some tasks with them. and Property Set procedure that sets the references to an object. Standard modules and Class modules.Procedures Sub Procedures A sub procedure can be placed in standard. let us suppose request variable has string value ³ pl. Then the functions returns a value that indicates the results of the tasks complete within the function. 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. Visual Basic provides three kind of property procedures-Property Let procedure that sets the value of a property. the statements between Sub and End Sub are executed. except they return a value to the calling procedure. . It is used to create read only properties for Forms. Property Get procedure that returns the value of a property. Each time the procedure is called. class and form modules. call me´ Function CallMe(request as string) As String Const mynumber=³9848912345´ CallMe = request & ³.
.. dblclick Private Sub Form_Load() ... The various events are click. The following syntax represents the event procedure for a Form_Load event. . an underscore(_).Procedures Event Procedures An event procedure is a procedure block that contains the control's actual name.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. and the event name.
Integer . Numeric I.4x10-38) . 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 (-32.Store large floating value which exceeding the single data type value VI. String ± Use to store alphanumeric values. Byte .483.2. Values are internally stored as -1 (True) and 0 (False) and any non-zero value is considered as true 5.255 II.(+ 2.store monetary values.(+ 32.147.4x1038) V. Double .767) III. Currency .768) . Variant ± Stores any type of data and is the default Visual Basic data type.468) IV.(+ 3.483. These are not stored as numeric values and cannot be used as such.Store integer values in the range of (.Data Types 1. Long . Boolean ± Boolean data types hold either a true or false value. A variable length string can store approximately 4 billion characters 3.Store integer values in the range of 0 . It supports 4 digits to the right of decimal point and 15 digits to the left 2.468) . 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 . In Visual Basic if we declare a variable without any data type by default the data type is assigned as default.Store floating point value in the range of (-3. Single .147. Date ± Use to store date and time values.
Select Shortcuts Range(³D5´) Range(³A1:D5´) Range(³A1:D5´.worksheets(³sheet1´).Offset (5. ActiveCell ).´G6:I17´) Range(³MyRange´) [D5] [A1:D5] [A1:D5.Referencing Range : Top-Left Bottom.Right Selection Range( ³A1:B5´ ).range(³a1´).value . ´B5´ ).Select Range( ³A1´ . ActiveCell.Select Range( Activecell .G6:I17] [MyRange] Full reference is Application.xlsm´).2) ).Select Range( ³A1´ .workbooks(³evba.
icons+ buttons] [. Ex. Title ± String expression displayed in the title bar of the dialog box. If you omit title.title ] ) memory_variable = MsgBox ( prompt [. If prompt consist of more than one line. and returns an integer indicating which button the user clicked. Syntax : MsgBox ( Prompt [.icons+buttons ] [. Code to display value of A A=1 Msgbox(³the value of A is ³ & A) . 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. the application name is placed in the title bar.title] ) Prompt ± String expressions displayed as the message in the dialog box. you can separate the lines using the vbrCrLf constant.
Default) a=a+1 MsgBox ("the value of A " & a) End Sub Following is an expanded InputBox Syntax : memory_variable = InputBox (prompt[.vbp Design the application as shown below. InputBox Function Displays a prompt in a dialog box.default]) memory_variable is a variant data type but typically it is declared as string.frm and save the Project as InputBox. Following example demonstrates the use of InputBox function Open a new project and save the Form as InputBox. waits for the user to input text or click a button. 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. add with 1 and display it Dim a As Integer a = InputBox("give the value of A ". and returns a String containing the contents of the text box. you can separate the lines using the vbCrLf constant Title ± String expression displayed in the title bar of the dialog box. . ³INavalue". If prompt consists of more than one line. Sub inputval() µ To accept a value .title][.Visual Basic Functions. x-position and y-position ± the position or the coordinate of the input box. The arguments are explained as follows: Prompt ± String expression displayed as the message in the dialog box. If you omit the title. which accept the message input by the users.
Range(Range(³A1´).xls´).Referencing Ranges with Other Sheets WorkSheets(³Sheet1´). Worksheets(³Sheet2´). End With With Worksheets(³Sheets2´) WorksheetFunction.Sum(Range(Range(³A1´).Range(Worksheets(³Sheet2´).Range(³A1´).Range(³A7´))) ± Wrong WorksheetFunction.Sum(Worksheets(³Sheet2´).Worksheets(³Sheet1´).Sum(Worksheets(³Sheet2´).Range(³A7´))) With«.Range(³A1´) Workbooks(³InvoiceData. range(³A7´))) End With .Range(³A1´) WorksheetFunction.
Bold = True Next i Cells Property in Range Property Range(Cells(1.Font.´c´) or Cells.Item(5.End(xlup).Bold = True Next i FinalRow = Range (³A65536´).Item(5.Item(Row.Cells(5.5)) ± useful to specify variables with parameters as in looping .Resize(.Row For i=1 to Finalrow Range(³A´ &i & ³:E´ &i).Font.3) Cells property is especially useful to loop through rows and columns Ex: FinalRow = Range (³A65536´).1).Cells Property to Select Range Cell Item Property Cells.Row For i=1 to Finalrow Cells(i.Column) Cells.End(xlup).5).´A´).
Resize(11.Interior.only Column Range(³B3´).3) Range(³B3´). 8).Row . Range(³B3´). Colorindex = 4 Sub try() Cells(1.2) --.interior.ColorIndex = 4 End Sub Column and Row Properties to select Range FinalRow = Range(³A65536´).1).Resize(.only Row Ex: Cells(i. Columnsize) To create a range B3:D13.Resize(1.resize(1.Resize(2) ---.Resize(Rowsize.End(xlUp).8).Resize Property to Change Size of Range Enables to change the size of range based off the location of active cell Syntax: Range. 1).
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
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
Instr(1.´ ³. Len(Str) ± 5) Week = Left(TStr.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.Functions ± convert week number into date Function Myname() As String Myname = ThisWorkbook.1.Name End Function Function MyFullName() As String MyFullName = ThisWorkbook.1)+ 0 ConvertWeekDay = FirstMon + (Week -1) * 7 End Function .4).Tstr.1) FirstMon = FirstMon ± FirstMon Mod 7 + 2 Tstr = Right(Str.
Then.IF If.Then.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 .Then selection structure Syntax of the If.Conditional Statements .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....value = "Pass" Else Range(³B3´).Then...Then selection If <condition> Then statement End If e..value = "A" End If Nested If..Else selection If <condition > Then statements Else statements End If e..Else selection structure Syntax of the If..: If A3>75 Then Range(³B3´)......: If A3>50 Then Range(³B3´).g.
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 ...Case Statement Select..Case selection structure Syntax of the Select..
Loop Statement The Do While. The following Do Loop counts from 1 to 100. if condition is True...1) = ³xlMacros´ number = number + 1 Wend ..Do while & While Wend Do While. First.Wend statement behaves like the Do While.. If condition is False on the first pass..Wend counts from 1 to 100 Dim number As Integer number = 1 While number <=100 Cells(number. The following While.1) = ³Company name´ number = number + 1 Loop A variable number is initialized to 1 and then the Do While Loop starts. the condition is tested. then the statements are executed.. Wend Statement A While.Loop is used to execute statements until a certain condition is met....Loop statement.. the statements are never executed While. Dim number As Integer number = 1 Do While number <= 100 Cells(number... When it gets to the Loop it goes back to the Do and tests condition again.
the program again executes the statements between Do and Loop While else exits the Loop. The following program block illustrates the structure: Dim number As Long number = 0 Do Cells(number.Loop While statement first executes the statements and then test the condition after each execution.Do Loop while 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.. Then it determines whether the counter is less than 201. If so..Loop While Statement The Do...
Loop statement. the Do Until..... .. Statements in the body of a Do Until..Loop and While.Wend repetition structures.Loop Statement Unlike the Do While. An example for Do Until....Loop are executed repeatedly as long as the loop-continuation test evaluates to False. Dim number As Long number=0 Do Until number > 10 number = number + 1 Cells(number. Loop structure tests a condition for falsity...Do until Do Until.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.2) = x Next The following loop counts numbers as 1.Next Loop is another way to make loops in Visual Basic.2) = x Next In order to count the numbers from 1 to 50 in steps of 2....Next Loop The For. 7. the following loop can be used For x = 1 To 50 Step 2 Cells(x.For Next « The For. 5.etc .. The following loop counts the numbers from 1 to 100: Dim x As Integer For x = 1 To 50 Cells(x.. 3.Next repetition structure handles all the details of counter-controlled repetition.
value= "This is number 4" Else Cells(number.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".Following example is a For.. . Dim number As Integer For number = 1 To 10 If number = 4 Then Cells(number..
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. Dim x As Integer Do While x < 10 Cells(x..While loop is terminated using Exit Do statement.Next loop. Dim x As Integer For x = 1 To 10 Cells(x..2) = x If x = 5 Then Cells(x.Exit Loops A For.2) = x x=x+1 If x = 5 Then Cells(x..3) = "The program is exited at x=5" Exit Do End If Loop .. The Exit For statement is executed and it terminates the For. Consider the following statement block. The Following statement block containing Do...Next loop condition can be terminated by an Exit For statement.
Font.With«.Text = "Hello World" End With .End With statement. It is easier to read the code by implementing the With.End With statement.Font. Multiple properties can be set and multiple methods can be called by using the With.Size = 14 .Bold = True .ForeColor = vbRed . a lot of coding is included that acts on the same object.Range(³A10:A20´) .. The concept can be clearly understood with following example. With Worksheets(³Sheet1´).... End With When properties are set for objects or methods are called.Height = 230 . The code is executed more quickly and efficiently as the object is evaluated only once.
12 Elseif Sales_V>=5000 Then /¶Subject to certain changes in Form1 statement¶/ Comm=Sales_V*0.06 Elseif Sales_V>=1000 and Sales_V<2000 Then Comm=Sales_V*0. "". 4500) If studentName(num) <> "" Then Form1. 1500.09 Elseif Sales_V>=200 and Sales_V<5000 Then Comm=Sales_V*0.Examples function sales commission Function Comm(Sales_V As Variant) as Variant If Sales_V <500 Then Comm=Sales_V*0. "Enter Name".Print studentName(num) Else End End If Next End Sub .03 Elseif Sales_V>=500 and Sales_V<1000 Then 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".
1).i).value = ³service revenue´ Cells(I.interior. 1).6).resize(1.interior.8).value >0 then Cells(I.Examples try for loop Ex 1: Sub tryloop() For I = 1 to 10 cells(i.end(xlup).6).1).8). Colorindex = 4 End if Next i FinalRow = Cells(65536. Colorindex = 4 End if Next i .value = ³service revenue´ Cells(I.8).row For i=2 to FinalRow if cells(I.resize(1.value >0 then Cells(I.value = I Next I End Sub For I = 2 to 10 if cells(I.8).
3).EntireRow.1).value = ³s54´ then Cells(I.end(xlup).value = 0 then Cells(I.6).value >0 then if Cells(I.1).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 .5).row For I = FinalRow to Step -1 if Cells(I.end(xlup).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.Example ± delete all rows where Column C has value s54 µDelete all rows where column C has value s54 FinalRow = Cells(65536. 1). FinalRow = Cells(65536.row ProblemFound = False For I = 2 to FinalRow if Cells(I.6).
Arrays An array is a consecutive group of memory locations that all have the same name and the same type. Each index number in an array is allocated individual memory space and therefore users must evade declaring arrays of larger size than required. . user-defined types and object variables. Arrays have upper and lower bounds and the elements have to lie within those bounds. To refer to a particular location or element in the array. The individual elements of an array are all of the same data type. 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.
Array must be declared explicitly with keyword "As". Dynamic array : The size of the array can be changed at the run time. Local arrays are declared in a procedure using Dim or Static. 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. module or local.size changes during the program execution. Arrays may be declared as Public (in a code module). Module arrays are declared in the general declarations using keyword Dim or Private.Array Declaration Declaring arrays Arrays occupy space in memory. .
numbers is the name of the array.Fixed-sized Arrays When an upper bound is specified in the declaration. The upper limit should always be within the range of long data type. If we want to specify the lower limit. a Fixed-array is created. The above declaration creates an array with 6 elements. an array of 10 elements is declared but with indexes running from 1 to 6. Public numbers(5) As Integer . Dim numbers (1 To 6 ) As Integer In the above statement. An example for this is given below. Declaring a fixed-array Dim numbers(5) As Integer In the above illustration. A public array can be declared using the keyword Public instead of Dim as shown below. then the parentheses should include both the lower and upper limit along with the To keyword. and the number 6 included in the parentheses is the upper limit of the array. with index numbers running from 0 to 5.
1 To 100) An example for three dimensional-array with defined lower limits is given below. An example for this is given here. A common use of multidimensional arrays is to represent tables of values consisting of information arranged in rows and columns. Visual Basic supports at least 60 array dimensions. Dim Marks ( 101 To 200.Multidimensional Arrays Arrays can have multiple dimensions. Dim AvgMarks ( 50. To identify a particular table element. 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. but most people will need to use more than two or three dimensional-arrays. Dim Details( 101 To 200. Note that multidimensional arrays can have more than two dimensions. 50) It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays. Tables or arrays that require two indexes to identify a particular element are called two dimensional arrays. 1 To 100. The following statement declares a two-dimensional array 50 by 50 array within a procedure.
ReDim Preserve dynArray ( 50 To 200) . This is shown in the example given below. the current data stored in the array is lost and the default value is set.: Dim dynArray ( ) The actual number of elements can be allocated using a ReDim statement. module or local scope. ReDim dynArray ( x + 1 ) Each time on executing the ReDim statement. a dynamic array can be initially declared and can add elements when needed instead of declaring the size of the array at design time. e. But if we want to change the size of the array without losing the previous data. This example allocates the number of elements in the array based on the value of the variable. dynamic arrays have either Public (in code modules). Like fixed-sized arrays.Dynamic Arrays There will be a situation when the user may not know the exact size of the array at design time.g. x. Module dynamic arrays are declared using keyword Dim or Private. Under such circumstances. we have to use the Preserve keyword with the ReDim statement. because they can be resized anytime to accommodate new data. Local dynamic arrays are declared with either Dim or Static. Dynamic arrays are more flexible than fixed-arrays.
You can control visible or invisible at runtime. and aspects of their behavior. the move method can be used with some controls to change their location and size. key press on keyboard etc. 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. Form controls are old generation and Activex are new and rich in features and driven by properties. For instance.. Form controls can respond to single predefined events whereas Activex controls can respond to many events like mouse click. in the calculator program. Controls have properties that define aspects their appearance. double click. For instance. Object Browser will help you to explore objects. all the captions of the command buttons such as +. When you right click a control. 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 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. 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. MC. For example. it gives assign macro. it is form control otherwise it is activex control with properties. . Once you right click form controls. double click etc. methods can also be used to manipulate controls from code. size and colour. 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. Activex show the properties. 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 . such as position. They can respond to events initiated by the user or set off by the system. . However. such as their response to the user input. a code could be written in a CommandButton control's click event procedure that would load a file or display a result. MR are commonly found in an ordinary calculator. In addition to properties and events... if you get assign macro. There are two types of controls 1) form controls 2) activex controls.
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. It stops highlighting design mode button. turn off design mode. Line and Shape controls. To run code. invisible or disabled controls also cannot receive the focus although a TabIndex value is given. Image. which are not included in tab order. Timer. At run time. . 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. When there are no more controls with higher TabIndex value. Data. except for Menu. Visual Basic assigns a tab order to control as we draw the controls on the Form.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. By default. Setting the TabIndex property of controls is compulsory in development environment. switch back to the worksheet. Every time a tab key is pressed.
properties. The list always begins with <globals>. a list of globally accessible members. Members list Displays the elements of the class selected in the Classes pane by group and then alphabetically within each group. Any object with code will appear in bold .Object Browser Press F2 in Visual Basic Editor . events. Methods. that class appears in bold. If you select a Class and do not specify a member. Methods Events Properties Enumeration objects . If there is code written for a class. 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. The default member is identified by an asterisk (*) or by the default icon specific to the member. you will get the default member if one is available. There are Classes Displays all of the available classes in the library or project selected in the Project/Libraries box.
Text Box Text Box Property of Controls A TextBox control is an edit field or edit control. displays information entered at design time. the text can be selected using three properties: SelLength ± Returns or sets the number of characters selected. 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. set the MultiLine property to True To customize the scroll bar combination on a TextBox. 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.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 . If the MultiLine property is et to False. When no text is selected. SelStart indicates the position of the inserted point. If no text is selected. then setting the Alignment property has no effect In order to work with the part of a text in a text box. you can set the alignment using the Alignment property. SelText consists of a zerolength string. entered by the user. SelStart ± Returns or sets the starting point of selected text. The test is left-justified by default. or assigned to the control using code at run time. Default event is change() and default property is value. Private Sub TextBox1_Change() If TextBox1. SelText ± Returns or sets the string containing the currently selected text.
which adds a subroutine like the one given below Private Sub Command1_Click( ) .. 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.Label . 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... End Sub ... We can also use a label to identify a control.. interrupt or end a process using the CommandButton control Properties of a CommandButton control To display text on a CommandButton control.. To add a click event handler.. 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... 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...... such as TextBox control. set its caption property An event can be activated by clicking on the CommandButton To set the background colour of the CommandButton... Properties Using a Label Its a graphical control user can use to display uneditable text.
You can use the Visible property to make the option button visible to invisible. CommandButton and three OptionButton controls. 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.Value = True Then MsgBox "I am Female³ End If End Sub . Example Open a new Standard EXE project and the save the Form as Option. The following example contains a Label. The Application is run by pressing F5 or clicking on the Run icon in the tool bar.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. By pressing the Exit button the program is terminated.vbp The application responds to the following events The click event of the optWithoutMeal displays the amount of 2500 in txtAmount.Value = True Then MsgBox "I am Male " Else End If End Sub Private Sub OptionButton2_Click() If OptionButton2.frm and save the project as Option. Private Sub OptionButton1_Click() µ create male and female two option buttons If OptionButton1. The click event of the optWithMeal displays the amount of 3500 in txtAmount. The code is to assign it to True Option1. TextBox.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 click event of the optLuxuty displays the amount of 5000 in txtAmount.
If the number of items exceed the value that be displayed. These scroll bars can be scrolled up and down or left to right through the list. scroll bars will automatically appear on the control. . The following Fig lists some of the common ComboBox properties and methods.List Box and Combo Box ListBox and ComboBox controls present a set of choices that are displayed vertically in a column.
because by default the index is assigned. 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. 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.AddItemitem. Object. 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. The AddItem method uses the following syntax. Following is an example to add item to a combo box.
The user could click the down arrow to view the list. The user can either select a value from the list or type a value in the edit area. 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. Open a new Standard EXE project is opened an named the Form as Listbox. There are three types of ComboBox styles that are represented as shown below.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. The user can only select an item and cannot type anything in the edit area. 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. Anyway this area displays the selected item. The Dropdown Combo box first appears as only an edit area with a down arrow button at the right. Remove.vbp Design the application as shown below. . Example This example is to Add .frm and save the project as Listbox. The user can select an item from the list or type an item in the edit box portion of the combo box. Clear the list of items and finally close the application. A simple combo box displays the contents of its list all the time. At run time . The list portion stays hidden until the user clicks the down-arrow button to drop down the list portion. The Dropdown list combo box turns the combo box into a Dropdown list box. the control looks like the Dropdown combo box. The difference between Dropdown combo & Dropdown list combo is that the edit area in the Dropdown list combo is disabled. A scroll bar is displayed beside the list if there are too many items to be displayed in the list box area.
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. The click event of the Add button adds the text to the list box that was typed in the Text box.The following event procedures are entered for the TextBox and CommandButton controls.
. The code for the clear button clears the listbox when you press it. The number of items is decreased in the listbox and the value is displayed in the label.Command Buttons Remove button removes the selected item from the list as soon as you pressed the Remove button. And the number of items shown in the label becomes 0.
which enables the user to select a value by positioning it at the desired location. 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. .vbp When the thumb's position of the ScrollBar is changed the value has to displayed in the TextBox. that may be any integer between minimum and maximum values assigned. Design the application as shown below. The Min and Max property represents the minimum and maximum value.frm and name the project as ScrollBar.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.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.
it retains its value when it reenters this sub in for loop of othersub() procedure End Sub . you need to declare it as public. 100) Call fnval For pv = 1 To 10 'when global variable value is change it is changed in all references wherever it is referred. 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.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. 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 computed value MsgBox ("fnvalue " & fn & " pv value" & pv) fn = fn + 10 'as fn is static . 50) fn = mul(pv. Call fnval Next pv End Sub Function mul(pv.
Setting the Index property to a value that is not null .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.
most of the property settings are copied from the lowest existing element in the array.frm and save the Project as Calculater.vbp Design the form as shown below . Index % is the value of the index in the array.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. 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. When a new element of a control array is loaded. Following example illustrates the use of 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. cmdDevide controls respectively. .Examples The below code is entered in the cmdNeg_Click( ) procedure The following code is entered in the click events of the cmdPlus. cmdMinus.
.To print the result on the text box. the following code is entered in the cmdEqual_Click ( ) event procedure. the output appears. Save and run the project. On clicking digits of user's choice and an operator button.
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. By ticking the CheckBox the value is set to True.vbp Design the Form as shown below and type the code in module1 . 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.
value=true Sub ckbx() UserForm1. use view->toolbox to see the controls User properties window to change the properties for controls like caption. use F4 Write event handler procedures for the controls like click .checkbox1..Show UserForm1. In VBE Editor.Using Userforms When you want to get lot of information. if controls are not visible .. use F7 to view the code . insert ->Userform Add controls to user form .Hide Unload userform1 End Sub . double click etc. then userforms are better tool. name etc. 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.
Value = True Then TxtDisplay.FontUnderline = False End If End Sub Private Sub optblue_Click() TxtDisplay.ForeColor = vbGreen End Sub Private Sub OptRed_Click() TxtDisplay.FontItalic = True Else TxtDisplay. Check the program by clicking on OptionButtons and CheckBoxes.FontBold = False End If End Sub Private Sub ChkItalic_Click() If ChkItalic.Value = True Then TxtDisplay.ForeColor = vbBlue End Sub Private Sub optgreen_Click() TxtDisplay.FontUnderline = True Else TxtDisplay.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.ForeColor = vbRed End Sub Private Sub TxtDisplay_Change() End Sub Run the program by pressing F5.FontBold = True Else TxtDisplay. .Value = True Then TxtDisplay.
vbp Design the application as shown below. .default]) memory_variable is a variant data type but typically it is declared as string. InputBox Function Displays a prompt in a dialog box. Following is an expanded InputBox Syntax : memory_variable = InputBox (prompt[. and returns a String containing the contents of the text box. If prompt consists of more than one line.Visual Basic Functions. The arguments are explained as follows: Prompt ± String expression displayed as the message in the dialog box. 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. waits for the user to input text or click a button. 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. which accept the message input by the users.title][. 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.frm and save the Project as InputBox.
Caption = ans End If End Sub Save and run the application. As soon as you click OK the output is shown as shown below . "Testing". 0) If ans = "" Then lbl2.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". 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.
Title ± String expression displayed in the title bar of the dialog box. and returns an integer indicating which button the user clicked. icons+ buttons] [. the application name is placed in the title bar. Code to display value of A A=1 Msgbox(³the value of A is ³ & A) . Syntax : MsgBox ( Prompt [. If you omit title. you can separate the lines using the vbrCrLf constant. Ex.title ] ) memory_variable = MsgBox ( prompt [. If prompt consist of more than one line.icons+buttons ] [. Icons + Buttons ± Numeric expression that is the sum of values specifying the number and type of buttons and icon to display.title] ) Prompt ± String expressions displayed as the message in the dialog box.MessageBox Function Displays a message in a dialog box and wait for the user to click a button.
AddItem txtName.SetFocus cmdAdd. "Add Confirm") If answer = vbYes Then lstName. vbExclamation + vbYesNo.ListIndex If remove < 0 Then MsgBox "No names is selected".Message Box code Following code is entered in the txtName_Change ( ) event Private Sub txtName_Change() If Len(txtName.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.Text = "" txtName.Text txtName.Text) > 0 Then cmdAdd. "Error" Else . vbInformation.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. "Confirm") If answer = vbYes Then End Else MsgBox "Action canceled". vbInformation. "Confirm" End If End Sub Save and run the application.answer = MsgBox("Are you sure you want to delete " & vbCrLf & "the selected name?".RemoveItem remove txtName.SetFocus MsgBox "Selected name was deleted". vbInformation. You can notice the different type of message box types are used to perform an action ._ vbCritical + vbYesNo. "Warning") If answer = vbYes Then If remove >= 0 Then lstName. "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?".
000/. Function Yearly_Rate(PV As Double.A3) store FD amount in A1 50. 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. you You can create your own User defined functions . enter the following code.000. of years invested =Yearly_Rate(A1.User defined Functions All the Excel functions are available in Fx (insert Function) .32) * 5 / 9 End If End Function .4 and only interest is 23466. of years to invest in A3 =5 . if conversion flag (cflag=1) it will convert from centigrade to Fahrenheit otherwise Fto C Function convertCentigrade_Fahrenheit(num 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.. R As Double. if these functions are not able to meet your requirement. N As Double) As Double Yearly_Rate = PV * (1 + R) ^ N 'Performs computation End Function UDF for CentrigradetoFahrenheit .rs for 8% interst how much will it be after 5 years ? The formula is Interest + principle = FD Amount (1+interst rate / 100)^ no. You get 73466. interest rate in A2 =8/100. 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 .4 after subtracting 50000/In Module1 . no.A2.
You need to use VBA equivalent functions or mathematical operators to carry out same calculation.User defined Functions UDF s will work only for a cell and they will not work for changing the structure of worksheet. 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.vlookup(Product. 2) but not all functions could be used .
and procedures . when a drive door is left open. With logic errors. 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. but will produce incorrect or unexpected results. 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 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.Error-Handling and Debugging No matter how hard we try. Visual Basic detects these errors as they occur and even provides help in correcting them. objects. Visual Basic allows you to trap such errors and make attempts to correct them ± Logic errors are the most difficult to find. The Visual Basic debugger is an aid in detecting logic errors Some ways to minimize errors: ± Design your application carefully. Examples include: when a variable takes on an unexpected value (divide by zero). or when a file is not found. errors do creep into our programs.
. your program will usually end in a rather unceremonious manner Error trapping is enabled with the On Error statement: On Error GoTo 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. That is. Visual Basic recognizes an error has occurred and enables you to trap it and take corrective action. .] On Error GoTo HandleErrors [Procedure code] Exit Sub HandleErrors: Error handling code] End Sub Once you have set up the variable declarations. Yes. the On Error statement is executed to enable error trapping. and any other procedure preliminaries. The error handling code goes at the end of the procedure. .. program control is transferred to the line labeled errlabel. Your normal procedure code follows this statement. constant definitions.Run-Time Error Trapping and Handling Run-time errors are trappable. Note you must exit (with Exit Sub) from the code before reaching the HandleErrors line to avoid inadvertent execution of the error handling code. If an error occurs and is not trapped. this uses the dreaded GoTo statement! Any time a run-time error occurs following this line. following the HandleErrors statement label. Sub SubExample() [Declare variables. This is the code that is executed if an error is encountered anywhere in the Sub procedure.
if a Resume is encountered outside of the error handling portion of the code. This is done in the error handling code Visual Basic offers help in identifying run-time errors. the number associated with the current error condition. an error occurs . in its Number property (Err. This could be dangerous in that. If at some time in your procedure. that is done with the following statement: On Error GoTo 0 Once a run-time error occurs.consult on-line help for further information. (The Err function has other useful properties that we won¶t cover here . That control is returned via the Resume statement.) The Error() function takes this error number as its argument and returns a string description of the error. if the error has not been corrected (via code or by the user). you want to turn off error trapping. There are three options: ±Resume Lets you retry the operation that caused the error. 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. Consult on-line help for Visual Basic run-time error numbers and their descriptions Once an error has been trapped and some action taken. Since the error handling code is in the same procedure where an error occurs. The Err object returns. all variables in that procedure are available for possible corrective action. an error occurs. When executing the error handling portion of the code and the end of the procedure is encountered before a Resume. control is returned to the line where the error occurred. control must be returned to your application. Likewise.Number). That is. we would like to know what the error is and attempt to fix it.
using the Visual Basic provided error description [Error(Err. provides a description of the error.General Error Handling Procedure Development of an adequate error handling procedure is application dependent. For example. If Abort is selected. program operation continues with the line following the error causing line. the offending program line is retried (in a real application. uses a critical icon along with the Abort.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. this routine is only executed when an error occurs. and allows the user to Abort. or Ignore. if a 'divide by zero' is found. you or the user would have to change something here to correct the condition causing the error). Retry. A message box is displayed. and uses the error number [Err. "Error Number" + Str(Err. and Ignore buttons. This framework is a good starting point for designing custom error handling for your applications.Number)] as the message.Number). It simply informs the user that an error has occurred. You need to know what type of errors you are looking for and what corrective actions must be taken if these errors are encountered. (This is done using a Resume to the line labeled ExitLine. This message box returns a response indicating which button was selected by the user.) If Retry is selected.Number] as the title. we simply exit the procedure. The generic code (begins with label HandleErrors) is: HandleErrors: Select Case MsgBox(Error(Err. First. Retry. vbCritical + vbAbortRetryIgnore. . If Ignore is selected. 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.
Place the line. if your procedure is the SubExample seen earlier.Number)) Case vbAbort Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub End Sub Again. . [Procedure code] .] .. you need to do three things: Copy and paste the error handling code into the end of your procedure. vbCritical + vbAbortRetryIgnore. . On Error GoTo HandleErrors.. .Number). you need code to clear error conditions before using the Retry option. For example. You must determine its utility in your applications and make any modifications necessary. Exit Sub HandleErrors: Select Case MsgBox(Error(Err. this is a very basic error-handling routine. On Error GoTo HandleErrors .To use this generic code in an existing procedure. Specifically. . the modified code will look like this: Sub SubExample() . [Declare variables. Place an Exit Sub line immediately preceding the HandleErrors labeled line. "Error Number" + Str(Err. at the beginning of your procedure.
not just ones generated with the Raise method). use the method Clear: Err. use: Err.Show frmerror. To cause an error with value Number.cmdGenError Text1: Name . to really get fancy. Once you've written an error handling routine. 2. you can also use Raise to generate your own µapplication-defined¶ errors.Hide End Sub .True Name . you need to test it to make sure it works properly. Add a text box and a command button. Set the properties of the form and each control: Form1: BorderStyle . 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.Clear Example ± Simple Error Trapping 1.Error Generator Name frmError Command1: Caption .txtError Text . There are errors specific to your application that you want to trap To clear an error condition (any error. though! And. Don¶t forget to remove the Raise statement once testing is completed.1-Fixed Single Caption .[Blank] The form should look something like this: Enter this code in module 1 Sub ergen() frmerror. One last thing. Start a new project.Raise Number We can use this function to completely test the operation of any error handler we write. But.Generate Error Default . creating run-time errors is sometimes difficult and perhaps dangerous.
"Error Number" + Str(Err.3. The generic error handler then displays a message box which you can respond to in one of three ways.Clear Exit Sub HandleErrors: Select Case MsgBox(Error(Err.Number).Raise Val(txterror. Option Explicit Private Sub CmdGenError_Click() On Error GoTo HandleErrors Err.Print ("error vbignore") End Select ExitLine: Exit Sub End Sub In this code.Number)) Case vbAbort Debug. .Print ("error vbretry") Case vbIgnore Debug. Attach this code to the cmdGenError_Click event. we simply generate an error using the number input in the text box. vbCritical + vbAbortRetryIgnore.Text) Err.Print ("VBAbort") Resume ExitLine Case vbRetry Debug.
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 . Notice how program control changes depending on which button is clicked. Save your application. Try it out using some of these typical error numbers (or use numbers found with on-line help).Error codes and description 4.
The usual approach is to eliminate them as they are discovered. Visual Basic provides an excellent set of debugging tools to aid in this search. should select the debugging approach and tools you feel most comfortable with. as the program designer. or the program will go into break mode if it encounters an untrapped error or a Stop statement. pressing Ctrl+Break. and the Watch Window. You can enter break mode by setting breakpoints.Debugging Visual Basic Programs We now consider the search for. The interface between your application and the debugging tools is via three different debug windows: the Immediate Window. logic errors. the Locals Window. not a science. Or. There are no prescribed processes that you can follow to eliminate all logic errors in your program. 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. These windows can be accessed from the View menu (the Immediate Window can be accessed by pressing Ctrl+G). and elimination of. These are errors that don¶t prevent an application from running. 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 . 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. Debugging a code is an art. You. but cause incorrect or unexpected results. Once in break mode.
Example ± Debugging 1.1 * X ^ 2) End Function Admittedly. The function Fcn is computed using: Function Fcn(X As Integer) As Integer Fcn = CInt(0. The code attached to this button¶s Click event is a simple loop that evaluates a function at several values. 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. Unlike other examples. We won¶t be real careful about proper naming conventions and such in this example. Set up the application and get ready to try debugging. especially without any output. It then increments X by 1 and repeats the Loop. . The button is used to execute some code. we¶ll do this one as a group. It will be used to demonstrate use of the debugging tools. 3. The example simply has a form with a single command button. It continues looping While X is less than or equal to 20. but it makes a good example for looking at debugger use. this code doesn¶t do much. Private Sub Command1_Click() Dim X As Integer. 2.
Thank You .