Excel VBA Intro
Excel VBA Intro
Table of Contents
INTRODUCTION ................................................................................................................... 1 VISUAL BASIC EDITOR .......................................................................................................... 2 VISUAL BASIC FOR APPLICATIONS (50 MINS)................................................................. 2 THE PROJECT EXPLORER ........................................................................................... 4 THE PROPERTIES WINDOW ....................................................................................... 4 THE CODE WINDOW ................................................................................................ 4 OBJECT PROGRAMMING ....................................................................................................... 4 WHAT IS OBJECT PROGRAMMING?.............................................................................. 4 THE PROPERTIES WINDOW ....................................................................................... 4 MODIFYING PROPERTIES........................................................................................... 5 USING THE CODE WINDOW....................................................................................... 6 COLOURS IN THE CODE WINDOW ................................................................................ 7 USING METHODS .................................................................................................... 7 USING EVENTS........................................................................................................ 8 OBJECT-ORIENTATED PROGRAMMING OVERVIEW ........................................................... 9 THE OBJECT BROWSER ........................................................................................... 11 UNIT SUMMARY .................................................................................................... 12 PROGRAMMING BASICS ...................................................................................................... 14 DATA 14 DATA TYPES ......................................................................................................... 14 VARIABLES ........................................................................................................... 15 IMPLICIT DECLARATION........................................................................................... 15 EXPLICIT DECLARATION........................................................................................... 16 CONSTANTS.......................................................................................................... 16 EXPRESSIONS ........................................................................................................ 17 OPERATORS ......................................................................................................... 17 THE CELLS OBJECT ................................................................................................. 17 FUNCTIONS .......................................................................................................... 18 USER INTERACTION FUNCTIONS ................................................................................ 18 CONCATENATING TEXT............................................................................................ 19 OBJECT VARIABLES ................................................................................................ 20
-i -
SCOPE OF VARIABLES ............................................................................................. 21 DECLARATIONS SECTION ......................................................................................... 21 TYPES OF SCOPE.................................................................................................... 21 SCOPE OF PROCEDURES .......................................................................................... 22 PROCEDURE SCOPES ............................................................................................... 22 CALLING A SUB PROCEDURE ..................................................................................... 23 FUNCTION PROCEDURES ......................................................................................... 24 CALLING FUNCTION PROCEDURES.......................................................................................... 25 CALL A FUNCTION FROM CODE................................................................................. 25 CALL A FUNCTION USING INSERT FUNCTION DIALOG BOX ................................................ 25 CONTROL STRUCTURES ....................................................................................................... 28 DECISION STRUCTURES ........................................................................................... 28 IF...THEN...ELSE CONSTRUCTION ............................................................................. 28 IF THEN STATEMENT ............................................................................................... 30 IF THEN ELSE STATEMENT ........................................................................................ 31 IF THEN ELSEIF ELSE STATEMENT ............................................................................... 31 SELECT CASE STATEMENT ........................................................................................ 32 LOOP STRUCTURES ................................................................................................ 33 THE FOR NEXT LOOP ........................................................................................... 33 THE FOR EACH NEXT LOOP ................................................................................... 35 DOLOOP STATEMENTS......................................................................................... 36 DO WHILE LOOP ................................................................................................... 36 CUSTOM DIALOG BOXES ..................................................................................................... 38 USER FORMS ........................................................................................................ 38 DESIGNING THE USER FORM.................................................................................... 38 NAMING OBJECTS .................................................................................................. 38 USER FORM INTERFACE .......................................................................................... 39 ADDING A USER FORM ........................................................................................... 39 USING CONTROLS.................................................................................................. 40 ADDING USER FORMS ............................................................................................. 41 EVENTS 44 EVENT HANDLING CODE .......................................................................................... 45 DATA VALIDATION................................................................................................. 47 FORM CHECK LIST ................................................................................................. 48
DEBUGGING AND ERROR HANDLING ..................................................................................... 49 ERRORS 49 ERROR TYPES........................................................................................................ 49 ERROR TYPES........................................................................................................ 50 DEBUGGING ......................................................................................................... 51 DEBUGGING TOOLS ................................................................................................ 51 BREAK MODE AND BREAKPOINT ............................................................................... 51 SETTING A BREAKPOINT .......................................................................................... 52 WATCH EXPRESSIONS............................................................................................. 54 STEPPING THROUGH CODE....................................................................................... 55 USING THE STEP INTO ........................................................................................................ 56 DELETE WATCH EXPRESSIONS ................................................................................... 56 THE IMMEDIATE WINDOW ...................................................................................... 57 WORKING WITH THE INTERMEDIATE WINDOW............................................................. 57 LOCALS WINDOW.................................................................................................. 59 ERROR-HANDLING ................................................................................................. 60 THE ON ERROR STATEMENT .................................................................................... 60 THE ON ERROR GOTO 0.......................................................................................... 60 ON ERROR RESUME NEXT ....................................................................................... 60 ON ERROR GOTO <LABEL>:..................................................................................... 61 ENABLED AND ACTIVE ERROR HANDLERS ................................................................... 61 ERROR HANDLING BLOCKS AND ON ERROR GOTO ....................................................... 61 THE RESUME STATEMENT ....................................................................................... 62 ERROR HANDLING WITH MULTIPLE PROCEDURES ........................................................ 63 A NOTE OF CAUTION ............................................................................................. 64 THE EXCEL OBJECT MODEL ................................................................................................. 65 OBJECT REFERENCES: CELLS, SHEETS AND WORKBOOKS ................................................ 65 SQUARE BRACKETS................................................................................................. 66 WITHEND WITH ................................................................................................ 66 APPENDIX A HOW TO SPEED UP CODE ................................................................................... 68 PREVENTING CALCULATION WHILE EXECUTING CODE: .................................................... 69 SPEEDING UP CODE IF YOU HAVE WORKSHEET OR WORKBOOK EVENTS. ........................... 69 INSERTING A RELATIVE FORMULA INTO A RANGE OF CELLS: ............................................. 69 APPENDIX B SAMPLE CODE ................................................................................................. 71 Page iii
COPY DATA TO ANOTHER WORK SHEET ..................................................................... 71 COPY DATA TO ANOTHER WORK BOOK...................................................................... 74 FILTERING DATA.................................................................................................... 77 FILTER THE FIRST FIELD OF THE TABLE/LIST FOR THE INPUTBOX VALUE .............................. 77 ACTIVECELL VALUE AS CRITERIA ................................................................................ 78 FILTER THE FIRST FIELD OF THE TABLE/LIST FOR THE TEXT VALUE OF RANGE("D1") ............. 79 IN THE EXAMPLE I FILTER ON THE FIRST COLUMN FOR THE NETHERLANDS .......................... 82 MACRO TO CLEAR THE FILTER IN THE TABLE/LIST ......................................................... 83 PRINT ODD AND EVEN PAGES ................................................................................... 85 INSERT PAGE BREAKS EVERY ? ROWS ......................................................................... 86
Page v
Introduction
This manual is the copyright of MTC Training Solutions Limited. A number of individual trainers have contributed to this product through "work for hire". The Copyright, Designs and Patents Act 1988 provides that if a copyrighted work is made by an employee in the course of that employment, the copyright is automatically owned by the employer.
Introduction
All the Office 2010 applications allow users to create their own Visual Basic code to carry out particular actions in the Application. But why do you need to do this given that each application comes with a host of powerful features? The answer lies in how these features are used. VBA is present in Word 2010, Excel 2010, PowerPoint 2010, Outlook 2010, Project 2010 and Publisher 2010. Access 2010 and Visio 2010 create VBA code a little differently and will be covered in other Courses. The purpose of this course is to give you the fundamental tools to start down the path of VBA programming in Microsoft Excel and to encourage you to further your knowledge beyond basic functionality; maybe you will use what you learn as the basis to explore VBA in other applications. Whatever path you decide to take the basic VBA for excel will give you the tools at your fingertips to explore further.
Page 1
VBA Terminology
Before you start coding in VBA you need to be familiar with some key terms associated with it. The following table describes some of those terms. Object VBA object is something like a tool or a thing that has certain functions and properties, and can contain data. For example, an Excel Worksheet is an object, cell in a worksheet is an object, range of cells is an object, font of a cell is an object, a command button is an object, and a text box is an object and more. Each VBA object has its own properties that control its appearance. When we talk about range as an object typical properties are:Column Width, Row Height, Font, Text, Value, Formula, Borders Method While most objects only provide characteristics to describe them, other objects can perform actions. For example, a house can be used to protect people when it is raining outside. In computer programming, an action that an object can perform is referred to as method. A procedure is a section of code created to carry an assignment, separate from a spread sheet, whose action can be used to complement a spread sheet. You cre6ate the procedure by writing code. One of the advantages of a procedure is that, once it exists, you can access it when necessary and
Property
Procedure
Page 2
A line of text within a procedure, that you can use to describe each line of code or the entire procedure. To comment a line out place an apostrophe at the beginning of the line. The comment will turn green. Is a file that you can write and edit blocks of code and other VBA code.
Module
Properties Window
Page 3
Object Programming
Object Programming
What is object programming?
In excel objects have certain properties, methods, and events. Properties control the appearance and other attributes of an object. Methods are built in procedures that you use to perform specific actions on an object. Events are actions such as mouse click double click or open and close a workbook. Most objects in VBA have events associated with them. For example a worksheet object has an event called activate.
Page 4
Object Programming
Modifying Properties
EXERCISE 1 In the project explorer verify that sheet1 (sheet1) is selected In the properties window double click name Edit the value to read purchase sales 2012 Press the Enter Button In the project explorer the worksheet name changes to purchase sales 2012 EXERCISE 2 in the properties window, double click standardwidth enter 12 Select to view the changes Point and Click between C & D a screen tip appears showing as 12
Page 5
Object Programming
The code window contains two lists, the object list and the procedure list. The object list displays all objects associated with the current module. The procedures list displays all the procedures in the current module or all the events of the object selected in the object list, the definition of the objects default procedure appears in the code window, for example if you select the object worksheet from the object list the following code appears in the window. Private Sub Worksheet_SelectionChange(ByVal Target As Range) End Sub The code indicates that Worksheet_SelectionChangeis the defaultevent of the worksheet object. This event occurs when the user selects a cell in the worksheet. Code written within this procedure will execute every time this event occurs. For example if you write code within this event procedure to display a specific message that message will appear every time you select a different cell. Type in the following to give it a try: MsgBox "you selected another cell" The general syntax for changing object properties through code is Object.property = Value EXAMPLE Sub change_name() Worksheets("sheet1").Name = "myworksheet" End Sub
Page 6
Object Programming
Using Methods
Every object can perform certain actions are defined by methods. Some methods need a value as input to complete their actions. For example, the open method of the workbook object takes a file name as input so it knows specifically what workbook to open. The input value is called an argument. An argument is a variable, constant or expression that provides additional information to a method, so that it can execute properly. To use a method in VBA code, you would use the following syntax. Object.method argument1, argument2, argument3 For example to protect worksheet1 with the password My Password, you can use the following code. Sheet1.protect mypassword EXERCISE 1 Add password protection to sheet 2 in a work book Sub mypasson() Sheet2.protect "mypassword" End Sub EXERCISE 2 Remove password protection to sheet 2 in a work book Sub mypassoff() Sheet2.Unprotect "mypassword" End Sub
Page 7
Object Programming
Using Events
You might want a procedure to run in response to a specific user action. You can do this by associating the code with an event object. This association is created using an event procedure. An event procedure is a code that is executed when an event occurs. For example, you can write code for the activate event of a worksheet to display a message indicating that you cannot change the data in the worksheet this procedure will activate when the user activates the worksheet. To program an event, double click the object to display a code window. Select an event from the procedure list and enter the code, the code will run automatically when a user triggers the event for that procedure.
EXERCISE Switch to the VBE Window In the project explorer verify that sheet3 is selected In the Code window, from the object list, select Worksheet (left)as shown above from the procedures list select Activate (right) Type the following: Sheet3.protect password MSGBOX (protected Worksheet. You cannot edit the data in the list.) Switch to excel Click on sheet3 to see the results
Page 8
Object Programming
Object Properties Make Model Colour Year Price Methods Start Drive Park Events On-start On-Parked On-Brake
Page 9
Object Programming
Using Buttons
The following procedure shows you how to add a button to the worksheet and assign code to that button. From the ribbon bar navigate to the developers tab, from the controls group select insert then click on the button icon. Draw the button to the size required. Next the macros dialog box opens, in the macro name box type in calculate, next click on new. Insert the code below in the code window. Sub Calculate() ActiveCell.FormulaR1C1 = "=Product(rc[-2]:rc[-1])" End Sub The code when executed adds two numbers to the left of a highlighted cell. Later on we will look at the looping stamen to automatically add up all values in the columns.
Page 10
Object Programming
The various elements in the object browser are: Project/Library list shows the names of all the projects and object librarys Search Text Box, accepts text strings and searches for information related to the text typed in. Search results shows the results of the information typed into the search text box Classes list shows the classes that are available depending on what has been selected from the project library list. Members of list, shows the methods and properties that belong to a particular object. Details Pane shows the definition and syntax of a selected method, property or event.
Page 11
Object Programming
Unit summary
In this unit you have learnt that VBA is a programming language been introduced to the Visual basic Editor, Terminology use in VBA and gained an understanding of how objects, properties, methods and events play a role in Object-orientated programming. You have learnt how to modify properties and use methods by using the code window, you also learned how to associate code to an event, and finally in this section you added a button to execute some VBA code. In the last part of this section we looked at how the object browser worked, familiarised ourselves with the interface and icon sets and performed a search to find out information about properties and methods.
Page 12
Object Programming
Notes:
Page 13
Programming Basics
Programming Basics
Data
Programs receive data as input then process that data to generate output, a good example of this is a calculator where you input numbers, instruct it which operator to use and it then returns an output as the answer. When inputting data the program uses a temporary storage space called a variable, the variable consists of a name and data type. The name is used to identify itself in the program and the data type indicates the type of data to be stored. In VBA its not mandatory to specify the data type if you dont it will assign a type called variant, however specifying data types makes the code run more efficiently.
Data Types
Type Byte Integer Long Single Storage 1 byte 2 bytes 4 bytes 4 bytes Range of Values 0 to 255 -32,768 to 32,767 -2,147,483,648 to 2,147,483,648 -3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E+38 for positive values. -1.79769313486232e+308 to -4.94065645841247E-324 for negative values 4.94065645841247E-324 to 1.79769313486232e+308 for positive values. -922,337,203,685,477.5808 to 922,337,203,685,477.5807 +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use +/- 7.9228162514264337593543950335 (28 decimal places). 1 to 65,400 characters
Double
8 bytes
Length + 10 0 to 2 billion characters bytes 8 bytes 2 bytes 4 bytes January 1, 100 to December 31, 9999 True or False Any embedded object Any value as large as Double Same as variable-length string
Page 14
Programming Basics
Variables
We have established that variables are used in VBA to store data and the name given to it uniquely identifies the variable in the computer memory. For example in a procedure that calculates a commission value, you would create a variable to contain that value. The process of defining a variable and its data type is called declaration; there are two types of declaration in VBA either implicitly or explicitly.
Implicit Declaration
You can use a variable without declaring it. This is called implicit declaration, consider the following code. Answer = 100 + 100 In the code above we have a variable called Answer this holds the sum of the two answers.
Programming Basics
Explicit Declaration
As you have discovered implicit declarations are open to errors in the code, to prevent errors and control the type of variable used we need to set an explicit Declaration. To make sure this action takes place type Option Explicit at the top of the code window as shown below. With your cursor inside the code press F5 to run the code as you can see from the dialog box we get a compile error complaining the variable is not found.
To make this code run we have to declare the variables add the following code line to the sub routine. Dim answer As Integer the code will now run to display the correct result. You can declare more than one variable at a time, for example Employee surname and salary amount as. Dim Salary_ammount as Double, Employee_name as string
Constants
A constant is a special type of variable that holds static data Tax rates commission rates and scientific constants are good uses for this variable to be used. To declare a constant use following syntax const <constant_name> = Value, for example setting the current vat rate as a constant may be written as Const VAT=0.20 Option Explicit Const VAT = 0.2 Sub calc() Dim answer As Integer Answer = (100 + 100) * VAT MsgBox (answer) End Sub Type in the code above this will result in 40 being displayed in the dialog box.
Page 16
Programming Basics
Expressions
An expression is a combination of operators, constants, procedures and names of controls and properties that is evaluated to obtain a result. When you use an expression in code it returns a value in one of the data types provided by VBA.
Operators
Operators are arithmetic symbols Arithmetic Operators + / * Addition Subtraction Division Multiplication Comparison Operators < > = <> Less than Great than Equal to Not equal to
A comparison operator returns a Boolean value because the result of any comparison is always true or false
Page 17
Programming Basics
Functions
If you have got to the stage of learning VBA then you will be proficient already in excel and would have used many of the inbuilt functions, functions always return results.
Page 18
Programming Basics
Concatenating text
You can use the message box function to display text along with the value stored in a variable. To combine variables with text you can use the concatenation operator ampersand (&). The general syntax for using the concatenation operator ampersand is: Msgbox (message_text &<variable_name> For example to display the message the amount is, along with the value that is stored in the variable amount, the code is: Msgbox (the amount is:& amount) Type in the text below in the code window Sub join() Dim Amount As Integer Amount = InputBox("enter a value") MsgBox "The Amount is:" & "" & amount End Sub The code above takes the value you enter in an input box, then displays that as The amount is 90 that is on the assumption you have typed 90 into the input box. Try typing in the code below comment out each line to describe what it does. Sub usingfunctions() Dim saleseast As Integer, saleswest As Integer, sum As Integer MsgBox "please enter whole numbers only" saleseast = InputBox("enter the total sales for the east") saleswest = InputBox("enter the total sales for the west") sum = saleseast + saleswest Cells(2, 4).Value = sum MsgBox "total sales for east and West: " & sum End Sub
Page 19
Programming Basics
Object Variables
In another example of a variable we can define an object variable in the example shown we are going to change the colour of the tab colour of two worksheets one to red and one to green, using object variables is discussed in depth in a later course.
Example 1 using a variable Sub changewkstabcolour () Dim wks As Worksheet Set wks = ThisWorkbook.Worksheets ("sales2011") wks.Tab.Color = vbRed Set wks = ThisWorkbook.Worksheets ("sales2012") wks.Tab.Color = vbGreen End Sub
The code above sets variable WKS as a worksheet object, worksheets are a member of the workbook family, and inside the parentheses we define the worksheet name. The property of the tab is changed by referencing the object variable and setting the property to the appropriate colour.
Example 2 define the sheet to change Sub changetabsales () ThisWorkbook.Worksheets ("sales").Tab.Color = vbBlue ThisWorkbook.Worksheets ("sales2011").Tab.Color = vbGreen ThisWorkbook.Worksheets ("sales2012").Tab.Color = vbRed End Sub
Example 3 change the active worksheet Sub changecol () Sheets (ActiveSheet.Name).Select ActiveWorkbook.Sheets (ActiveSheet.Name).Tab.ColorIndex = 21 End Sub
Page 20
Programming Basics
Scope of Variables
Having set up variables it may become apparent that you need to use it in more than one procedure, rather than copy to each individual module we can broaden its scope or put another way its usability. The accessibility or scope is determined where the variable has been declared.
Declarations Section
The top of the code window includes a declaration section; variables placed here can be used by all procedures within the module remember option explicit is also set in this area.
Types of Scope
Three types of scope are available in VBA as already stated the scope of a variable is determined by the way you declare it. Procedure-level, when you declare a variable within a procedure it is not accessible outside of the procedure. A procedure level variable is only available within the procedure it is written. Private module-Level, when declaring a variable in the declaration section of a module using Dim or Private keyword the variable is known as a private module-level variable, the variable can be used by any procedure within the module but cannot be accessed by a procedure outside the module. Public Module Level, when a variable is declared in the declaration section with the prefix keyword public, the variable is called a public module-level variable these variables can be called from any procedure or module.
Page 21
Programming Basics
Scope of Procedures
You may have a procedure that performs a general function like multiplying the value of two numbers; this procedure can be included in different modules by giving it the relevant scope. You can also specify a type for the procedure it can be one of the following, Sub, function or property function procedure is similar to a sub function but whereas the sub procedure executes code the function procedure returns a value.
Procedure scopes
The general syntax that determines the procedure scope is as follows Private/Public sub <procedure name>() <Procedure Body> End Sub Understanding the syntax Public indicates that the procedure can be used in different modules . Private indicates the procedure can only be used in the current Module. Sub / End Sub the start and the end of the procedure. <Procedure name>denotes the name of the procedure, you must give a unique name and it must not be the same as any of the VBA Keywords. <Procedure Body>, denotes the code for the procedure. A procedure can have one or more statements that are executed sequentially.
Page 22
Programming Basics
Public Function CalculateSalesTax() As Currency 'CalculateSalesTax = Cells(5th row, 4th column)=D5.Value * 0.08 CalculateSalesTax = Cells(5, 4).Value * 0.08 End Function
This is the function that you run in turn it calls the information from above, calculatesalestax takes the value and multiply it by .08 this information is then stored in the variable ST. then the contents of cell D5 are added to the Result of ST Public Sub CallFunc() Dim ST As Currency 'Set st as a currency variable 'cell D5 value = D5 value + ST 'st is the results of a public function calculate sales tax ST = CalculateSalesTax() Cells(5, 5).Value = Cells(5, 4).Value + ST End Sub
Page 23
Programming Basics
Function procedures
Similar to sub procedures in the way that are written but a function returns a value. The value that the function produces is stored in a predefined variable. The scope of the function will be either private or public. General Function Syntax: Function <procedureName)(variables) as data type <Procedure Body> End Function Example Function: In excel there is no function called mpg below we have created that function, inside the brackets we have created three variables , line 2 of the code indicates the way the mpg function uses those variables. Remember the rules of BODMAS still apply. Function mpg (start_miles, End_miles, Fuel) As Integer mpg = (End_miles - start_miles) / Fuel End Function Syntax Components Function and End function specify the start and finish of the function procedure Function <procedure Name>, this gives the function its name, the name has to be unique and cannot be a VBA keyword. As <data type>. Though optional if not declared the variables are set to variant remember we said earlier code is more efficient when specified. <Procedure Body> the lines of code within the function that make up the function and that are executed in sequential steps. Remember you can also add a function through the add procedure dialog box, you make your selections and the correct deceleration is added to the module when you click ok
Page 24
Page 25
This launches the insert dialog box on the or select a category drop down box select user defined as shown below, in the select function pane you should see MPG select and click ok.
Next the input function arguments dialog box for MPG opens enter the cell references for start_miles, end_miles and fuel_used as shown below, click OK to complete.
Page 26
Notes:
Page 27
Control Structures
Control Structures
Decision Structures
Decision structures allow the program to execute various procedures dependant on an outcome if a condition is met run one procedure if not run an alternative procedure, it is possible to run nested decision structures within VBA using the correct syntax.
If...Then...Else Construction
If...Then...Else constructions allow you to test for one or more conditions and run one or more statements depending on each condition. You can test conditions and take actions in the following ways: Run one or more statements if a condition is True Run one or more statements if a condition is False Run some statements if a condition is True and others if it is False Test an additional condition if a prior condition is False
The control structure that offers all these possibilities is the If...Then...Else Statement in (VBA). You can use a single-line version if you have just one test and one statement to run. If you have a more complex set of conditions and actions, you can use the multipleline version.
Sub test () If condition [Then] [statements] [ElseIf elseifcondition [Then ] [ elseifstatements ] ] [ Else [ elsestatements ] ] End If -orIf condition Then [ statements ] [ Else [ elsestatements ] ]
End sub
Page 28
Control Structures
Syntax property
Condition Required. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to Boolean. Then Required in the single-line form, optional in the multiple-line form. Statements Optional. One or more statements following If...Then that are executed if condition evaluates to True. Elseifcondition Required if ElseIf is present. Expression. Must evaluate to True or False, or to a data type that is implicitly convertible to Boolean. Elseifstatements Optional. One or more statements following ElseIf...Then that are executed if elseifcondition evaluates to True. Elsestatements Optional. One or more statements that are executed if no previous condition or elseifcondition expression evaluates to True. End If Terminates the If...Then...Else block.
Page 29
Control Structures
If then statement
In this procedure we check a cell reference to check to see if the vale is greater than 100 if the cell evaluates greater than 100 the function is deemed as true and places the message very high mpg in cell E4 at the end if it breaks out and continues to run the remainder of the procedure, in this case places a value in cell G4
Example 1 Sub test1() If Cells (4, 5).Value > 100 then Cells (4, 6).Value = "Very high MPG" End If Cells (4, 7).Value = 200 End Sub
In this procedure two variables have been set score and grade score is = to value of cell A1, when run this procedure checks the value of cell A1 if the value is greater than the result is passed. Otherwise the cell stays empty
Example 2 Sub test2() Dim score As Integer, grade As String score = Range("A1").Value If score >= 60 Then grade = "passed" Range("B1").Value = grade End Sub
Page 30
Control Structures
Page 31
Control Structures
Page 32
Control Structures
Loop Structures
You use loop structures such as for next and for each next when you want to run a specific block of text repeatedly. Use one of two loop structures depending on the number of iterations that are required. Fixed iterationThis runs a set of statements for a predetermined number of times.Example For next loop Indefinite Iterationthis runs a set of statement until a defined condition is met. Example Do while loop
Example 1 Sub count() Dim count As Integer For count = 1 To 3 'this adds 1+2+3 Sum = Sum + count Next count 'places answer in a cell Cells(2, 2).Value = "the sum of the amount counts " & Sum 'you could use this if the value added to a worksheet is not visible to the user MsgBox ("the sum of the amount counts " & Sum) End Sub
Page 33
Control Structures
Example 2 Next we consider a nested if function and how we can convert it into code. =IF(A1<500,A1*0,IF(A1<=1000,A1*10%,A1*30%)) Sub count2() Dim count As Integer For count = 1 To 20 totalsales = Cells(count, 1).Value If totalsales >= 500 Then commisionamnt = totalsales * 0.1 ElseIf totalsales > 1000 Then commisionamnt = totalsales * 0.3 Else commisionamnt = totalsales * 0 End If Cells(count, 2).Value = commisionamnt Next count End Sub
Page 34
Control Structures
Example 1 In this example we set a variable as cell setting it to range Sub ShowValue() Dim cell As Range For Each cell In Selection MsgBox cell.Value Next End Sub
Example 2 In this exercise if a cell has a number in the range A1:A50 the procedure will Double the cell value, if it contains a number,otherwise clear the cell. Sub ForEachCollectionLoop2() For Each cell In Range("A1:G50") If IsNumeric(cell) Then cell.Value = cell.Value * 2 Else cell.Clear End If Next End Sub
Page 35
Control Structures
Example 2 Sub DoLoops2() x = 10 Do x = x + 10 MsgBox x Loop While x < 40 End Sub Page 36
Excel VBA Intro You can conditionally break out of a Do...Loop using Exit Do.
Control Structures
Save your file before testing the code. It is very easy to get stuck in a conditional loop. You must try to terminate the procedure if you are stuck. Press the ESCAPE key. If this fails, try CTRL and BREAK together. It's bad news after this, CTRL+ALT+DELETE.
Page 37
Naming objects
It is awkward having to use the default object names when you are completing the event procedures for each control; is the OK button CommandButton1 or is it CommandButton2? Follow the published standard conventions for Control names, add the three-character lower case prefix to your names and you will never have any problems identifying your control objects in code.
Ob
Check Box Combo Box Command Button Frame Label List Box Option Button Text Box Toggle Button User Form
Prefix
chk cbo cmd Fra lbl Lst opt txt Tog frm
Page 38
Page 39
Using Controls
Control Name Label Text Box CommandButton ListBox CheckBox Optionbutton ComboBox Description Displays a text label on a form Accepts data from users Performs actions such as saving data User can select from a list of values Yes or no true or false Represents a single option in a group Displays a list of values, the user can select or add to the combo box list.
Page 40
In the example above you will create a user form to enter the employee name, their Department from a list enter their earnings and add two controls one to enter the data and one to close the form. Switch from the excel view to the visual basic editor, from the insert menu select user form. The screen will now look as shown below. If the toolbox is not displayed from the menu bar select view toolbox.
Click the
and draw the label box as shown resize the label as shown below
Page 41
Before we go any further click on the form navigate to the form propertys box in name type Employeeinfo
icon
Change the properties of the name to read txtempnamenow add a further label below employee name, change the properties in caption to Department. Now we are going to add a List Box click on the employee name input box. To show as below. icon add the list box below
Next change the name property to lstempdepartment, locate RowSourceenter the following details E4:E10, the list Box will be populated from this data Range. Next add one more label rename the caption to Earnings, add a text box change the name property to txtempearnings.
Page 42
Two more buttons to add these are to be command buttons lay out as shown below.
Now we shall finish it off navigate to the properties of the form in the caption box type the following. Employee Information now for the commandButton1 in the properties change the caption to Enter Data change the name property to CmdAdd now for the commandButton2 in the properties change the caption to Close change the name property to CmdClose your form should now look like the one below.
We have now created our user form click the save button to update and save your work In the next section we will look at events and how to transfer data from the user form to the excel data sheet.
Page 43
Events
VBA is based around event driven programming. In other words the code doesnt follow a predetermined path, instead it responds to events that a user or condition that occurs. For example the click of a button generates an event, the on_click event. Procedures are executed when an event is triggered. User forms and their controls respond to the events that are associated with them. Below is a list of events and their triggers.
When a user form comes active When a user form becomes inactive When a user clicks on any part of a form When a user double clicks any part of a form When a user form is loaded into memory When a user form is unloaded into memory
Triggers
A Controls data is changed A control is clicked A control is double clicked A controls value is updated through the user form and is about to lose focus. Focus is the ability of a control, user form or window to receive a click or keyboard input A controls value is updated through the user form and loses its focus
AfterUpdate
Page 44
Private Sub CommandButton1_Click() End Sub Add the following code to read as below this stores the data from the form to the spread sheet in the following Cells A12 ,B12, C12 Private Sub CommandButton1_Click() Cells(12, 1).Value = Employeinfo.txtempname.Value Cells(12, 2).Value = Employeinfo.lstempdepartment.Value Cells(12, 3).Value = Employeinfo.txtempearnings.Value End Sub
Double click on the command button Close the code window opens as below
This code closes the user form Employeinfo Private Sub CommandButton2_Click() Employeinfo.Hide End Sub
Now switch to the excel spread sheet and add a control button from the developers tab controls group, insert drop down, button form_control. Draw the button and the assign macros button dialog box opens, click on New Enter the code as shown below, Edit the text on the Button face to say OPEN Sub Button1_Click() Employeinfo.Show End Sub
Page 45
Having clicked on the open user form button the employee information form will open Enter the details you wish to add to the spread sheet, click enter data to transfer the contents of the form to the spread sheet, click close to exit the form.
Page 46
Data Validation
If a user accidently enters the wrong data or data is missing we want to be able to set in place some rules of checking that information, this is known as validation. Navigate to the VBA Editor window On the textempearnings enter the following code
Private Sub txtempearnings_AfterUpdate() If Val(txtempearnings.Value) <= 0 Then MsgBox "Null Value Not Valid" txtempname.Value = "" lstempdepartment.Value = "select one" End If End Sub
nextrow = Application.WorksheetFunction.CountA(Range("a:a")) + 1
If optMale.Value = True Then Range("a1").Offset(nextrow, 2).Value = "Male" Else Range("a1").Offset(nextrow, 2).Value = "Female" End If
If chkPension.Value = True Then Range("a1").Offset(nextrow, 3).Value = "Yes" Else Range("a1").Offset(nextrow, 3).Value = "No" End If
Page 47
Page 48
Error Types
There are three types of programming error, compile time, run time and logical. The following table describes the type of error. Error Compile-error Description A compile-time error happens when the program is being compiled. Generally, compile-time errors are syntax errors; and they are caught by the compiler. Run-time errors occur at at run-time; generally, the program compiles but does not run correctly. An example of a compile-time error might be leaving out a semi-colon in C. An attempt to read past (dereference) a null pointer in C would be an example of a run-time error. a logic error is a bug in a program that causes it to operate incorrectly, but not to terminate abnormally (or crash). A logic error produces unintended or undesired output or other behaviour, although it may not immediately be recognized as such. Logic errors occur in both compiled and interpreted languages. Unlike a program with a syntax error, a program with a logic error is a valid program in the language, though it does not behave as intended. The only clue to the existence of logic errors is the production of wrong solutions.
Run-time error
Logical
Page 49
Error Types
Compile Time error Compile Time error This is because no Endif Present Sub calculationbonus() Dim bonus As Currency, earnings As Currency earnings = InputBox("enter earnings") If earnings > 40000 Then bonus = earnings * (12 / 100) MsgBox "the bonus is " & bonus End Sub
Logical Error This is a logical error the + has been used instead of the* Sub bonus() Dim bonusamt As Currency, salesamt As Currency salesamt = 10 bonusamt = salesamt + (6 / 100) MsgBox "bonus is " & bonusamt End Sub
Run Time Error This is a run time error the code executes and creates a divide by Zero Error because the (6 / 0) Sub bonus() Dim bonusamt As Currency, salesamt As Currency salesamt = 10 bonusamt = salesamt * (6 / 0) MsgBox "bonus is " & bonusamt End Sub
Page 50
Debugging
To create an error free application you need to be able to trace an correct errors when they occur, the process is called debugging. VBA provides the following tools to help you debug your code these are located on the debug toolbar.
Debugging tools
The following table describes the tools available to you in VBA to view values of variables and expressions and trace the execution of a program. Tool Break Point Used To Pause the execution of code at a specified statement. You can insert a breakpoint in the first line of code segment that you suspect to be the cause of the error. You can then monitor the execution of the code Monitor values of specified variables and expressions while the code is running Test your output by assigning different values to variables or expressions Monitor all the declared variables of the procedure currently running
Choose debug, toggle breakpoint Press F9 Click the toggle breakpoint button on the debug toolbar ( if not open then, view, toolbars, debug.
Click in the margin indicator bar adjacent to the code click again to
remove it
MTC Training Solutions Limited
Page 51
Setting a Breakpoint
Open a new work book and layout the data as shown below Save as my debugging tools
Option Explicit Dim TotalSales As Currency, CommissionAmt As Currency Public Sub Commission() TotalSales = Cells(4, 6).Value If TotalSales > 10000 Then CommissionAmt = TotalSales + (10 / 100) Else CommissionAmt = TotalSales * (7 / 100) End If Cells(4, 7).Value = CommissionAmt End Sub
Page 52
Run the procedure you created called commision this calculates a commision amount if total sales is greater than 10,000 of 10% any sales less than 10,000 then 7% Switch back to excel notice cell G4 contains a value of 12450.10 the value we are looking for is 12450.00. this indicates a problem in our logic Switch back to the VBE we will find the error using the debug toolbar To open the tool bar select, view toolbars, debug
Click the hand icon to set the break point Now click on the run icon Switch back to excel and we can seeno data has been entered into the cell Now toggle off the break point and set a break point on the next line of code Click on the run icon again repeat for the next line The cell is now populated with an incorrect value, as the breakpoint stops the code running we know the line above the breakpoint has the problem lets examine that code. CommissionAmt = TotalSales + (10 / 100) Straight away we can see that the +operator has been used instead of Change the operator from + to * Remove the break Point Run the procedure again. You will see that the calculation has now returned the correct value, so using a break point we can identify the problem area, in the next section we will look at the watch window.
Page 53
Watch Expressions
Some errors may not be traceable to a single statement in your code, for example in some logical errors its difficult to isolate the line of code that is causing the error. In cases such as this you need to monitor the behaviour the expressions and variables of the entire procedure. Each expression or variable you monitor is known as a watch, watch expressions can be defined in either break mode or design time. VBA automatically monitors and displays the expressions in the watch window. The watch window is displayed automatically when you enter break mode or you choose to open the watch window manually by clicking the watch window button on the debug toolbar. The watch window can be used to change values of variables and expressions this allows you to observe how these changes to affect the code.
Consider the following, using the file you have already created make sure you are in the VBE window Select debug then add watch In the expression box type totalsales, the variable to watch, in the context region make sure the procedure list refers to commision and the module list states sheet1 then set watch type to watch expression Click ok Repeat the procedure this time add CommissionAmt Update the code
Now these watches are in place we shall now use stepping through code in the next section to see how they work.
Page 54
Step into, runs each executable line of code sequentially and steps into the procedure. This allows you to observe the effect of each statement on variables. To step into the code either choose debug step into or press F8 or click step into button on the debug toolbar. Step Over, this runs each procedure as if it was a single statement, you can use this to skip calls to other procedures from the current procedure. To step over code choose debug, step over, click step over button on the debug toolbar or press shift + F8. Step Out, runs the remaining code in the current procedure as a single statement. If the current procedure is a called procedure the remaining code in the procedure is executed and the debugging stops at the next statement in the calling procedure. To step out of the code, choose debug, step out. You can also click Ctrl+Shift+F8 or click step out button on the debug toolbar.
Now we understand what stepping through procedure and how it works we shall now put that into practice.
Page 55
Select debug, edit watch select the expression to delete and click delete Right click on the watch to delete in the watch window, right click on the mouse and from the menu select delete watch.
Page 56
With the employee information work book open make sure you are on the employeeinfo worksheet. Switch to the VBE window Make sure the employeeinfo code window is selected
Page 57
Using the Step Into Copy the following code into the code window pane Option Explicit Dim Percentage As Single
Dim Earnings As Currency, TotalEarnings As Currency, Bonus As Currency Public Sub NetEarnings() Percentage = 6 Earnings = Cells(4, 6).Value Bonus = Earnings * (Percentage / 100) TotalEarnings = Earnings + Bonus Cells(4, 7) = TotalEarnings End Sub In the procedure net earnings insert a break point at Bonus = Earnings Run the procedure NetEarnings, the code enters break mode
Point your cursor art the first procedure as shown note the variable percentage as 6
Click
In the immediate pane type Percentage = 15, press the enter key Point your cursor art the first procedure as shown note the variable percentage as 15
Press F8 to run the line that calculates the bonus amount and move to the next line In immediate window type Print Bonus to view the bonus amount in the immediate window Press the Enter Key to display the bonus amount. On the next line of the immediate window type percentage = 20 Press the Enter Key
Page 58
Excel VBA Intro Drag the arrow back to the break point Press F8 to run the line that calculates the bonus In the immediate window type ?Bonus press the Enter Key The bonus is now displayed in the immediate window. Remove the Breakpoint Close the immediate window Update code and run procedure Switch back to Excel. Save your work
Locals Window
The locals window helps you monitor the values of variables within the current executing procedure or function The Locals Window VBA provides one way to access the objects from which Excel is composed. Start to examine these objects by writing a short routine to change the value of a variable. Activate the VB Editor, select Insert/Module and enter the following subroutine in the code window: Sub SampleVariable() Dim aval As Variant aval = 200 aval = 123.123 aval = "Cat" aval = True aval = #12/1/1998# End Sub Now select the Locals Window command from the View menu and then use the F8 key to step through the subroutine. You will see the entries in the Locals Window change as each line is executed with the contents and type of each variable displayed in turn.
Page 59
Error-handling
Error handling refers to the programming practice of anticipating and coding for error conditions that may arise when your program runs. Errors in general come in three types: compiler errors such as undeclared variables that prevent your code from compiling; user data entry error such as a user entering a negative value where only a positive number is acceptable; Run time errors, that occur when VBA cannot correctly execute a program statement. We will concern ourselves here only with run time errors. Typical run time errors include attempting to access a non-existent worksheet or workbook, or attempting to divide by zero. The example code in this article will use the division by zero error (Error 11) when we want to deliberately raise an error. If you have no error handling code and a run time error occurs, VBA will display its standard run time error dialog box. While this may be acceptable, even desirable, in a development environment, it is not acceptable in a production environment. The goal of well-designed error handling code is to anticipate potential errors, and correct them at run time or to terminate code execution in a controlled, graceful method. Your goal should be to prevent unhandled errors from arising.
appropriate action. You do this by testing the value of Err.Number and if it is not zero execute appropriate code. For example, On Error Resume Next N = 1 / 0 ' cause an error If Err.Number <> 0 Then N=1 End If This code attempts to assign the value 1 / 0 to the variable N. This is an illegal operations, so VBA will raise an error 11 -- Division By Zero -- and because we have On Error Resume Next in effect, code continues to the If statement. This statement tests the value of Err.Number and assigns some other number to N.
Page 61
Using the Step Into On Error GoTo Err1: Debug.Print 1 / 0 ' more code Err1: On Error GoTo Err2: Debug.Print 1 / 0 ' more code Err2:
When the first error is raised, execution transfers to the line following Err1:. The error hander is still active when the second error occurs, and therefore the second error is not trapped by the On Error statement.
Page 62
The second form of Resume is Resume Next . This causes code execution to resume at the line immediately following the line which caused the error. The following code causes an error (11 - Division By Zero) when attempting to set the value of N. The error handling block assigns 1 to the variable N, and then causes execution to resume at the statement after the statement that caused the error. On Error GoTo ErrHandler: N=1/0 Debug.Print N Exit Sub ErrHandler: N=1 ' go back to the line following the error Resume Next The third form of Resume is Resume <label>: . This causes code execution to resume at a line label. This allows you to skip a section of code if an error occurs. For example, On Error GoTo ErrHandler: N=1/0 ' ' code that is skipped if an error occurs ' Label1: ' ' more code to execute ' Exit Sub ErrHandler: ' go back to the line at Label1: Resume Label1: All forms of the Resume clear or reset the Err object.
Page 63
A Note Of Caution
It is tempting to deal with errors by placing an On Error Resume Next statement at the top of the procedure in order to get the code to run without raising an error. This is very bad coding practice. Remember that using On Error Resume Next does not fix errors. It merely ignores them.
Page 64
Page 65
The Excel Object Model [A1:F50] ActiveCell.Range("A2") Cells(1) Range(Cells(1,1),Cells(50,6)) Range("NamedRange").Cells(1,1) Range("A:A") [A:A] Columns(1) Range("5:5") [5:5] Rows(5) Sheets("Sheet1") Worksheets("Sheet1") Sheets(2) Worksheets(3) Worksheets("Sheet1").Range("A1") [Sheet1].[A1] ActiveSheet.Next Workbooks("Basic") Range A1:F50
The cell below the active cell Cell A1 Range A1:F50 The first cell in the named range Column A Column A Column A Row 5 Row 5 Row 5 The Sheet called Sheet1 The Worksheet called Sheet1 The second Sheet in the Workbook The third Worksheet in theWorkbook Cell A1 on Sheet1 Cell A1 on Sheet1 The sheet after the active sheet The Workbook file, Basic.xls
Square brackets
The full object reference to the worksheet cell A1 is Range("A1"). If you are typing-in cell references rather than recording, it is easier to use the shortcut notation using square brackets, [A1]. You can use the same style of referencing on other objects as well, such as worksheets but there are a number of rules and restrictions. It is usually best to restrict the square bracket notation to cell references only, where it is entirely definitive and reliable.
WithEnd With
The With statement is used so the object reference can be made and then retained so that multiple actions may be carried out without having to repeat the same object reference in each statement. You can keep the With reference open for as long as you like in the same procedure, just pointing to it using the dot operator. Every With requires an End With. You can have
Page 66
multiple With pointers. When you are reading code that uses multiple With pointers, the rule is simple; the dot points to the nearest With. With Object .Property With .Child Object .Method .Method End With End With
Page 67
Sub GoToManual() Dim xlCalc As XlCalculation xlCalc = Application.Calculation Application.Calculation = xlCalculationManual On Error GoTo CalcBack 'YOUR CODE Application.Calculation = xlCalc Exit Sub CalcBack: Application.Calculation = xlCalc End Sub
Speed up code and stop screen flickering: Sub NoScreenRePainting() Application.ScreenUpdating=False 'Your code here. Application.ScreenUpdating=True End Sub
Page 68
'Or, if only values are needed: Sheet2.Range("B1:B200").Value= Sheet1.Range("A1:A200").Value 'Or, if only formulae are needed: Sheet2.Range("B1:B200").Formula = Sheet1.Range("A1:A200").Formula 'See also FormulaArray and FormulaR1C1 etc 'Instead of: Sheet1.Range("A1:A200").Copy Sheet1.Range("A1:A200").PasteSpecial xlPasteValues Application.CutCopyMode=False'Clear Clipboard 'Use: Sheet1.Range("A1:A200") = Sheet1.Range("A1:A200").Value End Sub
Page 70
Page 71
MsgBox "There are more than 8192 areas, so it is not possible to " & _ "copy the visible data to a new worksheet. Tip: Sort your " & _ "data before you apply the filter and try this macro again.", _ vbOKOnly, "Copy to new worksheet" Else 'Copy the visible cells. ACell.ListObject.Range.Copy 'Add a new Worksheet Set New_Ws = Worksheets.Add(after:=Sheets(ActiveSheet.Index)) 'Ask for the Worksheet name sheetName = InputBox("What is the name of the new worksheet?", _ "Name the New Sheet") On Error Resume Next New_Ws.Name = sheetName If Err.Number > 0 Then MsgBox "Change the name of sheet : " & New_Ws.Name & _ " manually after the macro is ready. The sheet name" & _ " you fill in already exists or you use characters" & _ " that are not allowed in a sheet name." Err.Clear End If On Error GoTo 0 'Paste the data in the new worksheet With New_Ws.Range("A1") .PasteSpecial xlPasteColumnWidths .PasteSpecial xlPasteValuesAndNumberFormats .Select Application.CutCopyMode = False End With 'Call the Create List or Table dialog. Application.ScreenUpdating = True Page 72
Application.CommandBars.FindControl(ID:=7193).Execute New_Ws.Range("A1").Select ActiveCellInTable = False On Error Resume Next ActiveCellInTable = (New_Ws.Range("A1").ListObject.Name <> "") On Error GoTo 0 Application.ScreenUpdating = False 'If you not want to create a table it will run the code below If ActiveCellInTable = False Then Application.GoTo ACell CopyFormats = MsgBox("Do you also want to copy the Formats ?", _ vbOKCancel + vbExclamation, "Copy to new worksheet") If CopyFormats = vbOK Then ACell.ListObject.Range.Copy With New_Ws.Range("A1") .PasteSpecial xlPasteFormats Application.CutCopyMode = False End With End If End If End If 'Select the new worksheet if not active Application.GoTo New_Ws.Range("A1") With Application .ScreenUpdating = True .EnableEvents = True End With Else MsgBox "Select a cell in your List or Table before you run the macro", _ vbOKOnly, "Copy to new worksheet" End If End Sub
Page 73
Page 74
'Test if there are more than 8192 separate areas. Excel only supports 'a maximum of 8,192 non-contiguous cells through VBA macros and manual. If CCount = 0 Then MsgBox "There are more than 8192 areas, so it is not possible to " & _ "copy the visible data to a new workbook. Tip: Sort your " & _ "data before you apply the filter and try this macro again.", _ vbOKOnly, "Copy to new workbook" Else 'Copy the visible cells to the new workbook ACell.ListObject.Range.Copy 'Add a new workbook with one worksheet Set New_Ws = Workbooks.Add(xlWBATWorksheet).Worksheets(1) 'Paste the data in the worksheet in the new workbook On Error Resume Next With New_Ws.Range("A1") .PasteSpecial xlPasteColumnWidths .PasteSpecial xlPasteValuesAndNumberFormats .Select Application.CutCopyMode = False End With On Error GoTo 0 'Call the Create List or Table dialog Application.ScreenUpdating = True Application.CommandBars.FindControl(ID:=7193).Execute New_Ws.Range("A1").Select ActiveCellInTable = False On Error Resume Next ActiveCellInTable = (New_Ws.Range("A1").ListObject.Name <> "") On Error GoTo 0 Application.ScreenUpdating = False 'If you not want to create a Table it will run the code below If ActiveCellInTable = False Then Application.GoTo ACell
MTC Training Solutions Limited
Page 75
CopyFormats = MsgBox("Do you also want to copy the Formats ?", _ vbOKCancel + vbExclamation, "Copy to new workbook") If CopyFormats = vbOK Then ACell.ListObject.Range.Copy With New_Ws.Range("A1") .PasteSpecial xlPasteFormats Application.CutCopyMode = False End With End If End If End If 'Select the new workbook if not active. Application.GoTo New_Ws.Range("A1") With Application .ScreenUpdating = True .EnableEvents = True End With Else MsgBox "Select a cell in your List or Table before you run the macro", _ vbOKOnly, "Copy to new workbook" End If End Sub
Page 76
Filtering Data
Option Explicit 'There are four filter examples in this module 'And a macro example to clear the filter below the filter examples '1: Filter on InputBox value '2: Filter on ActiveCell value '3: Filter on Range value (D1 in this example) '4: Criteria in the code (Netherlands, with tips below the macro)
Filter the first field of the Table/List for the inputbox value
Sub FilterListOrTableData() 'Works in Excel 2003 and Excel 2007. Dim ACell As Range Dim ActiveCellInTable As Boolean Dim FilterCriteria As String 'Use this line if you want to select a cell in the Table with code. 'Application.GoTo Sheets("Yoursheetname").Range("A24") If ActiveSheet.ProtectContents = True Then MsgBox "This macro is not working when the worksheet is protected", _ vbOKOnly, "Filter example" Exit Sub End If 'Set a reference to the ActiveCell named ACell. You can always use 'ACell now to point to this cell, no matter where you are in the workbook. Set ACell = ActiveCell 'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you 'don't need to know the name of the table to work with it. On Error Resume Next ActiveCellInTable = (ACell.ListObject.Name <> "") On Error GoTo 0 'If the cell is in a list or table, run the code. If ActiveCellInTable = True Then
Page 77
Appendix B Sample Code 'Show all data in the table or list. On Error Resume Next ActiveSheet.ShowAllData On Error GoTo 0 'This example filters on the first column in the List/Table '(change the field if needed). In this case the Table starts 'in A so Field:=1 is column A, field 2 = column B, ......
'Use "<>" & filtercriteria if you want to exclude the criteria from the filter. FilterCriteria = InputBox("What text do you want to filter on?", _ "Type in the filter item.") ACell.ListObject.Range.AutoFilter _ Field:=1, _ Criteria1:="=" & FilterCriteria Else MsgBox "Select a cell in your List or Table before you run the macro", _ vbOKOnly, "Filter example" End If End Sub
'Set a reference to the ActiveCell named ACell. You can always use 'ACell now to point to this cell, no matter where you are in the workbook. Set ACell = ActiveCell 'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you 'don't need to know the name of the table to work with it. On Error Resume Next ActiveCellInTable = (ACell.ListObject.Name <> "") On Error GoTo 0 'If the cell is in a list or table, run the code. If ActiveCellInTable = True Then 'Show all data in the table or list. On Error Resume Next ActiveSheet.ShowAllData On Error GoTo 0 'This example filter on the ActiveCell value ACell.ListObject.Range.AutoFilter _ Field:=ACell.Column - ACell.ListObject.Range.Cells(1).Column + 1, _ Criteria1:="=" & ACell.Text Else MsgBox "Select a cell in your List or Table before you run the macro", _ vbOKOnly, "Filter example" End If End Sub
Filter the first field of the Table/List for the text value of Range("D1")
Sub FilterListOrTableData3() 'Works in Excel 2003 and Excel 2007. Dim ACell As Range Dim ActiveCellInTable As Boolean Dim FilterCriteria As String 'Use this line if you want to select a cell in the Table with code. 'Application.GoTo Sheets("Yoursheetname").Range("A24") Page 79
MsgBox "This macro is not working when the worksheet is protected", _ vbOKOnly, "Filter example" Exit Sub End If 'Set a reference to the ActiveCell named ACell. You can always use 'ACell now to point to this cell, no matter where you are in the workbook. Set ACell = ActiveCell 'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you 'don't need to know the name of the table to work with it. On Error Resume Next ActiveCellInTable = (ACell.ListObject.Name <> "") On Error GoTo 0 'If the cell is in a list or table, run the code. If ActiveCellInTable = True Then 'Show all data in the table or list. On Error Resume Next ActiveSheet.ShowAllData On Error GoTo 0 'This example filter on the first column in the List/Table. '(change the field if needed). In this case the Table starts 'in A so Field:=1 is column A, field 2 = column B, ...... 'It will use a cell text of Range("C1")for the Criteria. ACell.ListObject.Range.AutoFilter _ Field:=1, _ Criteria1:="=" & Range("D1").Text Else MsgBox "Select a cell in your List or Table before you run the macro", _ vbOKOnly, "Filter example" End If End Sub
Page 80
Excel VBA Intro 'Criteria in the code (read the tips below the macro)
This example will filter the first column "Country" for "Netherlands"
'ACell.ListObject.Range.AutoFilter Field:=1, Criteria1:="=Netherlands" Sub FilterListOrTableData4() 'Works in Excel 2003 and Excel 2007. Dim ACell As Range Dim ActiveCellInTable As Boolean Dim FilterCriteria As String 'Use this line if you want to select a cell in the Table with code. 'Application.GoTo Sheets("Yoursheetname").Range("A24") If ActiveSheet.ProtectContents = True Then MsgBox "This macro is not working when the worksheet is protected", _ vbOKOnly, "Filter example" Exit Sub End If 'Set a reference to the ActiveCell named ACell. You can always use 'ACell now to point to this cell, no matter where you are in the workbook. Set ACell = ActiveCell 'Test to see if ACell is in a table or list. Note that by using ACell.ListObject, you 'don't need to know the name of the table to work with it. On Error Resume Next ActiveCellInTable = (ACell.ListObject.Name <> "") On Error GoTo 0 'If the cell is in a list or table, run the code. If ActiveCellInTable = True Then 'Show all data in the table or list. On Error Resume Next ActiveSheet.ShowAllData On Error GoTo 0 'This example filters on the first column in the List/Table '(change the field if needed). In this case the Table starts 'in A so Field:=1 is column A, 2 = column B, ......
Page 81
'Use "<>Netherlands" if you want to exclude the criteria from the filter ACell.ListObject.Range.AutoFilter Field:=1, Criteria1:="=Netherlands" Else MsgBox "Select a cell in your List or Table before you run the macro", _ vbOKOnly, "Filter example" End If End Sub
Page 82
Page 83
Page 84
Page 85
Page 86