VBA Quick Introduction

28
VBA Using the Macro Recorder Microsoft provides programmers with an easy-to-program technique commonly known as Macro Recorder. Any action which can be performed manually on the surface of the spreadsheet can be recorded in the form of VBA code. The same set of actions can be re- performed simply by running the VBA code aka Macro. This functionality provides excel users, who are not able to dive into the complexity of VBA programming, an option to automate simple steps, generally expected to be carried out multiple times. VBA Code Know How Section: A Module is a word processing document with some special formatting characteristics that helps the programmer write and test code. The Visual Basic Editor (VBE): Can be accessed via shortcut Key (Alt + F11) or by Tools>Macro>Visual Basic Editor (Alt+ T>M>V). Code Modules : All macros reside in code modules. Multiple code modules can be associated with a single spreadsheet and multiple macros can reside inside a single code module. There are two types of code modules namely standard modules and class modules. Class modules are used to create user-defined objects and Standard modules are used to store general purpose interactive macros. Procedures : In VBA, macros are referred as Procedures. There are two types of procedures – subroutines and functions. The macro recorder can only produce subroutines. Subroutines start with the keyword “Sub” followed by the name of the procedure and opening and closing parentheses. The end of the sub procedure is marked by the keywords “End Sub”. Adding comment : Comments can be added within VBA code by starting the line by a single quote (‘) which is ignored by VBA. Comments are added to provide documentation, which are very important component of good programming practice. Comments can also be added to the right of line of code. Example: Range(“B1”).Select ‘select the Cell B1 The Project Explorer : The project explorer is an essential navigational tool. In VBA, each workbook contains a project. The project explorer displays all open projects and the component parts of those projects. The project explorer can be used to locate, activate, add and remove Code Modules. The properties window : The scrollarea property of sheet can be used to restrict the users to that area of the worksheet. Other ways to run a Macro : Apart from running macros by using shortcut keys and via Tools menu, macros can also be run by attaching to Objects like buttons, combo boxes, list boxes, scrollbars, check boxes and option buttons and running the macro based on any event on the object. Event Procedures : Event procedures are special macro procedures that respond to the events that occur in Excel. Events include user actions, such as clicking the button, activating sheet, activating worksheet etc. All event procedures are contained in the class modules behind the workbook, worksheets, charts and

Transcript of VBA Quick Introduction

Page 1: VBA Quick Introduction

VBA

Using the Macro Recorder Microsoft provides programmers with an easy-to-program technique commonly known as Macro Recorder. Any action which can be performed manually on the surface of the spreadsheet can be recorded in the form of VBA code. The same set of actions can be re-performed simply by running the VBA code aka Macro. This functionality provides excel users, who are not able to dive into the complexity of VBA programming, an option to automate simple steps, generally expected to be carried out multiple times.

VBA Code Know How Section: • A Module is a word processing document with some special formatting

characteristics that helps the programmer write and test code.

• The Visual Basic Editor (VBE): Can be accessed via shortcut Key (Alt + F11) or by Tools>Macro>Visual Basic Editor (Alt+ T>M>V).

• Code Modules: All macros reside in code modules. Multiple code modules can be associated with a single spreadsheet and multiple macros can reside inside a single code module. There are two types of code modules namely standard modules and class modules. Class modules are used to create user-defined objects and Standard modules are used to store general purpose interactive macros.

• Procedures: In VBA, macros are referred as Procedures. There are two types of procedures – subroutines and functions. The macro recorder can only produce subroutines. Subroutines start with the keyword “Sub” followed by the name of the procedure and opening and closing parentheses. The end of the sub procedure is marked by the keywords “End Sub”.

• Adding comment: Comments can be added within VBA code by starting the line by a single quote (‘) which is ignored by VBA. Comments are added to provide documentation, which are very important component of good programming practice. Comments can also be added to the right of line of code. Example: Range(“B1”).Select ‘select the Cell B1

• The Project Explorer: The project explorer is an essential navigational tool. In VBA, each workbook contains a project. The project explorer displays all open projects and the component parts of those projects. The project explorer can be used to locate, activate, add and remove Code Modules.

• The properties window: The scrollarea property of sheet can be used to restrict the users to that area of the worksheet.

• Other ways to run a Macro: Apart from running macros by using shortcut keys and via Tools menu, macros can also be run by attaching to Objects like buttons, combo boxes, list boxes, scrollbars, check boxes and option buttons and running the macro based on any event on the object.

• Event Procedures: Event procedures are special macro procedures that respond to the events that occur in Excel. Events include user actions, such as clicking the button, activating sheet, activating worksheet etc. All event procedures are contained in the class modules behind the workbook, worksheets, charts and

Page 2: VBA Quick Introduction

Userforms. Available events can be used/browsed by activating a module such as ThisWorkbook module, choosing an object such as Workbook, from the left drop-down list at the top of the module and activate the right drop-down menu and select the event.

The Workbook_Open event can be used to initialize the workbook when it is opened

• User Defined Functions: Excel has hundreds of built-in worksheet functions that can be used in cell formulas. For more sophisticated functions, User Defined Functions can be created using VBA. UDF can not be recorded unlike Subroutines. The key difference between functions and sub procedures is that a function procedure returns a value. A function procedure returns the value to be returned by setting its own name equal to the return value. Functions may or may not have input parameters.

• Direct References to Ranges and Using Worksheet functions: An example: Sub Sum_Range()

Dim xyz As Integer, sumrange As Range Set sumrange = ThisWorkbook.Worksheets("Sheet1").Range("C1:C5") xyz = WorksheetFunction.Sum(sumrange) Range("C6").Value = xyz

End Sub

• Note: UDFs are not as efficient as the built-in excel functions. If UDFs are used extensively in a workbook, recalculation time will be greater compared with a similar workbook using the same number of built in functions.

Page 3: VBA Quick Introduction

Excel Object Model: At a Glance The Visual Basic for Applications programming language is common across all Microsoft Office Applications. In addition to Excel, VBA can be used in Word, Access, Powerpoint, Outlook, Frontpage etc. Working with different applications require knowledge about the objects that the application contains. Each application has a clearly defined set of objects that are arranged according to the relationships between them. Their structure is referred to as the application’s object model. Object: In Object-Oriented Programming (OOP) everything that can be described is denoted by a class. Instance of a class is an Object. In Excel, a workbook is an object, a worksheet is an object and a range is an object. These objects are only a small sample of around 200 object types available in Excel. Collections: Collections are objects themselves – objects that contain other objects that are closely related. Excel is an object itself, referred to by the name Application. In Excel Application object, there is a workbooks collection that contains all the currently open workbook objects. Collections and Objects are often related in a hierarchical or tree structure. Fields: Fields are variables that capture the state of an object. Properties: Properties are quantifiable characteristics of an Object. Methods: Methods are the actions that can be performed on objects or by objects. Methods often have parameters (or arguments) that can be used to modify the way the method works.

Excel Object Model Excel is a three-tier application: the client services tier, the object model, and the data services layer. The usual spreadsheet interface that you view is the client services tier and is the layer that normally communicates with the user. Underneath the client services tier sits the Excel Object Model. Every time something is done on the surface of the spreadsheet, a command is issued through the Excel Object Model. Every command menu and function key on the Microsoft Excel Front end is represented with the Excel Object Model. Below the Excel object model sits the data services layer, which holds the data in the spreadsheets and is modified by commands from the Excel object model. The Excel object model contains a large number of objects—for example, Workbooks, Worksheets, Ranges, Charts, Pivot Tables, and Comments. These Excel objects are discrete entities that offer various pieces of data analysis functionality. Most important, they can be controlled from code. An object is a part of the Excel program. The objects are arranged in a hierarchy. For example, at the top of the object model is the Application object, which is Excel itself. Under the Application object is the Workbook object, and within the Workbook object are Worksheet objects. Within each Worksheet object are Range objects, and so on. Each object can contain settings, called properties, and actions that can be performed on the object, called methods.

Page 4: VBA Quick Introduction

Properties

A property is a scalar attribute that defines various parameters of an object. An example is the Visible property of a worksheet, which can be xlSheetVisible (–1), xlSheetHidden (0), or xlSheetVeryHidden (2) and dictates whether the worksheet is visible to the user or is hidden. This is done here using built-in constants (numeric values are in parentheses). The properties hold the parameters that define the object. Properties are very much dependent on the objects that they are part of, and their values can be text or numeric. Properties can be either read-only or read/write. Read-only means the property's value (setting) can be accessed but not changed. Read/write means that a property’s value can both be accesses and changed. Few properties are read only to preserve the integrity of the Excel Object Model. Read/Write properties can be manipulated by substituting other values into it to provide different effects depending on the object and property. A dot is used as a separator between the Object and the Property. Methods

Methods are ways of executing actions based on a particular object. They provide a shortcut to take some action on a particular object. Methods effectively are subroutines based on objects that take certain actions, sometimes dependent on parameters passed to them. For example, in the following code,

Workbooks.Open ("c:\MyFile.xls") “C:\MyFile.xls” defines the location of the file to be opened; this is a mandatory parameter for this method. There are other optional parameters that can be passed, such as a password if required, and read-only. Optional parameters are shown in the tip text for the method with square brackets around them, such as [Title]. The preceding example can be rewritten as follows: Workbooks.Open FileName:="c:\myfile.xls", ReadOnly:=True, Password:="apple" Each parameter can be defined by naming the parameter and following it with a colon and an equal sign (:=). When passing by name, the parameters can be passed in any order. However, when parameters are passed without naming them, the default order must be followed. Collections

Collections are objects that contain a group of like objects. An example is the Worksheets collection, which contains all the worksheet objects for a given workbook. All the worksheets are like objects because they have the same properties and methods. In Excel, all objects are either singular objects referenced by name, or objects in a collection referenced by index or name. Collections also have their own properties and methods apart from the objects that they hold. For example, collections always hold a Count property that represents the number of objects within the collection, and they always have an Add method to add a new object into the collection. The greatest advantage with collections is that it can be used in a loop/iteration.

Page 5: VBA Quick Introduction

Example: Sub ShowName()

Dim w As Worksheet For Each w In Worksheets MsgBox w.Name Next

End Sub Initially, this code sets up a variable w to represent a worksheet object. This represents the current worksheet being cycled through. The code then cycles through the Worksheets collection using a For Each..Next loop. The code takes each worksheet in turn, gets the name property, and displays it in a message box onscreen. The Object Browser

The Object Browser is a useful tool for looking at the properties, methods, and constants of an object—in this case, the Excel Application object. To access the Object Browser, select View | Object Browser from the VBE menu or press F2. Use the pull-down that says <All Libraries> to find the Object Library, and click it. This will show all the classes of the Excel object and the properties and methods. It will also show the relationships and hierarchy of the objects themselves. Specific strings can be searched in the browser to locate the object or property of interest. For a specific class, all properties, methods and collection can be browsed through. The read only or read-write permission related to a property can also be looked at by clicking the property in the browser. Clicking a method displays the syntax for parameters and which ones are optional and mandatory. The window at the bottom of the Object Browser displays the full syntax of the method, with optional properties shown in square brackets ([ ]). Hierarchy

Within the Excel object model there is a hierarchy of objects. It is important to understand how this hierarchy works because of the implications in referring to objects. The highest object in the hierarchy is called Application; this represents Excel itself. The most commonly used object collections below this are as follows:

Object Collection Description

Dailogs Collection of built-in dialogs in Excel

Windows Used to access different windows in Excel

Workbooks Collection of all current workbooks loaded into Excel

CommandBars Collection of menu items in Excel

Worksheets Collection of all worksheets within current workbooks in Excel

The third, fourth, and fifth tiers of the hierarchy contain further objects to access functionality on the second-tier objects. The Excel object structure has a tree-like structure. The Application object is the root, the Workbook objects are the trunk, the

Page 6: VBA Quick Introduction

Worksheet objects are the branches, and the cells become the leaves. For example, going down from the Workbook object, there are worksheets, windows, and charts. Application Object: The Application object is at the highest point in the hierarchy of the object model and represents the whole Excel application. It contains the collections of workbooks and worksheets that make up spreadsheets in Excel, and it will give high-level information about the application itself, such as the active cell (the cell where the cursor currently is) and the active worksheet (the worksheet that has the focus of the cursor). It also has methods for functions such as calculating the spreadsheet (in the same way as pressing F9 on the Excel spreadsheet) or retrieving the Open filename or the Save As filename of the Excel application. The Excel application can also be quit and closed completely. The Application object has no print options, as it is only an Application object and not a worksheet or workbook. The Application object is the default object and does not have to be specified within the syntax of the statement for some properties. For example, the statement ActivePrinter returns the details of the active printer.

Main Properties, Methods, and Collections ActiveCell: The ActiveCell property represents the active cell the cursor is currently on within the Excel spreadsheet. The properties of the active cell can be accessed by further going down the structure. ActivePrinter: This property returns the name of the active printer and the connection it is using. ActiveSheet: This property represents the active worksheet being displayed in Excel. ActiveWindow: This property represents the active window in Excel. ActiveWorkbook: This property represents the active workbook within Excel application. AddInns: It is a collection of all the add-ins currently loaded in Excel. Example:

Sub test() Dim MyAddin As AddIn

For Each MyAddin In AddIns MsgBox MyAddin.FullName

Next End Sub

Calculate: This method forces recalculation of the entire spreadsheet just as when F9 is pressed. Syntax: Application.Calculate Calculation: This property sets the method of calculation used in the Excel application. It can be set to xlCalculationAutomatic, xlCalculationManual, and xlCalculationSemiAutomatic. Example: Application.Calculation = xlCalculationManual Caption: This property holds the caption for the Excel application that is found in the window bar for Excel. Help: This method will call up the standard Excel help file. Quit: This method closes down the Excel application completely. The prompt is shown to save any unsaved files. Example: Application.Quit

Page 7: VBA Quick Introduction

Selection: This property holds the current selection object within the Excel application. Sheets: This collection represents all the worksheets within the current workbook. This sounds similar to the Worksheets collection, but it does have different properties and methods. Also, there is no individual Sheet object, and there is within the Worksheets collection. Another important difference is that Sheets can be used to print or print preview individual sheets; a Worksheet object does not have a method to do this Example: Apllication.Sheets(“Sheet1”).Print Apllication.Sheets(“Sheet1”).PrintPreview ThisWorkbook: This property represents the workbook where the current macro is running. Undo: This method undoes the last action on the Excel application. It is the same as selecting Edit | Undo.... from the Excel menu. UserName: This property returns the name of the user logged on to the Windows system. Version: This property returns the version number of VBA being used. WorkBook Object The Workbook object represents an entire workbook loaded into Excel. The default workbook is Book1. It is one level down from the Application object. The Workbook object forms a part of a Workbooks collection, which represents all the workbooks currently loaded into Excel. The Workbook object can not be referenced directly; it must be accessed through the Workbooks collection.

Main Properties, Methods, and Collections Activate: This method activates the workbook specified in the Collection object. It will automatically go to the active sheet within that workbook. This is the same as selecting Window from the Excel menu and clicking a workbook. Example: Workbooks(“book1”).activate ActiveSheet: This property references the active sheet within a particular workbook. The ActiveSheet property in relation to the Application Object refers to the active sheet anywhere within the application. Close: This method closes the workbook. HasPassword: This property returns True or False, depending on whether the workbook is protected by a password. This is a Read Only property. PrintOut: This method prints out the active sheet of the referenced workbook to the current printer. Example: Workbooks("book1").PrintOut PrintPreview: This method provides a print preview on the active sheet of the referenced workbook. Example: Workbooks("book1").PrintPreview ReadOnly: This property returns True or False on whether the workbook is read-only. Save and SaveAs: These methods save the workbook, normally before it is closed. The workbook can be saved to the same name or usnig the SaveAs method to save to a different filename. Save will overwrite the previous version; SaveAs will create a new version. Example: Workbooks("book1").Save

Page 8: VBA Quick Introduction

Workbooks("book3").SaveAs "C:\Myfile.xls" Saved: This property returns True or False, depending on whether the workbook has been saved pending any changes the user has entered. If the workbook has been saved and no further changes have been made, this will display True. If changes are then made, it will display False. Sheets: Sheets work exactly the same way as the Sheets collection described in the “Application Object” section. Windows: This collection represents all the windows within the Workbook object. Worksheets: This collection represents all the worksheets within the Workbook object. Windows Object This object represents all the windows within the Excel application. The Windows collection represents what is seen when the Window option is selected on the Excel menu, and many of this object's methods relate to the options on the Window menu, such as Split or Freeze Panes. Main properties, Methods and Collections Activate, ActivateNext, ActivatePrevious: These methods activate a particular window from within the code by specifying the window within the windows collection. The methods, ActivateNext and ActivatePrevious are used to move windows relative to the active window. Example: Windows("Book1").Activate ActiveCell: This property gives the active cell details for a particular window. The active cell is the cell that the cursor is on. Activepane: This gives the address of the visible area of the active pane. Example: MsgBox Windows(1).ActivePane.VisibleRange.Address ActiveSheet: This method gives the active sheet. Close: This method closes the window. FreezePanes: This property is used to freeze panes on the current cursor position. Example: ActiveWindow.FreezePanes = True NewWindow: This creates a new window based on the active window. Panes: This is a collection of all the panes within the window RangeSelection: This property returns the range which is selected. SelectedSheets: This collection returns all the sheets that are selected. Split: This property splits the current window into panes or sets it back to one pane Zoom: This sets the Zoom property of the window. Example: ActiveWindow.Zoom = 80 WorkSheet Object This object represents the actual worksheet that is being worked on. In the hierarchy of the Excel object model, it sits below the Workbook object.

Main Properties, Methods and Collections Calculate: This method calculates one particular worksheet, assuming that the calculation method has been set to manual. Example: Worksheets(1).Calculate

Page 9: VBA Quick Introduction

Comments: This is a collection of all the comments added to the selected worksheet. Delete: This method deletes a worksheet. Printout and PrintPreview: These methods allow to print out a particular worksheet or to preview the printing of it. Protect: This method protects a worksheet. A password, which is an optional parameter, can also be provided. Example: Worksheets("sheet2").Protect

Worksheets("sheet2").Protect ("apple") In the second Example, Password is set as “apple”.

Range: This is an important object under the workbook object and has been discussed in the section Range Object. SaveAs: This method saves the workbook under a different filename. Although it is part of the Worksheet object, it saves the entire workbook. Select: This method selects a particular Worksheet within a Workbook. UnProtect: This method unprotects a sheet. Password is required for sheets protected using a password. Visible: This property defines whether a worksheet can be seen or not. Range Object This object communicates with a range of cells or individual cells and makes changes in them. Without this object, multiple cells on a worksheet can not be changed at one time.

Main Properties, Methods and Collections Activate: This method activates a particular cell or range of cells to make them into the active cell or cells. For this to work, Sheet1 has to be the active worksheet. Example: Worksheets("sheet1").Range("a1").Activate Addcomment: This method adds a comment into the cell defined by the range. If this method is used on a cell already having comment, an error is encountered. This is applicable when only a single cell is selected using Range. Address: This property returns the address of a range. Example: MsgBox Worksheets("sheet2").Range("a3").Address The above example will return $A$3. BorderAround: This method draws a border around a group of cells or a single cell. Calculate: This method calculates a particular range specified, assuming that autocalculation is not set to On for the workbook Cells: This is a collection of cells within the range specified. Clear: This method clears the contents of the range of cells. Column and Row: These properties return the first column number or the first column row within the range defined. Example: MsgBox Worksheets("sheet2").Range("b3.d12").Column Columns and Rows:This returns the collection of rows and columns within the specified range. Copy and PasteSpecial: These methods copy and paste a range of cells. Example: Worksheets("sheet2").Range("f19.g20").Copy

Worksheets("sheet2").Range("h19").PasteSpecial

Page 10: VBA Quick Introduction

Replace: This method replaces a specified character found within the range with another one. Example: Worksheets("sheet2").Range("A1.B20").Replace "a", "b" Select: This method selects a range of cells specified in the code. Example: Worksheets("sheet1").Range("A19.B20").Select Text: This property returns the text in the cell of the range. The range can only be a single cell; otherwise, it generates an error. This property returns the data as text. Example: sName = Worksheets("sheetA").Range("A1").Text Value: This property is similar to Text but is read-write. Example: Worksheets("sheetA").Range("A2").Value = 10

Declarations: Constants and Variables Variable names can be constructed from letters and numbers, and the underscore character (_). The variable name must start with a letter and can be up to 255 characters in length. VBA keywords and VBA function names can not be used as a variable name. VBA allows implicit as well as explicit variable declaration. Variables can be created and used by simply using them. This is referred to as implicit variable declaration. If a variable is to be declared explicitly, a “dim” statement or one of its variations can be used. Example: Dim sName as String, iAge as Integer Although Implicit declaration is supported but should be avoided. Explicit code and variable declaration conveys more meaning and makes the code more precise. In addition, implicit variables are invariant data types. The problem with using invariant data types is that extra code must be added behind the scenes to determine the type of the data each time it is used. This extra decision code is added automatically, and in addition to conveying less meaning, it adds unnecessary overhead to execution time.

Page 11: VBA Quick Introduction

Option Explicit Explicit declaration can be forced using the statement “Option Explicit” at the top of the module as shown below:

Option Explicit only applies to the module it appears in. Each module requiring explicit declaration of variables must repeat the statement in its declaration section. When a module is run with explicit variable declaration, VBA will check for variables that have not been declared, highlight them and show an error message. Option Explicit also helps in picking the spelling mistakes which are very common in nature. Scope and Lifetime of Variables: There are two important concepts associated with variables:

1. The scope of variable defines the accessibility of the variable. 2. The lifetime of a variable defines how long that variable retains the value

assigned to it. The scope of a variable declared within a procedure is confined to the procedure the procedure under which it has been declared and the lifetime of a variable is the time taken for the procedure to run from the declaration statement to the end of the procedure. If a variable is declared using a “Static” statement, the lifetime of the variable is extended to the time that the workbook is open. A variable declared in the declaration section (at the top of the module) is referred to as module-level variable and its scope is the whole module and lifetime is the time for which the workbook is open. If a procedure declares a variable with the same name as a module level variable, the module level variable will not be visible to the procedure and will process its own procedure level variable.

Page 12: VBA Quick Introduction

Arrays Arrays are VBA variables that can hold more than one item of data. An array is declared by including parentheses after the array name. An integer is placed within the parentheses, defining the number of elements in the array. Example: Dim iNum(50) as Integer The number of elements in an array depends on the array base. The default base is zero, which means that the first data element in item is zero. The above declaration when used with zero base will declare an array of 51 elements, starting from iNum(0) to iNum(50). Alternatively, if “Option Base 1” is used in the declarations section at the top of a module, then the array are one based. Option Base can only be set to either 0 or 1. The above declaration when used with base one will declare an array of 50 elements, starting from iNum(1) to iNum(50). Arrays can use LBound (lower bound) and UBound (upper bound) functions to determine the lowest and highest index values. The lower bound and upper bound of an array can be declared independently of option base statement by explicitly declaring them. Example: Dim iNUm(5 To 15) as Integer Multi-Dimensional Array: VBA supports multidimensional arrays with up to 60 dimensions. Multidimensional arrays can be declared as follows: Dim iNum (a1 To a2, b1 To b2, ……, bh1 To bh2) as Integer The functions Ubound and Lbound has a second parameter to indicate which index it is referring to. If this parameter is left blank, the functions refer to the first index. The functions UBound and LBound can be used as follows with multidimensional arrays. Example: Dim iNum (1 To 5, 6 To 10, 13 To 20) as Integer Xyz = LBound(iNum, 2) ‘This will set Xyz = 6 Xyz = UBound(iNum, 3) ‘This will set Xyz = 20 Xyz = UBound(iNum) ‘This will set Xyz = 5 Dynamic Arrays Sometimes, the size of the array is not known at the time of declaration. An inefficient solution could be to declare an array big enough to hold the largest amount of data possible. VBA supports defining a dynamic array and re-dimensioning it when the procedure runs. The array is declared by leaving out the dimensions. Dim sName() as String The dimension can be declared at runtime with a ReDim statement, which can use variables to define the bounds of the indexes. Dim sName (iRows, iColumns) as String ReDim will initialize the array and destroy unless Preserve Keyword is used. Dim Preserve sName (minRow To maxRow, minCol To maxCol) as String

Page 13: VBA Quick Introduction

User Defined Data Types VBA also supports user defined data types and can be created by using the Type Keyword. This declaration has to be done in the declarations section of the module. A certain user defined data type, once declared in the declaration section in any module is accessible to all modules. The data type is automatically included in the pull down list within the VBA editor. Example: Type Employee sName as String cSalary as Currency iYear as Integer End Type Dim Emp1 as Employee Emp1.sName = “Amritanshu” Emp1.cSalary = 12345 Emp1.iYear = 2008

Page 14: VBA Quick Introduction

Constructs in VBA: Constructs in VBA can be divided broadly into two major categories:

• Decision making and,

• Loops Decision Making Programs usually have to make decisions according to data retrieved or input by the user. VBA supports two main structures for making decisions and carrying out alternative processing, represented by the IF and SELECT CASE statements. IF statement is more flexible but SELECT CASE is better when a single value has to be examined. IF Statement

IF comes in three forms: The IIF function, the one line IF statement and the block IF structure. IIF Syntax: Var1 = IIF(expression, Truepart, Falsepart) IIF function has three input arguments, the first (expression) is a logical test, the second (Truepart) is an expression that is evaluated if the test is true and the third (Falsepart) is an expression that is evaluated if the test is false. IIF always evaluates both the Truepart and Falsepart, even though it returns only one. It should be kept in mind that none of the two (Truepart or Falsepart) results in an error. Example: Function Max (num1 as Integer, Num2 as Integer) as Integer Max = IIF(Num1>Num2, Num1, Num2) End Function One Line IF Statement Syntax

If [condition] Then [Statement] Else [Statement] Example: If (Num1>Num2) Then Max = Num1 Else Min = Num2 Advantages of one line IF statement over IIF function are:

• Else section of one line IF is optional whereas both Falsepart and Truepart are mandatory for IIF function.

• IIF can only return a value to a single variable whereas IF can be used to assign values to different variables.

Block IF

Block IF can be used where multiple expressions are required to be evaluated when a test stands true. Syntax: If [Test1] Then Expression a1 Expression a2…….. ElseIf [Test2] Then Expression b1

Page 15: VBA Quick Introduction

Expression b2… Else Expression c1 Expression c2…… End If The scope of block If must be terminated with an End If statement. A block If may have an Else section or an ElseIf section. Block If can be nested, one inside the other. Proper indentation should be used to clearly specify the scope of each block. Select Case

Select Case statement provides a simple means to evaluate a specific variable and take action accordingly. It is easier to use as compared to nested IF block statements, if a single variable has to be evaluated multiple times. Syntax:

Select Case Product Case "Apples":

Price = 12.5 Unit = “KiloGram”

Case "Oranges": Price = 15 Unit = “Piece”

Case "Pears": Price = 18 Unit = “100 Grams”

Case "Mangoes": Price = 25 Unit = “KiloGram”

Case Else: Price = CVErr(xlErrNA) Unit = CVErr(xlErrNA)

End Select If product is not found, Price and Unit variable as assigned Excel error value of “#NA”. If there is only one statement for each case, then Colon (:) is optional. For using multiple statements for each Case statement, a colon must be placed between Case statements as shown above. Select Case can also handle ranges of numbers or text, as well as comparisons using the Keywords “IS” and “TO”. Example:

Function Fare(Age As Integer) As Variant Select Case Age

Case 0 To 3, Is > 65 Fare = 0

Case 4 To 15 Fare = 10

Page 16: VBA Quick Introduction

Case 16 To 65 Fare = 20

Case Else Fare = CVErr(xlErrNA)

End Select End Function

LOOPING VBA has four constructs that allow us to loop through the same code in an efficient way. They are the WHILE….WEND, DO….LOOP, FOR….NEXT and FOR EACHLOOP. The “While...Wend” loop places the test at the beginning, and consequently, the test will run 0 or more times. The “Do...Loop” can place the test at the beginning or the end. If the test is at the end then the loop will run at least once. The “For...Next” loop is typically used when a specific number of iterations are known, for example, looping over an array of 50 items. The “For Each” statement is used to process objects in a collection. WHILE….WEND

Syntax: While (Test)

Statement 1 … Statement n

Wend This will continue as long as the specified test result in true, it stops as soon as the test becomes false. DO…LOOP

The “Do Until” loop keeps looping until a specified condition is met. Often this means waiting for a variable to contain a particular value. When the condition is met, the loop stops, and the program continues executing on the next instruction after the loop. “Do ..While” statement can also be used so that while a certain condition is met the code will carry on looping. Example: Do Until (Num1>50) Num1 = Num1 + 1 Loop Do While(Num1<50) Num1 = Num1 + 1 Loop FOR…NEXT

The “For...Next” loop differs from the Do...Loop in two ways. It has a built-in counter that is automatically incremented each time the loop is executed and it is designed to execute until the counter exceeds a predefined value, rather than a user-specified logical test.

Page 17: VBA Quick Introduction

Syntax: For Var1 = n1 To n2 Step n3 Statement a1 Statement a2 … Next Var1 The Step option determines the increment value. By default, “For…Next” increments the counter by 1. Step may be set to any negative or positive integer. FOR EACH…NEXT

This loop is used when every member of a collection needs to be processed. Example: For Each aWorksheets in Worksheets aWorksheets.Name = Left(aWorksheets.Name, 2) Next The loop steps through all the members of the collection. During each pass a reference to the next member of the collection is assigned to the object variable aWorksheet.

Page 18: VBA Quick Introduction

Error Handling and Debugging in VBA Error Handlers: If an error is anticipated in a code, the situation can be dealt by tactical use of ‘On Error’ Keyword. ‘On Error’ can be used with ‘GoTo Label’, ‘Resume’, “Resume Next’ and ‘Resume Label’. Example: On Error Go To Label

This statement causes the execution to start from the Label if an error is encountered. This branches the execution to an arbitrary line number of text label followed by a colon.

Sub ErrorExample() Dim MyFile As String, Message As String Dim Answer As String On Error GoTo errorTrap Workbooks.Add MyFile = "C:\Data.xls" Kill MyFile ActiveWorkbook.SaveAs Filename:=MyFile ActiveWorkbook.Close Exit Sub errorTrap: Message = "Error No: = " & Err.Number & vbCr Message = Message & Err.Description & vbCr & vbCr Message = Message & "File does not exist" Answer = MsgBox(Message, vbInformation, "Error") Resume Next End Sub Description: In the above subroutine ErrorExample, an excel workbook is created and saved in “C:\” Drive as “Data.xls”. If the file already exists at the destination, it is deleted using the “Kill” command. However, if the file does not exist, the kill command will result in a fatal error and an entry will be made about the error in Err object. The in-built Err object contains information about run-time errors. When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. The command “GoTo errorTrap”, which follows the “On Error” command, specifies that if any error is encountered then go to the label used (errorTrap). Care should be taken to avoid execution of the error handling code when no error occurs. To ensure this the labels used with On Error should be preceded by “Exit Sub” like in the example shown above. The command “vbCr” is a newline feed command for message box. The command “Resume Next” will resume the execution of the program from the next line to the line at which error occurred. On Error Resume Next: On Error Resume Next can be used to ignore an error and continue execution with the next statement. This technique is used immediately preceding a statement that can pass or fail.

Page 19: VBA Quick Introduction

On Error Resume: This label can be used to try the same statement again if an error is encountered. On Error Resume Label: This statement causes errors to be ignored and execution to start where the Label has been declared. On Error GoTo 0: On Error Goto 0 disables error handlers in the current procedure. The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property or Resume Next statement within an error-handling routine. The Clear method can be used to explicitly reset Err.

ERR Object: Err is a Singleton Object that means there is only one in the entire application. The Err object contains the information about the most recent error. Included in this information is the error code, the origin of the error, a description about the error, and a link to a Help file document, if available. As it is an instance of a class, it has methods and properties. An error can be invoked in a code by using “Err.Raise”. An error can be cleared by using “Err.Clear”. DEBUGGGING

Using Debug.Print: The Debug object contains two methods, Print and Asset. Debug.Print accepts a string message and sends it to the Immediate window. Immediate Window can be accessed in VBE by View>Immediate Window or Ctrl + G. Debug.Print is useful in verifying the values of variables and tracing the progress of execution by suitably placing the method statement. Example: Sub TraceProgress() Dim iNum as Integer For iNum = 0 To 1000 Debug.Print “The code is executing the “ & iNum & “ loop” Next End Sub Using Debug.Assert Assert is designed to stop the execution if the test passed to the assert method fails. It can be used to verify whether a variable is not being set to unwanted value. Example: Sub CalcSpeed()

Dim distance As Integer, time As Double, speed As Double distance = InputBox("Enter the Distance travelled") time = InputBox("Enter the Time of journey") Debug.Assert time <> 0 speed = distance / time End Sub

Page 20: VBA Quick Introduction

In the above example, execution will stop if time = 0, that is when the test time<>0 results in false. DEBUGGING AND TESTING

A code might end up being conditionally erroneous and to track the root of the error, testing of the code is required. To facilitate smooth testing of codes, VBA has provided the following methods:

• Running the code from VBE: A code can be run/executed by pressing F5 or using the menu. If the code is bug free, the code will run in entirety.

• Stepping into the code: The Step Into feature is found in the VBE on the Debug menu. The shortcut for the Step Into feature is the F8 key. Step Into single steps over each line of code. If you press F8 on a method call then the debugger will step into that method. Step Into is labor-intensive process, but it permits can be used to check every line of code, line by line. Sub CallMultiply() Dim product as Integer

product = Multiply(2,3) End Sub Function Multiply(Num1 as Integer, Num2 as Integer) as Integer Multiply = Num1*Num2 End Function If a subroutine or function is called from within a subroutine and F8 is pressed, the execution will step into the sub or function called. Here, if F8 is pressed at “product = Multiply(2,3)”, the execution steps into the function Multiply and its first line is highlighted in yellow.

• Stepping Over: If we do not wish the execution to go into a subroutine which is bug free, Step Over can be used to execute sub or function called and return the debugger to the next line. The Shift+F8 combination is the shortcut for the Debug

➪StepOver behavior in the VBE.

• Step Out: If the code has stepped into a sub or function and it is wanted that the code should step out of that sub or function and return the debugger to the sub or function that called it, Step Out can be used. The Ctrl+Shift+F8 combination is

the shortcut for the Debug ➪StepOut behavior in the VBE.

• Run To Cursor: The debugger can be run until it reaches a specific line of code by using Run to Cursor option. . The Ctrl+ F8 combination is the shortcut for the

Debug ➪Run To Cursor behavior in the VBE.

• Set Next Statement: If it is required to debug after a specific line of code without executing the code in between, this technique can be used. All preceding lines of codes will be skipped and the debugger will jump to that specific line where the next statement has been declared. The Ctrl+ F9 combination is the shortcut for the

Debug ➪Set Next Statement behavior in the VBE. This feature is especially

useful as it can help skip lines of code that may make critical updates before being completely sure that preparation for the modifications is perfect.

Page 21: VBA Quick Introduction

• Show Next Statement: Debug ➪Set Next Statement can be used to automatically

position the cursor to the next line of code to be executed. The above functionality can be used to freely move along the code while in debug mode and avoid unnecessary keystrokes to be used while debugging. Using Breakpoints Breakpoints can be used to force the debugger to halt at the line with breakpoint. The F9

key toggles a breakpoint—Debug ➪Toggle Breakpoint—on an executable line of code. A

breakpoint is indicated by a red highlight on each line containing a breakpoint. During the course of a debugging session it is possible to set dozens of breakpoints. To quickly

clear all breakpoints, after finishing debugging, select Debug ➪Clear All Breakpoints.

Clear All Breakpoints can be invoked with the Ctrl+Shift+F9 key combination Using Watches The Debug menu contains the AddWatch, EditWatch (Ctrl+W), and Quick Watch (Shift+F9). Watch behavior can be invoked on a variable, object or expression and its

value can be watched in the Watches window. The Debug ➪AddWatch behavior permits

to add a variable, object, or expression to a modeless window. The Watches window is displayed while the code is running in the debug mode, and the watch expressions that are in scope are updated in the window as the program runs.

The AddWatch dialog box indicates the expression—context, variable, object, or expression—the context, which includes the procedure and module, and the watch type. The default watch type is just used to keep an eye on the changing value of the expression, but there is also the option of breaking when the expression evaluates to the equivalent of True or when the value changes. Using the watch to break on True or

Page 22: VBA Quick Introduction

changing values is a convenient way to permit your code to run without being interrupted until some desired condition is met. Another feature of the Watches window is the ability to drill down into complex objects. For example, if an object is placed in the Watches window and the [+] symbol is clicked to expand the watched object and drill down into that object’s current state, the current state of all the properties related to the object is shown. Like other expressions, the watched object’s state is updated as the state changes.

The basic information related to Watch can be edites using Debug ➪Edit Watch

behavior. Quick Watch

This behavior is invoked by selecting the expression and selecting Debug ➪Quick Watch

from the VBE menu or by shortcut key Shift + F9. Upon its use a quick watch dialogue box opens showing the value of the expression and the value. The dialogue box also has the option to Add the watch to watchlist or resume debugging by Cancel or ask for Help. As the Quick Watch dialog box is modal, execution is suspended while the dialog box is open and the dialog box window has to be closed to interact with other parts of Excel. Locals Window: The locals window is very similar to the watch window, the difference being that it contains all the variables in the current, or local scope. Immediate Window

The Immediate window (View ➪ImmediateWindow or the shortcut Ctrl+G) is an editor-

cum-interpreter. Commands, variables, objects, and code statements can be entered which get executed immediately. This can be used to test assumptions and alternatives immediately without running a lot of code.

A common task that can be performed in the immediate window is to print the value of a variable in the current context. The print command is the keyword Print or the symbol ?.A function can also be invoked to get the output under given arguments. However, a subroutine can not be called from the immediate window using a Print command. The

Page 23: VBA Quick Introduction

function has to be called with the instance of the class that defines the function. If the function were in the same class (module or sheet) then no object is required. With suitable use of all the debugging and error handling tools, almost bug free code can be developed.

User Forms UserForms play the role of a blank slate, a palette, upon which visual metaphors can be used to enable users to interact with the application in a structured way. Various controls can be added to UserForms by dragging and dropping tools from the Toolbox in VBE. The forms and controls that are added have associated methods, properties and events that can be used to facilitate interaction between user and code.

• A UserForm can be added in VBE using Insert>UserForm.

• To load the UserForm into memory, without making it visible, Load statement in used. Syntax: Load UserForm1

• The UserForm can be unloaded from the memory by using Unload statement. Syntax: Unload UserForm1

• To make a UserForm visible, Show method is used. When a Show method is used without loading the UserForm, the UserForm is loaded automatically. The default behavior of the Show method is to display the UserForm as a modal form. This means that the UserForm behaves like a dialog box maintaining the focus whether the form is hidden or unloaded. The user cannot interact with any other part of Excel until the UserForm is dispensed with. Syntax: UserForm1.Show

• To hide a UserForm, Hide method is used. Syntax: UserForm1.Hide

• Once the UserForm has been added in the project, various controls can be added to it by dragging and dropping controls from the standard toolbox. The visual properties related to the controls as well as to the forms can be modified using properties window to modify the visible appearance of form.

• The methods, properties and events associated with the controls and forms can be used for decision making, data entry and smooth direction of the code.

• A modeless UserForm does allow the user to activate worksheets, menus, and toolbars. It floats in the foreground until it is hidden or unloaded. Syntax: Call UserForm1 (vbModeless)

Example: An example has been included in the attached worksheet, the effect can be studied by using the form via sheet 2.

Page 24: VBA Quick Introduction

Interaction With Databases Using ADO

ActiveX Data Objects, or ADO for short, is Microsoft’s technology of choice for performing client-server data access between any data consumer (the client) and any data source (the server or provider). ADO is Microsoft’s universal data-access technology. ADO is designed to allow access to any kind of data source. ADO doesn’t actually access a data source directly. Instead, ADO is a data consumer that receives its data from a lower-level technology called OLE DB. OLE DB cannot be accessed directly using VBA, so ADO was designed to provide an interface that allows you to do so. ADO receives data from OLE DB providers. Most OLE DB providers are specific to a single type of data source. Each is designed to provide a common interface to whatever data its source may contain. One of the greatest strengths of ADO is that, regardless of the data source being accessed, the same set of commands is used. ADO’s Object model consists of five top-level objects, all of which can be created independently. They are:

• Connection Object

• Command Object

• Recordset Object

• Record Object

• Stream Object Record Object and Stream Object are not commonly used in Excel applications and are not discussed herein.

Connection Object

The connection object provides the pipeline between the application and the data source. The connection object is extremely flexible and in most cases this might be the only object that is used. In some cases, this object may not be created as the Command object and Recordset object can create a Connection object automatically if needed. It is advisable, from performance point of view, that if several queries are to be executed for the same source, only one connection should be used. Connection pooling is a feature provided by ADO preserves and reuses the same connection to the data sources rather

Page 25: VBA Quick Introduction

than creating new connection for each query. Connections can be reused for different queries as long as their connection strings are identical. ConnectionString Properties The ConnectionString property is used to provide ADO, and the OLE DB provider that you are using with the information required to connect to the data source. The connection string consists of a semicolon-delimited series of arguments in the form of "name=value;" pairs. Example: Dim adoCn as New ADODB.Connection Dim adoCmd as New ADODB.Command Dim adoRs as New AODB.Recordset adoCn.Provider = "sqloledb" ' Specify connection string on Open method.

sProviderStr = "Server=" & Range("wso_server").Value & ";Database=" & Range("wso_db").Value & ";UID=" & Range("wso_user").Value & ";Password=" & Range("wso_pwd").Value

adoCn.Open sProviderStr Set adoCmd = New ADODB.Command adoCmd.ActiveConnection = adoCn adoCmd .CommandText= “Select Name, Age, Gender, Salary from_ tblSalaryMaster” Set adoParam = adoCmd.CreateParameter(, adInteger, adParamInput, 5) adoParam.Value = 5 adoCmd.Parameters.Append adoParam Set adoParam = Nothing Set adoRs = adoCmd.Execute() RS2WS adoRs, Range(“A2”)

The provider argument tells ADO which OLEDB provider to use. This is an optional argument and if no argument is provided, ADO assumes the default argument of ODBC provider. Connection Timeout Property

The Connection class has a ConnectionTimeout property that specifies how long ADO will wait for a connection to complete before giving up and raising an error. The default value is 15 seconds. The value is in the unit of seconds. This is a read/write property and hence can be modified as follows: adoCn.ConnectionTimeOut = 30 State Property

The State property allows you to determine whether a connection is open, closed, connecting, or executing a command. The value will be a bit mask containing one or more of the following ObjectStateEnum constants defined in ADO:

• AdStateClosed: Means the connection is closed

• AdStateOpen: Means the connection is open

• AdStateConnecting: Means the Object is in the process of making a connection

• AdStateExecuting: Means the connection is executing a command Example: If (adoCn.State = ObjectStateEnum.adStateOpen) Then adoCn.Close

Page 26: VBA Quick Introduction

Connection Methods The Open Method

The Open method establishes a connection to a provider. Open accepts several optional parameters.If the ConectionString property has already been initialized then Open can be called with no arguments. If the ConnectionString is not initialized, then ConnectionString, UserID, Password etc can be passed as arguments. The Open method also supports Options:=adAsyncConnect, which allows the connection object to go off an open the connection in the background while the code continues to run. Example: adoCn.Open Options:=adAsyncConnect Execute Method

The Execute method runs the command text provided to the Execute method’s CommandText argument. Syntax for Action Query (all except Select) connection.Execute CommandText, [RecordsAffected], [Options] Syntax for Select Query Set Recordset = connection.Execute(CommandText, [RecordsAffected], [Options]) For Select Query, the execution is set to a recordset. Close Method

This method simply closes an open connection. The Close method requires no arguments. Syntax: Connection.Close Connection Object Collections The Connection Object has two collections: Errors and Properties. Errors Collection

The Errors collection contains a set of Error objects, each of which represents an OLE DBp provider-specific error (ADO itself generates runtime errors). The Errors collection can contain errors, warnings, and messages (generated by the T-SQL PRINT statement, for instance). The Errors collection is very helpful in providing extra detail when something in your ADO code has malfunctioned. The Errors collection can be seen by dumping its values by using Debug.Print. Properties Collection

The Properties collection contains provider-specific, or extended properties, for the Connection object. RecorSet Object The Recordset object serves as a container for the records and fields returned from a SELECT statement executed against a data source. RecorSet Object Properties

ActiveCOnnection Property

This property returns an object reference to the Connection object being used by the recordset. Syntax: Set Recordset.ActiveConnection = adoCn

Page 27: VBA Quick Introduction

BOF and EOF Properties

These properties indicate whether the record pointer of the Recordset object is positioned before the first record in the recordset (BOF, or beginning of file) or after the last record in the recordset (EOF, or end of file). If the recordset is empty, both BOF and EOF will be True. Example:

If (adoRs.EOF And adoRs.BOF) Then Debug.Print "There is no data"

End If There is no difference between an empty recordset and a closed recordset. If a query is executed that returns no data, ADO will present a perfectly valid open recordset but containing no data. Hence, recordset should be validated to ensure the presence of data before performing action on it. Filter Property

The Filter property allows to filter an open recordset so that only records that meet the specified condition are visible, acting like an additional WHERE predicate on the recordset. This property can be set to a string that specifies the condition to be placed on the records, or to one of the FilterGroupEnum constants. Multiple filters can be placed and the result would be the records that meet all the filters. Logical AND and OR can be used to join the filters. Example: adoRs.Filter =”Name = ‘Amritanshu’” OR “Post = ‘Asscoiate’” State Property

The Recordset.State property has the same possible values as the Connection.State property. Recordset Methods Open Method

The Open method retrieves the data and makes it accessible to the coed. Syntax: Call Recordset.Open( Source, ActiveConnection, CursorType, LockType, Options) Close Method

The Close method closes the Recordset object. This does not free the memory used by the recordset, for freeing up the memory, recordset must be set to Nothing. Methods For Moving The Cursor When a recordset is first opened the current record pointer is positioned on the first record in the recordset. The Move methods are used to navigate through the records in an open recordset. The basic navigation methods are enlisted below:

• MoveFirst: Positions the cursor to the first record of the recordset.

• MovePrevious: Positions the cursor to the prior record of the recordset.

• MoveNext: Positions the cursor to the next record in the recordset.

• MoveLast: Positions the Cursor to the laste record in the recordset.

Page 28: VBA Quick Introduction

Command Class

The Command class is an object-oriented representation of an instruction to a provider. Command Properties ActiveConnection Property

The ActiveConnection property represents a connection object whether explicitly initialized or implicitly created via a connection string. CommandText Property

The CommandText property is used to set the string value that will be used by the data provider to figure out what information to fill the recordset with. CommadnType Property

The CommandType property represents a hint to the provider indicating the meaning of theCommandText property. If the CommandText represents a stored procedure then the CommandType needs to be CommandTypeEnum.adStoredProcedure. If the CommandText r presents a persisted recordset file name then the CommandType needs to be CommandTypeEnum.adCmdFile. Command Methods CreateParameter Method

This method is used to manually create Parameter objects that can then be added to the Command.Parameters collection. Syntax:

CreateParameter([Name As String], _ [Type As DataTypeEnum = adEmpty], _ [Direction As ParameterDirectionEnum = adParamInput], _ [Size As ADO_LONGPTR], [Value]) As Parameter

Execute Method

This method executes the command text in the Command object’s CommandText property.It has similar syntax as Execute method of Connection Object.