Vous êtes sur la page 1sur 98
J Handy Reference Froncesco Fresta Excel ‘Control Toolbox ‘ew, Toolbars, Control Toolbox from men To access the VBE. Alc igh click the sheetname tab View Cade from is shortcut menu | Doaback cond | [Records macro Hep aca macro “Tool, aera, Macros. Ei rom mena “Tools Maer, ecord New Macro from men Ft Selec curren eon view al she formals Cessies= Ga Visual Basi (VBE) Io can | [Were ore ew Pe re CoA) Dou rt crs Rt i Oe rc Workbook event View Project Explorer (CirH*R) . ote i Tsertook | tn Wai hd as iin | New UserForm | [RunContinve a Properdes Window Fa = [Object Browser: nn) a zg [Excl ARF a Help Select a keyword, Press FI — indent a oie sa om law a Debug Shortcuts — = Sianeli o casio fnretae Winv fears [Clea Al Breakpoints CuShicor® EXCEL VBA ED ROBINSON FRANCES PRESTA 2008 In easy steps isan imprint of Computer Step Southfield Road . Southam Warwickshire CV47 OFB . United Kingdom wworwineasysteps.com Copyright © 2004-2006 by Computer Step. All rights reserved. No part of this book may be reproduced or transmitted in any form oF by any means, electronic or mechanieal, including photocopying, recording, or by any information storage or retrieval system, without prior written permission from the publisher. Notice of Li Every effort has been made to ensure that this book contains accurate and current information. However, Computer Step and the author shall not be lable for any loss or damage suffered by readers a5 a result of any information contained herein. Trademarks Microsoft® and Windows® are registered trademarks of Microsoft Corporation. All other trademarks are acknowledged as belonging to their respective companies. Printed and bound in the United Kingdom ISBN 13 978-1-84078-271-4 ISBN 10 1-84078.271-4 Table of Contents Incroduetion 8 Weiting your fist program 9 Running your program 2 Editing the code B your pragram does run 4 ‘Variables 16 The message box 's ‘Comments 9 Option Expl 20 f Other varable pes 2 IncelliSense au Help: pe Arithmetic operstiors % “The For..Nex¢ loop Using Cells 29 “The debugger 30 Breakpoins 31 “The Immediate window 2 i Then 2B i Logi operators j Do. Loops 36 i Sect Case 38 | paca eanele 2 | Program development 0 Loops inside loons “4 ‘A number search % {A program eo delete blank cls 46 Seing handling 50 re Properties and methods Object hierarchy The Microsoft Excel Object Model (Other properties and methods Object variables ‘To sum numbers according to color &A £ 56 37 8 3 & “To record and run a macro To-edica macro Project Explorer Macros available to other workbooks Torun a macro from a toolbar butzon VA ‘Worksheet properties and methods Collections Collection properties and methods Calls, columns and rows Worksheet events ‘Automatic sheet entry Worksheet names Qs ‘The Workbooks collection ‘Workbook properties Werkbook/s methods Workbook events Workbook in the Excel Object Model ‘An automatic alere i | j ‘Columns 08 Rows 103 Practical examples 110 Value 12 Copy and Paste methods 113 Currentheglon 14 UsedRange NN6 Offset M7 Resize 119, ‘A dynamic selection 120 Incersect i Union 123 To cesta selection 24 ‘The Areas collection 12s, ‘Command button 128 ‘Changing a property at design-time 129 “exe boxe 133 Spin button 135 Check box 137 ‘Option buttons 1338 ‘Combo box. 19 Using option buttons M41 Subs laa Functions 146 Passing ByRef and 8)¥al \a7 Using a sub 48 Using a function 149 Variable scope 130 To color the minimun value 152, Variable lifetime 153 The MsgBox function 154 ‘Named parameters 155 User defined functions 156 Using arrays LD arrays 2D arrays ReDim Variant arrays The Array function The UserForm Run-time errors Names Date and Time ‘Now, Date and Time Separating date components ‘Assembling date components ‘Adding and subtracting dates The number of weekdiys ‘The Mod operator Anniversaries The Application object Index Application properties WorkSheetFunction Methods Volatile 157 133 160 ler 162 163 lea 167 170 171 m 173 74 175, 176 7 V8 179 130 132 34 86, 187 Getting Started In this chapter, we will see that Excel VBA is fun, and simple to learn Why learn Excel VBA? We will consider this question and then learn to write, run and edie our first program. Introduction 8 Writing your frst program 9 Running your program 12 Editing the code 13 Iyour program doesn’t run 14 Chapter One Introduction 8 | Excel VBA in easy steps Why learn Excel VBA? Excel Visual Basic for Applications extends and customizes Excel ~ allowing us to do things that Excel itself is not able to do. For those who simply wish to learn to program, Excel is an ideal environment. The spreadsheet is well suited asa programming interface — for inputting data to be processed as well as displaying the results ennianncni It's not essential to make a further software purchase in order to learn the elements of Visual Basic programming, Excel VBA comes free of charge with every copy of Excel (97, 2000, 2002, 2003, etc.) and provides a great deal of the functionality of stand-alone Visual Basic - and more! There may be some with financial/accounting experience who have ‘come to realize that simply recording a macro has limitations, and that iis necessary to start to learn Excel VBA from the ground up. Excellent texts abound, but where to start? Just because Excel VBA is easy to learn, does not mean that itis not 4 serious programming language. It can also be used to perform ‘complex tasks such as automatically getting up-to-date financial information from the Internet, or calculating option prices. [tis ‘even used in scientific applications. One of the great advantages of Excel VBA is the macro recorder (which stand-alone Visual Basic does not have). This is invaluable if you are struggling with some programming syntax, Just get the recorder to do it for you and then view the code to see how itis done! We will learn about the macro recorder in Chapter 5. ‘There are many ways to write a program using Excel VBA. We ‘could write user-defined functions (which are a type of bespoke ‘worksheet function), in which we could try our experimental code, ‘or we could record a macro and place our trial code in it Each has advantages and disadvantages. For the most part, we will place our ‘experimental code inside a command button procedure. We will now describe thar method, and learn just how easy i is to progeam in Excel VBA. Writing your first program shal ‘We will place a command button on a sheet which we can click in order to run asimple program. istly, in order w draw a button on our sheet, we need the Contral Toolbox: | Glick View, Toolbars, and then Control Toolbox. set_Forivt Tole Data Normal LD eagetroak Preven TeisPane esas era Bar austen ‘window He 20 B Did anderd Fomating oxders chart ‘ContralToabor anit 2, ick he Deen Mode tniton This tp isnot exert ‘0CommandButtont 3. Glick-the Command Button on the Control Toolbox. click on the sheet and then drag a ‘command button on the sheet as shown, sscont'd This code modu is specific to this particular worksheet. Each ‘worksheet has ite own code module in which code can be placed. In this module, you will notice that some code already appears. Option Explicit (ifit does appear) will be explained in Chapter 2. It could be considered to invoke spell-checking. "r4:vate means that this code can only be referred to in the code module for this particular sheet. It also does not concern us at this The VBE wil coptoize stage and could even be omitted if desired. pron for yu Wecan wie” ConmandButtor: refers to the command button (object) that we covortge ofths placed on the sheet. C1ick is what we are about to do to the byolwoys ying keyworesn command button to run the program. lowercase As you press h Ener key the VBE wil copeaize Subp and Ena Sub is a way of indicating a self-contained unit of re | | i j j i i i | Per = | ‘em for yu thereby checking code, More about subs in Chapter 10. | j | ‘oCommandButtont Tet Creuse ‘Altematively, double-click on the command button making sure that the Design Mode button is still depressed. 55 The Vinal Bsc Editor (VBE) appears. Ck inside ott this "code skeleton” to place the cursor here, Range ("A1").Value = "simple" End Sub (A drop-down box may appear as you type. This is IntelliSense and is discussed on page 24.) The code above will simply place the ‘word “Simple” into the top left cell of the spreadsheet when we run the program. As we will see, Value isa property of the Range long artemis object and indeed is the default property. Being a default property, it can be omitted, ie. we could simply have: tke Soran ror wer opie eve Range ("AA") von epg re 7 Go back to te Excel spreadineet by choosing Excel inthe tsk barat the baltom ofthe screen. Atel, ald down the At vay ane contre 0 pres Tab ul you se the Excel con ~ and ty) pee eppeove window os wel example the Project Explore window pyivace Sub Commandbuttont_¢1ick() then release *he Alt key. Use these methods to also return to Cla ve vee Close button 10 | Excel VBA in easy |. Getting started | 11 Running your program Now that you have written the cod, is ime to esti |. cick he Bet Design Mode button 0 ent design mode It shuld become “deere Ext Desgn dade) 6 a ‘oCommendSutiont SpE N ‘The command button has also become “deselected as shown below. Click on it to run the program, ‘CommandButtont The text appears in cell Al 0d for nina CommancButton! 12 | Excel VBA in easy steps iting the code You may have noticed that the command button on the sheet has an “inner rectangle” around it immediately after clicking it ~ it “has the focus — Return to the VBE by clicking on the View Code button on the Contral Toolbox. You will only need to have the Design Mode button depressed ifthe command button has the focus ‘2, Ect the code shown blow Private Sub Cormandsuttonl_Click(} Range ("AZ") .value = 2 Vous F Bea Sub perenne 3 Return tothe Excel window: Make sue thatthe Design Mode fed commas buttons not depressed. Clik on the command button to run the program, Atematiely, you could cick on the Run buton in the VBE, making sre that your cursor is inthe code frst. ihowtecons FRA Decency Option Explicit Options 4, Return to the Excel window. The number 2 wil appear in cel A2 ja EEE If your program doesn’t run For example, if you made a spelling mistake, you may geta message like this: werth making the prod HEE arr) -voive = "sine ao ‘Sor fectennc defn eam) Click OK — but that is not the end of the story! ou were sat to You must now click on the Stop button, the Sap that you are silo mht cpr your rogram we you VRE window by ekg 14 | Excel VBA in easy steps Basic programming techniques [Now that we ean write a simple program, we ean learn the basic programming techniques to enable us to write useful, practical programs. Variables 16 ‘The message box 18 Comments 19 ‘Option Explicit 20 Other variable types | 22 Incellisense 24 Help 25 Arithmetic operations 26 Chapter Two Variables Afr you enter 3 ine eontanng ‘an legal vriale VBE. the ine wit sum re BA in easy steps cont'd Avvarlable isa name that we use to store a value, There are a few restrictions on the names that we may choose — for example they cannot stare with a number and they cannot contain periods (fall- stops), for example x, y2, var, sum are legitimate variable names whereas 1 and x. 1 are not. Be careful not to use keywords as variable names, ¢.g, Sub isan illegal name for a variable. Variables, are used to store values which you may wish to use lar in your program. Variables are categorized depending on the type of data they will contain, A common type is Integer. A variable of Integer type, strictly speaking, can only hold whole number values, eg. x = 2 —— Giving a variable a value is known as initializing it String variable types contain text, eg. Surnane = "Jones" ‘We indicate the type of the variable by using the Dim statement, eg. pim x As Integer Dim Surname As String This is known as declaring variables, Different variable types ‘occupy different amounts of space in memory. The Dim statement signals how much memory is going to be required for this particular variable. We will edit the previous code to include a variable. It will simply. place 2 in the top left cell. w—— Option Expt option Explicit which will be explained later, may oF may not Private Sub Commandsutton!_Click() Dim x Ae Integer x= be included in Range ("AI") .Value ~ Bea your code at this stage ‘Swapping Values Why use variables? Consider this example. We have two integers in two spreadsheet cells as shown below. We wish to write a program ‘to swap them. First place the two numbers that we 2 ‘wish to swap in the cells as shown, Ifyou were to ny the following code it wouldn't work: Range (*AL") Value Range (*A2") Value Range ("A2") .Value Range ("Al") .Value ‘The problem is tat the value in Al gets overwritten and therefore lost. The result would be that both cells would finally contain 3. ‘We need to be able to save the value in Al in a variable as follows: Private Sub ConmandButton1_Click(} Dim x As Integer x = Range("”i") .Value Range ("AL") .Value = Range (*A2") .Value Range ("AZ") Value = End sub __— The value in Al is saved in x *~— The saved value is retrieved ‘When we run this program by returning to the Excel window and clicking on the command button on the shect, the values in the cells will be successfully swapped: elas ay] a ea Note that ifyou ere to click the command button again, the numbers would zgain be swapped 2. Base progrenming techniques | 17 a The message box ‘The message box is a means of displaying data. ‘The following code will cause a message box to appear when we click the command button on the sheet. Private Sub Commandsutton}_click() MagBox "Simple" End Sub ees Click OK to dismiss the message box ‘We can display a combination of text and the value of a variable: Private Sub ConmandButtonl_click() Dim x As Integer x2 Whereosthe MagBox The value of x de" & str(x) i freer ection comited (ter s verse ocs (ERIE an imp eype conversion from integer to Sing) it's nor | Theat of ie ‘esdered g000 programing procs Note also tat St) = ieduces a spureus space on fs efi inti case to the left of "The MsgBox’s message (prompt) must be a string (text), hence the Str() function is required to convert an integer to a string, which is then concatenated with the first string using the & operator. More about strings in Chapter 3. 18 | Excel VBA in easy steps Comments ‘Comments are test that you can place in the code purely for annotation. Comments play no part in the running of the program. ‘Comments can be useful when later reading through your code to remind you what you did! To make a comment, place an apostrophe at the start of the text, After the line is entered, it should turn green to indicate that itis a comment. Dim x As Integer ‘Declare x ‘This whole line is @ coment Rather ten i See euea Ifyou have many lines that you wish to comment, you can tse the wont se ote, Comment Block button which can be placed on your VBE toolbar commenti as follows. From she VBE menu, choose View, Toolbars and then click Customize... The Customize dialog box should appear as below. | choc te ‘Commands tab. Suavarnbabinoaa er 2 croose Ea 3 Drag the Comment Black (end the Uncomment Block) button onto Themen the VBE Tooter. coment of he al Geclmion eS A Close the dig box ae very sarin oppecrence Take cre 0 isting between them ‘These buttons should now be visible on your VBE toolbar, Now, in order to comment out a block of text, simply highlight the block and click the Comment Block button. Likewise, in order to uncomment a bleck, highlight the commented block and click the ‘Uncomment Block button, 2. Base programming techniques | 19 Option Explicit You may have noticed in our previous code examples, that sometimes option Explicit appears and sometimes it doesn That's because itis optional! Option Explicit at the top of our code module forces us to declare all of our variables, ie. use Dim statements. At the least, Opticn Gxp1cit invokes spell-checking. The example below uses the variable sales, but does not use option Explicit. Simply delete/comment iti tis there. See eo behavor of the Procedure Separators (which can be ingle ono by frst choosne Private Sub Comandbuvcont Click( Tels Opin. Ea), which sont actualy peer Cee 9 ee eee, fn nt ofr the ine i ner the command button (frst exiting design mode), as we expect, a message box appears displaying the value of 2 In the example below however, the second sales variable has been inadvertently misspelled as sais. When this program is run, the mistake goes undetected! A message box appears, but with a blank value (see next page), because the misspelled variable sale is regarded as another legitimate variable without a value! Alves ine MogBex sale VBA in easy steps fseaeiets No value is displayed Include Option Explicit at the very top of the code. Declare (Dim) the variable sales and run it again This time the prograrn halts with an error message. Click CX — and don't forget to click the Stop button! Ifyou now correct the typo (ie. change als to sales), the program should rur.as expected, ic. the message box will correctly display 2. fusing option Explicit may seem a bit unnecessary, even at this early stage, it isa good idea to get used to it now ~ it will eventually save you time, especially as programs become larger. option Explicit can be made to appear automatically at the top cof your code by checking Require Variable Declaration, after choosing Tools, Options... Editor from the VBE menu. It will not take effect however, until you open a new workbook. Meanwhile, you can simply type option mxplicit in the General Declarations section ifit does not already appear. 2. Basi programing techniques | 21 i - Other variable types lesvey tempcing to cect af vorebes es Vent Tis has dsochartoges ret ony fom performance pot of view, your code wl un Slower, but you shoul fied that fore ore easier to oat if you ‘are more spec abou the vanabie ype The 2 ("erin the defaut VBA fontcan be easly mstaken forthe VBA 2 (ore). 22 | Excel VBA in easy steps ‘The Long (meaning long integer) variable type is used for large integers up to 2,147,483,647. Integer can only take values up t0 32,767. Single can cater for decimal values as well as integers. Double (64 bit) isa more accurate version of the 32 bit Single ‘ype, Boolean can take only the values True or False, ‘variant can take any type! Date is used for storing dates. More about Date later, Generally speaking, if you are not sure of the size of variable required, opt for the larger capacity, eg. use Long rather than Integer. ‘The following code segment demonstrates common types: option Explicit Private Sub Commandmuttenl_click() Dim 1g As Long Dim sg As Single Dim db As Double Dim tf As Boolean Dim vr As Variant Dim dt As Date ag = 205 2g = 2.125 db = 2.125 te - True ve = 2.6 at = #1/1/20058 Range ("Al") .Value = 1g Range ("AZ") -Value = 6g Range ("A3") Value = db Range ("A4") .Value = tf Range ("AS") .Value = ve Range ("A6") .Value = dt End sub socont’d a | ‘205 215 2.125 TRUE 26 ‘101/205 It is possible to Dim many variables on the same line, e.g. Dim 1g As tong, 9g As Single, db As Double If we wish to specify a variable as a Variant type, we can omit the type qualifier altcgether, c.g. instead of Din vr As Variant, we could simply have Dim vz, since Variant is the default data type. “Take care however when declaring the variables on one line, eg. Dim x, y, 2 AS Integer will declare x and y as Variant and only 2 as an Integer. ‘An alternative method of declaring variables is to use a type- declaration character. This is a character which is appended to the variable name, eg. Dim i As Tateger can be replaced by Dim 3% and Dim 1g Ae Long can be replaced by Dim 1gé The use of type-declaration characters however is deprecated, ic. isto be phased out and eventually not supported, and is only mentioned here in case itis encountered. I is good programming practise to ensure that all variable declarations are laced at the very star of the code. ‘Unfortunately, with Excel VBA, itis not yet possible to declare and initialize a variable in one statement, eg. Dim 8 As Single = 22.1 is not yet possible. 2 Base programming techniques | 23 IntelliSense ‘You have probably by now, noticed a drop-down box which sometimes appears as you type. This is IntelliSense, 24 | Exce!VBA in Ea Borers Boje Ea Calcusteoreiss 2 Catcusteatems Ea catcusteowember InrelliSense is a feature of the VBE which allows you to easily complete yout line of cade. Note that asa space is typed, asin the above example after the ‘aa, IntelliSense appears. As further letters are typed, the IntelliSense suggestions become more specific. To accept the suggestion, either implicitly accept the suggestion by continuing to type the remainder of the line, or double-click on the suggestion. If the Enter key is pressed to accept the highlighted suggestion, a new line will be also started ‘You will also notice that IntelliSense will sometimes even make a suggestion for the valre of a variable, For example, in our case, a8 shown below, when "EE =" is typed, Truc or False is suggested, but only if you are declaring your variables using Dis etc. Option Explicit _ Private Sup Conmandiuttoni_Click() Din tz A2 Boolean 5 sep be ocessed by Excel VBA has a very comprehensive built-in reference. The most reliable way to get Help is the easiest! Simply highlight the word (you could double-click on the word) for which you want Help, and then press the F1 key. For example, highlight the keyword Boolean as shown below and then press the F1 key. option Explicit fete, Private Sub Commandbuttoni_Click() Dim et as End sub ‘The Help dialog box appears as shown below. Try the See Also and then choose Data Type Summary where you shuld find data types that we have not yet discussed (eerste Boolean Data Type Selo Evsngie Soe Boolean variables are sored as 16-bit (2-byte) fhumbers, but they can only be True or False, Boolean Variables digplay 02 etter True or False (when Print is used) or #TRUES oF PALE (when Write # is Used) Use the kexords True and False to assign one of the twe states 9 Boclean varables. When ether numeric tyzee are converted to Boolean Yaluee, 0 becomes False and all cther values beoome ‘True. When Boolean values are converted to other data upes, False becomes 0 and True becomes “1 ‘Try the hyperlinks for some extremely useful definitians The hypertinks change color after being “visited uss | 25 2. Basic programming Arithmetic operations You are most probably already familiar with Excel formulas. This formula of course will mutiply the contents of Al by 3 divide by 4 and then a add 310 the resut Ez siving 9 = a jas ‘The same operator symbols are used in VBA. We could carry out the above operation in VBA as follows: Private Sub CommandButtoni_Click() eae | 7 Range("B1").value=x+*3/44+3 Aenea Bnd Sub placed in cell BI ‘Try the exponentiation operator ~ replace the corresponding line above with: Range ("Bi") Value = x * 2 in which case the value of xis raised to the power of 2, ie. in this case, @ is squared to give 64 and placed in B1 AAs in Excel itself, parentheses ensure priority as shown below: Private Sub Commandsutton_Click() Dim x As Single 16 is divided by Heed 8, and then | is Range("AI") Value = 16 / x - 1 Range (WA2") Value = 18 /(x + 1) cet End Sub give | A D i 1B is divided by 2 2 ‘ommandButton the sum of & Z CommandSuttont | a = plus | to give 2 26 | Exel vi ranching and looping Ne proceed in this chapter to learn how to work with loops and branching 32 39 40 4% Use the Tab key toindento ne of code node rrpeoe epi 28 | Excel VBA in easy steps Next loop The For...8ext loop is one of the most usefull program construets, ‘We usually first declare an Znteger counter variable which will ‘get automatically incremented as control is transferred cyclically from the last line of the loop to the first. The Foz...vext keyword, pair serve to enclose the code. This code will simply cause a message box to appear three times after the command button is clicked to run the program. Private sub Conmandsuttoni_Click() Dim i As Integer For 4 = 1703 —_ Magbox "Simple" Next i control is transferred End sub back to For: After reaching Next, IED as essaze box wil as appear (and need to be dismissed) three times. Ese) ‘The For keyword signals the start of the loop. The value of i is initially 2. Program control continues down, line by line ~ the message box is displayed until the Next keyword is reached. Program control then automaticaly returns to the For above, ‘The value of i is then incremented to 2. This process continues ‘until & becomes 3 ~ control is no longer transferred back to the Fox but continues down to the statement after the Next — the na Sub whereupon the program terminates. Change the code to that shown below so that the message box will now display 1, 2and 3 respectively. Privare sup Commanasuttoni_C1ick() Dim i as Integer For i= 1703 MsgBox Str (i) Next i Bnd Sub Using Cells Rows fist ond may hep to remember Rose Colin Vue could be comited sce tis the defo propery Whereas hieger type i acceptable for experimental purposes, Long referble for more seus oppicacons reed, te numberof spreadiheet ows (65,536), moe than owe the copociy of reper (32.767) cells is an alternative to Range, Itis used to refer toa particular spreadsheet cel using indices. Ce1 Ls (1,2) for example would refer tothe cel of row 1 and colurnn 2 using the indices 1 and the 2. The equivalent using the Range notation would be Range (*B1"), so to place a3 in cell BI we would use: Private Sub ConmandButtoni_Click() cells(i, 2) value = 3 nd Sub EET a OSI i 3 2 al a ormencatont é ‘The advantage of using the Ce11s notation is that it can be used ‘with variable indices, which is particularly useful for looping as we shall now see. This program simply places the number 10 in the first five cells of the rst column. Private Sub ConmanéButtont_Click() Dim i Ag Integer For i=1T05 celis(i, 1)-Yalue = 10 Next i End Sub ‘The Cele notation can also be used to get values from a cell. To read the value in cell B1 into a variable x we would use: x = Cells(1,2) Value 3. Branching and looping | 29 ai The debugger ' reakpoints The debugger tool assists with finding crrors. It can be used to step _ ‘The program can be made to halt temporarily ata particular fine by through the code one line at a time. This is useful for instructional using a breakpoint. Dunposes- the program cun be ran in slow motion! || Clckon the left margin ofthe VBE athe pont where you would | View the previous program in the VBE : like to set a breakpoint. A brownimaroon dot appear. and place the cursor atthe start. ‘Option Explicse Instead of eion Explicie 3 Private Sub Conmandiuttoni_click() BED) vesreiners rivete Sub Comiandbuttoni r Dim 1 As Inceger fey fo te VBE Paserpis nates For i= 110.3 ier oan For i= 1705 : eee oe Cells(i, 1) Value = 10 Next 4 er Next 1 End Sub Eng Su pone. a 4 D. Fun the program by clicking the command button on the SSeS ee ane oe i spreadsheet, or by clicking the Run button from the VBE, making fre Ered The yellow bar Speion Expiicie sure that the cursor is within the code, The program wil halt at . shows the the breakpoint a Din d As Invege window, the Senet teas) Option Explicie Zz eS i! | | Seueee 9 wetwe #20 ; j ecu onthe sheet ~ rata) Private Sub ConmandButtoni_Click() ‘one by one — as you single step seared Dim i As Integer oo tea fori sites 3 Continue to press FB to single step. Not that it doesnt seem 10. eet “land” on the For statement as it cycles around the loop. é End Sub jeion Explicit Private Sub CommandBattoni_Cliek() By holding the cursor steady on a variable, we can inspect the Dim i As Integer value of the variable as we saw previously. Single step by pressing al commegrayswa The FS key con the FB key or continue to click the Continue (Run) button to run’ - Next i Gio be used fer? (gop) to the breakpoint. If you wish to stop the program, click (more canecty = one frebaa'Tps’ — yOUvery careful place your cursor on a variable as you debug, the Srarsotdie stancf eee A To remove the breakpoint, simply lick on it To clear all vaso rt. ote value of the variable will appear ina smal yellow box breakpoints, rem the WBE menu choose Debug Clear All sure thot Ato Doo Tpsis 2 eked ~ chose Toots Breakpoints ES Se vec 4. you wish to stop singe stepping, click the Stop button or click Pe menu the triangular Continue button to continue running, 3, Branching and looping | 31 30 | Excel VBA in easy steps a The Immediate window The Immediate window is used to display output and accep input ‘whilst debugging, It can be used to display values of variables as the program single steps. To display the Immediate window, from the VBE menu choose View, Immediate Window. If... Then Debug. Print is used in the code to send output from your program to the Immediate window. Include Debug. Print in the code of the previous example as shown below, and single step (continue pressing F8). In this cas, the value of che counter will be printed to the Immediate window for each loop. Private Sub Commandsuttonl_click () Dim i As Integer For i=1 705 Cells(i, 1) Value = 10 Debug. Print i Next i End Sub OS ebughrint il cause the value of | to be output to the Immediate window as the program loops rou wide torepect o mand wht ‘cheiomeaste Whilst debugging, you can type directly into the Immediate ‘nndow serpy window while the program is temporarily halted (break mode). ple your eusorat he ee of Typing print i will eause the value of ito appear. peer Gd mecven: ume I cause the value of ito app peviente | 2 . 32 | Excel VBA in easy steps Another extremely important statement pair is the T..-Then pai. ‘An action is either performed or not performed, depending on ‘whether a condition is satisfied. Private Sub ConmandButtont_Click() Dim i As Integer ie2 If d= 2 Then Cells(2, 1).Value = "yes" End sub Since the condition is fulilled “yes” is placed in cell Al 4] 2) CommandButtont a [s] Change £ = 2t0 1 = 3. The condition i = 2 now of course is false. When the program runs, nothing happens. Make sure that you delete the “yes” in the spreadsheet before you run the program clse you won't see that nothing has happened! ‘We have just seen how the 1£..-then construction was placed on ‘one line. It can be “split” by placing che conditional code in an TfinBnd Tf blockas shown below. ‘When run, this coce will perform exactly as the previous code. Option explicit Private Sub CommandButtont_click() Dim i As Integer a Te 4 = 2 then ————— The Ifand End I Celle(1, 1).value = "yes" — serve to enclose the End Tf ———_____ conditional code End Sub ‘The advantage of this construction is that more than one statement can be executed if the condition is satisfied, as we will now see. 3 Branching and looping | 33 sont’ P b End sub ConmandButtont_c teger ick () If i= 2 Then — celis(1, 1) .Value Celis(1, 2).Value = End 1f — The If and End IF now enclose more than one statement The result of running the previous code is that text appears in two cells CommandButtont Else Before proceeding, clear the cells Al and Bi. 1se is used with 1..rhen to cater for the alternative Private Sub ConmandButton_Click() Din i As Integer tna fi - 2 Then Celis(1, 1).value = tyes" Celis(1, 2).Value = "of course" Else Since the condition is Gells(2, 1).Value = "sorry" not satisfied, only the ~ Else section of the code is performed Logical operators “The most common logis operators ae And, Oe and ot When each of the three simple programs below is run, the result will be the same - “yes” will be placed in the top left cell of the spreadsheet in each case, And Private Sub CommanaButton]_Click() bim 4 As Integer, j As Inti Lea tea If i= .andj End Sub Beth conditions = 2'Then Cells(1,1) = "yes" must be true Or Private Sub ConmandButtoni_Click |) Dim ger, j As Integer oe 3 If itor j end Sub > Either condition 2: Then Cells (2,1 is sufficient Not Private Sub CommardButtont_Click() i As Integer 4+ 2 Then Cella(1,2) = "yes" Ary value fori other than 2 will result in the condition being satisfied | Bp, en: = mi Do...Loops oand Loop also occur in pairs and serve to enclose code which “repeats”. The program below will perform exactly as the For.nllext example we met previously. It will place five 10's in the Instead of Do...One11, we may use Do..jihile. Again the effect of this code will be identical. first column of the sheet, Whereas the For...Next loop will a Private Sub CommandButtonl_Click{) increment the counter for us automatically, when using the Dim i As Integer hi te teop we must Increment epi 7 net " <5 dlowsite op be ertered Deivate Sub Comandbuttont_Click() } Be white 4 < $i isles than 5, bt when Dim i As Integer a oo come inside the lor OF eee — Cells(i, 1) = 10 Decoines a inse te ee ae? =a ‘The statement i = i + | means “take the Loop ‘transfers control back to the else ee ee as nd Sub Do While and the loop terminates a : ‘understand thot eee x ee (=i +t means ‘Loop Until i = 5 —— For values of i less than 5, control is ‘increment the End Sub transferred back to the Do. When i finally becomes 5, the loop terminates vue of by 1 ‘When we click on the Command Button on the sheet, five ID are placed in the first column ‘As you can sce, the differences between loops using Bo...L00p is ; Da] 4 quite subtle — familiarity with one would suffice at this stage. [2 | The condition afte- the Do or the Loop, e.g. 4 < 5, evaluates to A cither True or False, Ifwe were to ran something like this 5 Do While False 6 ~ ‘Since the condtion i Fale, he e Loop program doesn't loop at all Re ee nothing would happen, it wouldn’t loop at all. Whereas the : ci following code wosld loop forever. Don’t ty this! Private Sub CommandButton3_click() Baers i Torate Be MEL Re se tne conn is Tete ino ‘The only sfferere is a thee condition qecike tee mew pace teem program would loop continuously Bo ures teed athe tat ofthe ep Aer a hoes ne ie eee a n general a Forex loop is used when the number of loops Called; a) a0 | |Paconereheceine bona oy required is quite definite, whereas the other loops, e.g, Do..while Loop Loop is encountered, control is 7 are used when a variable, which is not necessarily the loop counter, Bnd Sub translerred back to the Do Unti : ‘meets a condition inside the loop. whereupon the loop terminates 36 | Bicel VBA in easy stepe 3. Branching and looping | 37 CS EEE Select Case The most get be so Selet the words (eg Select Cae) in the VBE and When using this Immediote window is open. Fom the VBE choose ew, immediate Window or Cui 00 see te resut of the Debug Print starement 38 | Excel VBA in easy steps Select Case is like a multiple 1 statement. The option chosen will depend on the value of a variable, Private Sub ConmandButtoni_Click () Dim x As Integer x7 ‘The value of the variable x will Select Case * determine which Case is selected case 5 MagBox "Five" tase 7 —— Since the value of xis 7, this section MagBox "Seven" ofthe code (only) will be executed, End select gna sun > End Select atways accompanies Select Case Asa result of running the program, the message box will appear as below. Microsoft Excel) From the VBE, take a look at the Help for Select Case, ee ae Select Case Statement SeeAleo Exanple Soectes ‘The Help Example is particularly useful. Copy and paste it into the CommancButton procedure. Note inthe example how the option chosen can depend on a range of values rather than a single value Note also the use ofthe comnparson operators Is < and is > A practical example A salesman receives commission which increases with his sales, For sales of less than 1000 dollars he receives 5 %. Between 1000 and 2000 dollars (inclusive) he receives 10 % For greater than 2000 dollars he receives 15 %. We want to enter the sales value into cell A2, and then click the command button for his commission to appear in B2 oe ee eee) Sale Commi aoe ae eee Ga Private Sub ComandButtoni_click() Dim sales As Single, comm As Single sales = Cells(2, 1) Value Select Case sales 7 Te sales value i obtained case Ts < 1090 Bee from the cell A2 case 1000 To 2000 ‘comm = 0.1 ‘The commission percentage is case 18 > 2020 determined by the value of sales comm = 0.15 End Select cells(2, 2).Value = sales * comm ea The total amount of commission that he receives will be calculated and appea”in cell B2 2. rarching nd loping | 39 Program development ‘We wish to write a program which will indicate by means of a message box, the number of occurrences ofa particular number, in this ease, the number of occurrences of 12, as shown below. First place eight numbers (including some 12's) in the first column of sheet as shown. ae) eee) 1 2 Z 14 3 2 CommandButtont 4 | 14 5 16 ieee 6 15 Z 12 2 twelve were found 8 10 [3 « 10 it Rather than write the complete program to do this in one attempt, ‘we will write and test small sections, and finally piece them together ~ step by step. | Write some code to output all of the eight values in column A one at atime. Private Sub Conmandbutton_Click () Dim 4 As Tnteger Fori=1 708 MegBox Cells (i,1) -value Next 4 \ End sub The row value of Cells, 1) is increased by | each time it loops fees Eight message boxes, should appear with the respective values 40 | Excel VBA in easy steps cont'd 2 Hvettemenege iano ep eles seis Ue er Wy sare mestage box playing 12 should appear 3 tes. Private Sub CcnmandButtont_click() Dim i As Intecer rori=17c6 Tf Cells (i,1).Value = 12 Then Megbox Cells(i,1).Value End If Next 4 End Sub 3 Usea counter (inthis case). and ncrementit each time that a 12s encouniere Fay, incude a MsgBox statement afer the fay fs ead report ln fe alr Private Sub ComandButton1_Click() Dim i As Integer, ¢ As Integer e-0 Tondetobeck For 1 = 1 708 I ofcoce 0 mote Tf Celis(i,1).Value = 12 Then imal paper igh the ink thay wi to End Tf inden and press be Tobey To Next 4 ‘wndert, more corey 9 MagBox Stx(e) & " twelve/s found" sxcdent& Hehighe Cond ress ma sub Sb Tab. BA 4 When the progam erin we ocr should get a message box indicating the number of 12's found, 3. Branching and looping | 41 cont'd Using a flag What if we wished to know not how many 12's there are, but whether there isa 12 ina list of numbers? We need to indicate or flag that a 12 was found. It is usual to declare a flag as a type and initially set it co Paiee, The default value of a type is False, but itis always good practise to initialize va explicitly. Ifa 12 is found, we could use an T£ statement to set the flag variable to True and afier exiting the loop, use a message box to display the state of the flag as shown, Private Sub CommandButtonl_click () mi As Integer, £1 As Boolean £1 = False For i= 1708 If cal. = 12 Then £1 = True Next If £1 = True then i a MegRox "Found 2 12 Eee te lee the fag is set to True MsgBox "12 not found* could try removing all of the 12s from the th in column A to se condition For the sake of code efficiency, the For...1text loop in the above program could be modified to include an Exit Fox as shown below, so that when one 12 is found, the For..Next could be terminated and the flag would not repeatedly be set to True each time another 12 was found, IFthe debugger were used to single step, you would see an exit from the Por....ext as soon as the first 12 was found 1t08 celie(s, 2) we need to use an 3d if because there is more than one statement to be executed if 12 is encountered cont'd Adding flexibility So far, we have written a program that searches for the number of 12's. The 12s built into the Frogram, What if we wished to search for 14 or a 15? How should we let our program know what number to look for? We will enter it into a cell (C1 in our case) on the sheet isef, and then click the command buteon to Bind ‘whether this number is in our set of numbers. ~ The number that we wish to search for is input from cell to True and the loop is exited € £1 = True The MegBox "Found a" & x aa ~ The message box wil also Meqox x & " not founé’ ~ remind us of the number ~ that we The number that we are to look foris placed in cell C1. Fully est the code by using a number which is not in column A ing and looping | 43 Loops inside loops Redce and rearonge bth cond the VOE wd be 10 92 pour code in action, 2 VBA in easy steps ‘We wish to write a program which will iterate through this table of ‘values and display them one at a time using a message box. First, use the code below to iterate across the top row only. 5 sas DE SS BA DSL = fe 12] 70 6 2 2) 23 15 24 2 3 2 a 2 a 4 Private Sub CommandButtont_Click() Dim j As Integer For j= ito __—~ The Select satementis onl cella(i, 3) .Selece inclided so that the cell will MagBox Cells(1, j).Value appear selected each time the ext j End sub) message box appears So far, we have iterated through the frst row only. In order to move down one row ata time in order to iterate through the next ‘two rows, we need another loop. The counter of this outer loop (4), will need to increment from 1 to 3, thereby incrementing the row number Private Sub CommandButtoni_Click() Dim i Ae Integer,j As Integer For i=17o3 For each ofthe 3 values of 4 For j= 1 To nee (the row number), the inner Maguox Cells(i, j).value loop cycles 4 times Next j Next i ‘Watch the selection move across and then down End Sub CommandButtont A number search ft ono one etter Type espace falowed by on underscore ond then press the Enver key Dont Forget the space! Abways test (ode unde ll endo In thie example inte calurn C (eg, 18) whch i not in colar A In previous exarnple, we searched through a list of numbers in ‘column A to find a number which was read in from a particular spreadsheet cell. What if we wanted to find a series of such numbers? In this example, we want to search for each of the three numbers in column C, one ata time, to see if they exist inthe list ofeighe numbers in column A. We need a loop inside a loop, Ts i a Di We want to 2 2 determine whether 10 : 2 4 3 i ig these numbers are 4 4 in column A. 5 16 Ofcourse they all 5 16 Ea + a are present! 3 0 [31 Private Sub CommandButtonl_Click() Dim { As Integer, f1 As Boolean, _ x Re Variant, j As Integer For j = 1703 £1 = Palee 7 The outer loop iterates through x = Cells(j, 3).Value the 3 values in column C For i= 170 8 IE Celle (i, 1) .Value = x Then fl = Trve Exit For End If Next 4 If fl = True Then the inner loop MegBox “Fcund a * & x Else MsgBox x @ " not found End If Next j End Sub Ifthe value is found in colurn A, set the flag = True and exit Three such message boxes will appear in our example 3. ranching nd loping | 45 swcont'd A program to delete blank cells We are able to delete blank cells from Excel, but the method has a Aruple shortcoming: if we were to first select the blank cells by selecting secon can 080 the whole range and choosing Edit, Go To.... Special... Blanks and emo hire then from the Excel menu, delete them using Edit, Delete... Shift sone "cells up, all cells beneath the selection would be moved up as well! How can we avoid also moving these cells up? VBA to the resc ‘Once again, rather than write the program to do this in one attempt, we will develop our program in a step by step manner, testing the techniques required as we go. % 3 i For the moment, let's make the requirement a bit simpler. Say that ‘we are now required only to move all of the cells to the right which are non-blank, as shown below. Commansuttont ‘The following code should perform that task. 46 | Excel VBA in eaty steps Private Sub ConandButtont_click() Dim d as Integer mee etc tery os ae cates a blak (empty cel) TE Cells(i, 1) <>" Then Celis (i, 2).Value\= Cells(i, 1) Value End Tf ext 1 <> means “not equal to" End Sub The contents of the cell in column | is copied to the corresponding cell (on the same row) in column 2 Say that we now require the cells in the second column to be “bunched up” wth no spaces, as shown below. BTS ae ee eed 2 2 4 16 CommandButtont “2 2 18 2 2 To achieve this, we need a counter which will keep track of the number of occupied cells in the second column. We will use as this counter and increment c each time that a cell is copied across ach time that anon-blank is found. Private Sub ConmandButtonl_Click() Dim 4 As Integer, c As Integer cra For i-1T0@ TE Cells(i, 1) <>" Then e-c+d celis(c, 2).Value = cells(, 1).value Bnd tf Next 4 The variable c keeps track of the End sub next available row in column B 3. Branching and looping | 47 swcont’d 48 | Excel VBA in easy steps ‘We will now apply this same counter technique to the values in the first colunin in order to “bunch them up”. So change celis(c, 2).Value = Celle(i, 1).value wo: celle(c, 1).Value = Cells(i, 1).value Having moved the contents of a non-blank cell up, we then need to delece the cell contents by including: celis(i, 1).Value = "" (Our code should now look like this: Private Sub ConmandButtoni_Click() Dim d As Integer, ¢ As Integer c=0 For i= 1708 If Cells(i, 1) <> "" Then e-c+1 Cells(c, 1) .Value celie(i, 1).Value celle(i, 1).Value eae ee “The intention is to delete the cell fext 4 te contents after it has been copied up Unfortunately it doesn't work. Any non-blank cells above the first blank (in this case the 12) are being erroneously deleted. We need to find a way to prevent these deletions. Try single stepping, and carefully take note of the values of 3 and c. is | When thas the value ofa nonblaris encountered and therefore c is increased to |, We don't wish this 12 to be deleted. ERE] 7 nue esto, ncaa tic reas fl | tics, 3 When the next non banks encountered of couse, bute has only been increased to 2 14 ito be deleted [e cel appears to may not be blank could havea spocel You may ike to use the Tm fancier which removes any lei oF valng Space from o sting to make sure eg Tr(Celsi!) Value) ‘We want deletions to occur only ifa cell has been moved up ~ in which case, the value of ¢ will be les than the value of 4 as we have just scen. We therefore need to add this condition in the form ofan re statement: Ifc<4 Ther.. When the necessary ££ is included, the final version should look like this: Private Sub Cenmandsuttonl_Click () Dim 4 As Intecer, ¢ As Integer e=0 For i= 1T€ Tf Celle (i, 1).Value <>" Then croel wel Fess than If ¢ < i Then celis(c, 1).value Cells(i, 1).value End If ne e a od Now the cell will be cleared only if the Bnd sub Ifa blank has yet to bbe encountered ¢ celis(i, 1).Value cell's content has been moved up a ‘The blanks have been removed. You may ‘wich to also check that no cells beneath the range have hean moved ip! 3. Branching anc looping | 49 String handling ‘We previously mentioned that a piece of text is known as a string in ‘VBA (and many other languages as well). We can use special fianctions to join (concatenate) them, split them, search for one string inside another, etc ‘We have seen how to declare and initialize Sting types: Dim sti As String, st2 As String stl = "house" : st2 = "boat" Concatenation ‘To join wo strings, use the & operator. Cells(i, 1) = st & stz ‘ “house” and “boat” are concatenated to give “houseboat” Place these lines of code into a command button procedure. Run the following lines of code as well. Left ett extracts the'lefimost characters from string, eg, celis(2, 1) = Left (sti, 2) 7 ‘The 2 leftmost characters of Right “house’, ie. "ho" are extracted Right extracts the rightmost characters from a string, c.g. cetis(3, 1) = Right(st2, 2) 7 ‘The 2 rightmost characters of Instr house’, ie, "se" are extracted Instr finds the position of a substring in a string, e.g, cells(4, 1) = Instr(sti, "us") ‘The position of the string “us” inside the string “house” is found — at position 3 50 | Excel VBA in easy steps Mid Mid extracts a substring, eg. celis(S, 1) = Mid(st1, 3, 2) position 3 and of length 2, ie. "us" is extracted Len en simply finds the length of the string, i. the number of characters, eg celis(6, 1) = Len(st2) \ “The length o” the string “house” is determined, Le. 5 characters. ‘The results ofall of these lines of code is shown below: I ees Lef("house",2) Right(house2) 3 ae Instr(house’s'us") 3 — Midhouse’, 3,2) Len(hovse") ‘When using the wid function, if we don’t specify the last number, the substring extracted will be the rest of the string to the right, from the position specified, e.g. if instead of eth Mid(*house", 3, 2) which produced “us”, we used Maenboonon Mid (*house", 3) chen “use” would result. When extracting au shar haractrs tothe right from a string, chem faction is ‘neste soe8 surprisingly more usefil than Right, since it is usualy more __ (ated e008 convenient to specify the starting position for string extraction, os ree rather than the number of characters to the right to be extracted. "nouse” & "boat" 3. Branching and looping | $1 To rearrange a string We are given a person's full name, e.g, Jack Robinson. We wish to convert this to the formar Robinson Jack ic. the str bya comma (no space), followed by the Christian name, We require this technique to work for any Christian name-surname pair. First we must extract the Christian name. me followed Before that, we extract all of the characters to the left of this position (the C name). We then need to extract all of the characters to the right of this position (the surname). Finally we can concatenate the hristian name (in that order), not forge ed to find the position of the space. We can then Place the full name to be processed in cell Al and run this code Test it by trying a different full name in cell Al ‘This technique could be employed for example to loop through a set of full names in the column of a spreadsheet and place the names with the modified format in the next column to the right as shown below A Eee | 4. Jack Robinson Robinson Jack 2 ee DeMaggio DeMaggio,loe 3 James L 4 Objects and the Excel Object Model ‘We often hear how computer programming has became “object-oriented” and indeed it has. Whereas Excel VBA is not a truly object-oriented language, ‘we learn in this chapter what an object is in its simplest form, and how objects are categorized in the Microsoft Excel Object Model. Properties and methods 54 Object hierarchy 56 The Microsoft Excel Object Model 57 Other properties and methods 58 ‘Object variables 63 ‘To sum numbers according to color 65 Chapter Four Properties and methods ‘An object has properties and methods. We have already met an ‘example of an object the Range object. Properties are something which an object has, whereas methods do something. As we will now see, properties and methods are associated with an object by means of the dot operator (period/full-stop). 3 4 ‘CommandButtont ‘The ClearContents method will clear the contents of a cell Itis the VBA equivalent of the Excel Edit, Clear, Contents command For example, the fo lowing code will clear the contents of cell Al. Properties ‘An object can have more than one property. Properties have values, ‘They are usually preceded by che dat operator and then the object, ‘thereby associating them with that particular object, as we have | seen with Range ("AL") .Value for example, Recall that Value is Private Sub Commandsuttoni_Click(} the default property and could therefore be omitted. Range ("Al") .ClearContents End Sup ‘The Count prot ’, when applied to Range objects indicates the number of elise corespocing range Fo sale “The Clearcontents method of clearing 2 cell as above, i an alternative to the mare primitive Range ("AL") Value = wwe saw previously. that Private Sub ConmandButtonl_Click() MagBox Range ("A1:A3") count End sub Recall that the IntelliSense drop-down will appear (in this case after the period is typed) to show us a list ‘of suggestions.’ ‘The The number of Suggestions are ether methods (the “fying green bricks”) or cells in the range ~~, properties (the “pointing fingers”). ALAS is3 ei Private sw CormandButtont_Citckt) [eco] Range ("Ai") «| End Si <6 clear * Clearcomments Methods al Methods usually perform some operation on the object with which <2 Cunfomats they are associated, We have already briefly mentioned the Select aca method, which we used to selec a single cell. We can even use the et Cournn Select method to select more than one cell If this code is run, a range of cells A1:C2 will be selected as shown on the next page. Private Sub ConmandButtonl_Click() Range (*A1:C2") .Select End sub 54 | ca VBA ney steps 4. Objects and the Excel Object Model | $5 — Br re ttamentima - - Object hierarchy The Microsoft Excel Object Model ‘Objects can belong to other objects. The dot operator is used to Range and Font form part of Excel's object hierarchy ~ the Excel associate objects. ‘Object Model, Here is a small part of it. For example, the Font object belongs to the Range object. Being Microsoft Excel Objects an object, Font has properties, e.g. the Bold property. The Font soreseraton of We will discuss the object isa little exceptional however, as it has no methods. Oe | peplcauon Workbuok For example, to make the contents of cell Al bold, we could use: Help wilvary and Worksheet objects lhl th Excel version Range ("Al") ,Font.Bold = True Inueter srartere Object or property? lE.we consult the VBA Help for Font, you will find a brief indvpemeble description of Font as a property, and Font as an object where you eee aye reser will find a comprehensive list of the Font object's properties. Font, be dcowogea (also described as as it appears in code is a property. It isa property which “produces” things a nt cles 25 F_collections by the legend = a Font object. We say that the Font property recurns a Font object. Ceiceen a sear reer Coens? The distinction between the Font property and the Font object is objects which have the amg iiewan) Somewhat academic. For all intents and purposes, it is the aera Ino the VBE. hphiphing e and properties and methods of the corresponding objects that we wish shen pressing ie F Ke. raher 40 access, s0 to that end we ought to navigace in the VBA Help to thon vang the Hep oa bo% the respective objects — in this case the Pont object andl ascertain its properties (and usually methods) ~ for example, the Bold property ‘methods, which we will also discuss later Leven Ambgity Tris mo less confusing wo hear that Range as it appears in code as Tie ancecten confuses! Ranges above, is also a property. It is a property which returns a Range Jobject only aaeste obeet swe ick on an object Suretbere”” Instead of the Range, of course we could use Ce21s. to get Help on that Properties og Celt, ActeCe eee Cel1s(2,1) .Font.zold = True particular object ‘cole, as it appears in code, as above, is also a property! Ifyou earch Fibip for coi ta, you pill eenpe dt b described sa The Object Model enables us to Yeamares property (there is no cats abject). ces sa property which esxtablch which objects belong to eing tts Range cj hee ae many ter ropes wich Mh uaine nee eres ee reeurn a Range object). In practical terms, this simply means that in Sra ARUN See Seon ee ee ee seine oat ests bu ths dessfeoton_ locate the properties and meth 1 Range objec ‘fps “Appics To" ona rots ba ths densfcoon locate the properties and methods ofthe Range object Baa “re ft et bol Reade Wart, x particular indvicual property or seeking the propenies and methods of te Range ajc method page to establish this Example 56 | Excel VBA in easy steps 4. Objects ane the Excel Object Mode! | $7 Other properties and methods Formula ‘A formula is “copied down” when the single formula is “pasted” into a range of cells as shown below: VBA in ea The Formula propery ofthe range object is used to inser formula into a cell. ? : First place a value into cell A1 and then run this code: Private Sub ConmandButton1_Click() Range("Bi") .Formla = "= Al * 2" End sub Take care not to include a space before the second equal sign aA Soh roe ae CommandButtont The formula will be placed into cell BI and the result calculated Operations using properties are of two types: property read and property write. By assigning some data (a formula in the case above, but usually a value) to the property, we perform a property trite On the ote hand asthe fllowing piece of code shows we can also read the Formula property of the particular Range object if the formula is still in place. : a Private Sub CommandButtent_Click() Dim x As Variant x = Range ("Bi") ,Formula _ Megkox x End Sub For a property read, the ~~ property is usually on the right hand side of an equal sign (whereas for a wort ei is usually on the let) [ezocey ~~ The formula in cell BI will be displayed seivate Sub ConmandBut toni Click () Range ("B1:83") .Formila = "= Al * 2" End Sub “The formula automatically “adjusts” down the column. Ofcourse, to prevent the formula from changing when copying, down, we could specify an absolute reference. Range ("B1:B3") Cormula gi #28 FormulaRICl eormulaRict is usec ina similar manner to the Formula property, except that Formilaeic1 must be used in code with RIC style Formuia can be used with both Al and RICI style. For example, to place a formula ina cell AL which would refer to the contents of cell C2 (row 2, column 3) we would use: Range ("A2") .FormulaRiCl = "= R203 * 2 * 02 8 Commandeutton’ There is really no preference over the use of FormulaRICt or Formula, As well as formulas, both can be used to place values into a cell. The use of Form2aR1C1 will be seen in code resulting from the use ofthe macro recorder, in statements such as ActiveCell,FormulaRiCi = "2" as we will see in Chapter 5 Objects and the Excel Object Made! | 59 -.cont’d 60 | Excel VBA in easy steps Address The Addzese property will return the address of a parti It is a String type. fa particular range, Selection ‘The Selection property will return a R return a Range object representing the selected cellor cell Ieretumnsa Range ype, nS First select some cells on the sheet CommandButtont Sil When the code eon is ran a mesage bos wl address of the selection. 7 _ Private Sub ConmandButtont_Click() MsgBox Selection.Address End Sub ‘The Address of the range selected is Mlerosot Exc sages [execu retumed, At present, itis specified as an absolute reference (the default). See the VBA Help if you require a relative reference To simply emphasize that the Addzess property is indeed a Sting type, for the exercise, we can arbitrarily introduce a variable of string type as shown below to achieve exa of sexing ype a exactly the same result Private Sub CommandButtant_click() Dim st As string st = Selection.address MegBox st End sub -.cont’d For Excel 97 made to change certam properties by means of@ command button Colendex beng one of them. fete necessary tet the TekeFoeusOnck propery of the command buton to Fe See Chapter 9 on sting command button properties Th sve wos resaed for Excel 2000 onwards ColorIndex To change the font color of a spreadsheet cell, we can use the CoLortndex property of the Font object: private Sub CommandButten}_click() Range ("AL:A2") .Font .ColorIndex= 3 End sub Running the code above will change the font color ofthe 3 calls in the range Al:A3 to red Ree Oma 3 #1 ‘The value of Co-ex:Index isthe offier ofa particular color in the Excel color palete of 86 colors. The respective colors in this palette can be reassigned from the much larger range of colors available overall by using the Colors property (see VBA Help and overleaf for more information), but at any given time, only 56 colors are available. As demonstrated above, at present the color which is at offset 3 is red A convenient wey of determining the ColorIndex of a particular font is to first apply the font color toa spreadsheet cel, select itand then determine its Color index using a message box to display the value, eg. MsgBox Selestion.Font .Colorindex ‘You may be surprised to learn that the Colorindex for the default font of a cell in an Fxcel spreadsheet is not black, ic. it is not 1; it has the avvlovard value of -4105. Fortunately, Excel VBA assigns this value to x colorindexhutonatic, an Excel VBA built-in constant, so to change the font color of cell Al back to “black” we could use: Range ("AL") -Font ColorIndex = x1ColorIndexAutomatic 4 Objects and the Excel Object Model | 61 -cont’d Dent confse the elo propery shown hee ith the Coors propery which sued to charge the defut poet, 2g ActeWarkbooCaore(S) = RGB(2S5, 0,0) which wi! ange the cae with Cladnder Sine palete toed 2 | Bacal VBA in exty steps Pee Color Font colors can also be assigned using the Color property, eg t0 change the font color of cell Al to green we could use Range ("AI") -Font.Color = 65280 ‘These values will not seem to follow any pattern unless you are familiar with hexadecimal. Fortunately, there are two ways of getting assistance with assigning these constant values to the Color property. One way isto use the RGB finction, The RGB function has three numbers corresponding to the red, green and blue components respectively. These three numbers can only take values from 0) ¢0 255, depending on the amount of each of these primary colors, e Range ("Al") .Font Color = RGB(0,285,0) would achieve the same result as using the code above, ie. the cell's font color would be changed to (bright) green. Secondly, we could-use the built-in Excel VBA color constants, eg. Range ("Al") .Font color = vbGreen The line above will also cause the font color of the cell to be changed to green, exactly as before. It's interesting to single step the code and hold the mouse cursor ‘over the vbGreen constant to reveal its equivalent numerical vale ‘Whereas the VBA Help may be litle overpowering when trying to determine the values of these color constants (where they are given as hexadecimal), it may be more convenient to search for them using the Object Browser (press F2 from the VBE). Object variables ‘ristake to forget tose Set ‘We have seen how to declare and assign variables, eg. Dim 4 As Integer i22 Similarly, we can declare variables of the generic Object type. ‘When assigning an object variable, use the Set keyword. Dim y As Object Set x = Range{"B2:C4") ‘Whereas this code will perform perfectly well, it is more efficient if wwe are more specific as to the exact type of the object variable, ie. Dim x as Range Set r= Range ("B2:C4") ‘A Range variable is useful when used in combination with the cel 1s property. The cell reference can be specified relative toa Range as shown here, Private Sub CommandButton1_Click() Dim r Ag Range Set F = Range ("B2:C4") made relative to the range r For illustratior, place a border around the range B2:C4 7 oe +] ‘CommandButtont When che code is run, this cells selected, Calls(12) now refers to the cell of the Ist row and 2nd column of the range B2:C4 4. Objects and the Exel Object Mode! | 63 64 | Beco! VBA in easy steps ‘When ce11s is used with a single index (and without an object qualifier), it will refer to the cells on a worksheet, counting, from lefé to right, eg. celis(s) Select ‘would select the third cell of the top row. Ce11s wraps around, so that in the spreadsheet of 256 columns, cells (257) select would selec the fist cel ofthe second row fer wrapping around the first row as shown here. i It is particularly convenient to use Ce12s with a single index to loop through a defined range. For example the following code will loop through and display the first eight cells of the range AI:A8. Private Sub CommandButtent_Click() Dim rag As Range Dim 4 As Integer Set rng = Range (AL:A8") ae ees es ‘The value of the ith Msgbox rng.Cells(i) .value cell in the range AI:AB os oo 1g ie epee] 2 aS HH} 2 liza a3 a 8 E To quckiychonge the frt color of Incindl cls 0 Excel dekon @ cl concoring thot clo, double cick on he Fernat Painter button onthe tool br, and then cick 0 he cll to whch you mh fo opply the co trang Excel 97,21 TotefecisOntlek to Fale when sng Clochdex wth o commend btn, To sum numbers according to color Excel does not have any worksheet functions for dealing with font colors. For example, if we have alist of numbers that we wish to suum of sort according to their color, we will need to write some code. Here we wish to sum red and blue numbers separately, and display the respective totals using a message box. ‘We want a message box to appear displaying the respective totals Place eight numnbers in the frst column colored red and blue ESE Ame SB sebe TAB zi Nas ass [ae 5s a) aa @| 46 | Teameltteredvaber 56 tg Wedel tebe vaicscas 10 nal iW x 2 ‘Once again, we will develop our code in easy steps. | First modify the code on the previous page (modify the MsgBox line) to display the Colorindex of the eight consecutive cells by means of the message box as shown below. MagBox mg.Celis (4) .Fent .colortndex Ensure that only the «wo Colorlndex values 3 and 5 ate displayed, otherwise the code overleaf will need to be modified accordingly. 2. The use of Select Case wil eater or each of he posite vals of ColorIndex. We also need to include the mechanism for sureing the eel values, which we can do by using the variables sured and surBlve te keep runring totals, which are updated on each pas ofthe oop. 4, Objects and the Excel Object Model | 65 The complete code to sum numbers according to their color will then be Private Sub CommandButtent_Click(} Dim rng As Range, i As Integer, ci As Integer Dim num Re Single Dim sumRed As Single, sunBlue As Single sunRed = 0: sunBlue = 0 ‘se! c . Set rng = Range ("A1:28") For iz1To@ jo all 8 cell ei = mng.Cells(i) . Font .colorindex num = rng.Cells (i) .Value Ia red cel is found, the Case 3 value (num) is added to sumked = sunRed + num aa the red total sunBlue = sumflue + num Sera Likewise for the blue cel Next £ ve MsgBox "The sum of the red values ist &_ We, comnvston | Sex (sumRed) & vbCrLE & _ BS fpoeampae "TRE sun of the/blue values is" & str (sunslue) End Sub before VOCrLE (carriage retur-inefeed) is another of the VB built-in constants, It forces the string following to be output onto a new line As a result of running this program, a message box otight to appear displaying the respective totals. ec The sum of tho rd values i 5 Theat u Ute vase 203 66 | cel VBA in easy steps The macro recorder Not only are you able to write Visual Basic code using the Excel VBE (Visual Basie Editor), but you can get Excel to write it for you using the macro recorder! ‘We learn how to record a macro, and discuss its advantages and shortcomings, To record and run a macro 68 To edit amacro 70 Project Explorer 72 Macros avalable to other workbooks 74 To run a macro from a toolbar button 77 Chapter Five To record and run a macro ‘We will record and run the simplest of macros, a macro which will place a number into a cell when we press a certain key combination, To record the macro ‘Our macro will place the number 2 into cell Al when we press the Ctr+q key combination, | Betore we start recording elect any cll par rom cell Al, From the Excel menu choose Tools, Macro, Record New Macro, fama mL hse mm 2, Accept the defat rame for 3 Choose This Workbook. Be careful not to select the macro. In future you may wish to give it a more ‘meaningful name, Personal Macro, Workbook at this stage. Choose the key ‘combination rs ee 4 un the macro (Cirita). 5 Glick OK. 68 | Excel VBA in easy steps The macre recording your ‘very move mistakes induced If yeu do cose the Sop Recording box 9 errr, you vil reed to choose ew, Toolbars, Stop Recocng fom the Excel man t9 sch t ck on we the mac recording! he] : ‘ an se both ok eco ar can see the mac (VBA) c mite before your ery ees! The Stop Recording toolbar appears a 5 ; (aes a i 6 Clckinto cot A, type 2 and then press Enter T. Clckte Stop button he sold lve square). Do rot eck the Close button 6 to dose this box Congratulations, you have just recorded a macro. To run the macro If the 2is still in coll AL, delete it Axo eee eros os 2 [eles | From Excel press Cirttq, The 2 should appear in cll A That's all it takes to run an Excel macro! 5. The macro recorder | 69 70 | Excel VBA in easy steps To edit a macro ‘We will now view and modify the VBA cade produced by the macro recorder. | From the Exce! menu, choose Tools, Macro, Macros. A code moduile now appears (sce next page). Note the name in this case ~ Module1. Unlike the code modules that we have seen in the past, this is a general purpose code module (generally known as a standard code module) for the whole workbook, whereas the ‘modules that we have seen so far were specific to and only available for that particular worksheet. ‘The Macro Recorder frequently uses Select ‘Comments have and ActiveCell (another property which been automatically returns a Range object). We will show how Placedin the code this redundancy can be remaved below 2a Microsoft Vibual Basic - Book1. xls [design] -[Module1 (Code)] 09/2004 by ea Clicking the \ Keyboard Shortcut: cerita virgata Range ("Ai") -Select ActiveCell.FormulaRici = "2" button, with the ‘will also be includec Removing redundancy Remove Select and Act:ivece11 from the macro code and make one line as shown below. Range(*A1") .FormilaRi¢i = *2" Ifthe macto is run again, the result will be exactly the same, ic you will see 2 placed into cell AI (if it is not already there). Project Explorer Project Explorer displays all ofthe code modules in a project. Ie can be used to iew the coe tnt you have writen nthe respective code modules, aswell as that written by the macro recorder. | To view Project Explorer, click View, Project Explorer from the VBE menu or lice the Project Explorer button on the VBE toolbar. ge your sands he VBE you wh Explorer window t appear locked 0 Shown, The VBE windows eae Unfonunately. to Vinson Repay factang 2 fare Double click on’Madule| to see the macro code. This module may or may nat appear in a folder, depending on the state of TogeleFolders, task forthe “aires Vial Basic Book xl [desig] - sheet (Ce) ‘You can also double click on a sheet module to View any worksheet code which may be present 72 | Face VBA in easy steps swcont’d The macro recorder can be code skeet which to place experimental code in preference to using o command button Ifwe were to now record another macro, the code would appear in the same module (in our case Module!). If, on the other hand, we "were to starta new session (i. close and reopen our Excel workbook), and then record another macro, then a brand new module (Mochule2 in this case) would appear with the new macro code in it ‘The macro recorder is a truly outstanding feature of Excel. Itis not present in Access VBA nor stand-alone Visual Basic, which is further reason why Excel isin many ways a preferable environment for learning Visual Basic. So why don’t we jast use itall of the time? Because the macro recorder will not produce code for loops for example, (¢.g. Fox..21ext) and other conditional code (e-. 1£...then) which is really what programming is all about! ‘When should we use the macro recorder? ‘The macro recorder is invaluable when we need assistance with cour code. For example, if we did not know the code needed to change the font color ofa cell to red, we could simply change the font color of a cel to red whilst recording a macro, and then inspect the code. All will be revealed if we then eurn to the code editor and find a line like this: Selection. Font ColorIndex = 3 5, The macro recorder | 73 74 | Excel VBA in exey steps Macros available to other workbooks ‘We wish to record a macro which will be available not only to the mao open workbook, but to all other workbooks that we ight open in future. We will record a simple macro to appl Currency formatting to a cell - | Select the cell that you wish to format. 2. From the Excel menu, choose Tools, Macro, Record New Macro, 3 Give the macro a name, eg. 4, Choose Peseral Macro Workbook CurrencyFormat Sto 5, Choose the key combination that we would like to use to run our macro (eg. Ctrtw) 7 Fort a call as Curency Gamat Ceti, Number, Currey, OK) ~ the cel may or may not have a vale in it 6 CickoK. ick he Sup Revorcng baton You may wish to now run the macro and/or view its code Project Explorer con be oxcesed from the VBE by wing Crt, val show projects rk SB ‘This all seemed very straightforward, buc quite a bit has happened behind the scenes, From the VBE, take a look at Project Explorer. We have anew You could workbook — also see the Personals macro code Jouble- : Be ‘shestt (Sheet!) clicking on aoe its module Personals isa hidden workbook which is automatically created when we choose to make macros available to all workbooks. To vview Personal.xls, use the Unhide dialog box shown below; choose ‘Window, Unhide... from Excel. If you do unhide it, hide it again. ao hi wea Close the current workbook (save it or not) and close Excel. When asked whether yeu want to save (the changes to) the Personal ‘Macro Workbook, choose Yes. Personal.xls will now forever be opened antomativally as a hidden workbook whenever you start a new workbook (unless you choose to delete it). Ifwe had chosen not to save it, our macros recorded in the Personal Macro ‘Workbook would be lost. 5. The macro recorder | 75 cont'd Se Confirm that the macro will run in any workbook by opening a new workbook and pressing Crtrw in order ‘to run the macro (to format a cell as Currency) Where is this Personal.xls workbook saved? In the XLStart folder. How can we confirm it is there? Do a file search from Windows: Start, Search etc. ~ making sure to search for hidden files as well. Ifwe were to delete it from this folder (make sure that Excel is closed first), it will no longer open automatically when we start Excel, but of course all of the macros contained in the Personal xls will be lost. Since we will need the Personal.xls macros for the next exercise, retain it for the moment. 76 | Excel VBA in easy steps To run a macro from a toolbar button ‘We will now place button on the toolbar and associate it with the ‘macro that we have just written In order to place a toolbar button on the Excel toolbar, from Excel, choose Tools, Customize. 2. Choose the Commands tab. 4, Draga button rom here nto the Excel oo 3, croose Macros veavacm | penercue 5, The macro recorder | 7 Td With the Customize dialog box stil open right- click on the button and chose Assign Macro, ZA SLO 20 | UE a ok Choose our maero and click OK, ee acorme [alpen lrboole ogo eared 1903/2005 by wt Click the Close button on the Customize dialog box, To run the macro, simply choose a cell that we wish to format and click our button on the Excel toolbar: Note that this button ‘will appear on every workbook that you open in future. Ifyou delete Personal ls, Excel will complain if you click i! Ifyou wish to remove the button, open the Customize dialog box once again and simply drag it off the toolbar: 78 | Excel VBA The Worksheet object In this chapter we consider the properties, methods and events of the Worksheet object, and introduce the concept of the collection as it applies to the Worksheet object. We learn that events can be made to trigger by doing something as simple as clicking on a worksheet. Worksheet properties and method: &0 Collections 81 Cllection properties and methods 82 Calls columns and rows 84 Worksheet events 86 Automatic sheet entry 91 Worksheet names | 93 ; Worksheet properties and methods When the log asg fer care decline ably defete the Te rintOut preview 0 poge 80 | Excel VBA in eaty step Each worksheet in an Excel workbook is represented by a corresponding VBA Worksheet object. As an object, the worksheet object has properties and methods. This example demonstrates the Name property and Delete method respectively, Private Sub Conmandauttent Click() MsgBox Activesheet Name Activesheet Delete End sub ‘When the above code is run, a message box will appear with the name of the current sheet. lick Cancet ‘The PrintPreview method can be used to emulate the pressing of the Print Preview button from Excel, eg. Private Sub CommandButtont_CLick () Activesheet .PrintPreview End sub Similarly, if we wish to actually print the sheet we could instead ActiveSheet Printout Collections @ cing" the object eg Roms ton of Range ebect= whereas Row isos a property A collection isa group of objects which have the same properties and methods, A collection allows us to deal with the objects a5 2 unit, The name ofa collection ofa group of objects is almost always, very conveniently specified by adding “s” to the object. For ‘example Worksheet objects are contained in the Worksheets collection. Each object ina collection can be referenced by an index. A collection is particularly useful for iterating through group of objects. For example, if we wished to find the respective names of three workbooks, we could use 4 as an index to iterate tHrough the collection as follows: Private Sub CommandButton1_Click() Dim i As Integer For i= 1703 MegBox Worksheets (1) .Name Next i End Sub Bite umber of worksheets in this workbook aT Three message boxes will appear with the respective ‘worksheet names Note that the index of the Worksheet object corresponds to the corder in which the worksheets appear atthe bortom left of the Excel window. This is most important to remember, in case the end user of the spreadsheet decides to swap them around! In ancicipation of th’, CodeNane could be used to refer to the sheet in preference to Waza as we shall see atthe end of this chapter. ‘Try running the above code again, but this time first swap the sheets around so that Sheet? is the first sheet. Now the fist message box to appear should cleplay Sheet? — the first abject in the collection ‘Sheet? )sheet { sheot3 / Ogos Te | Autoshapes” Se LOB eat he Worksheet object | 81 Collection properties and methods 182 | Excel VBA in easy steps Collections have their own properties and methods. ‘The count property reveals the number of items in the collection, © Msgbox Worksheeta.Count will indicate the number of worksheets in the Worksheets collection, Count is particularly useful when we want to loop through a collection as shown below. Private Sub Conmandbuttonl_Click() Dim i As Integer For i = 1 To Norksheets.Count Megbox Workehests (1) .Name Next i End sub 4 — Worksheets Count specifies the total number of worksheets Just as we can add a worksheet from Excel (Insert, Worksheet etc), we can add a new worksheet by using the Add method of the Norksheets collection to add a new Worksheet object to the Worksheet s collection Worksheets.ada will add a new worksheet before the active worksheet. ‘The Remove method, in general is used to remove an item from a collection, but it seems that we are only able to remove a Worksheet from the Worksheets collection via the Delete method of the Worksheet object. For example, the following line of code will effectively remove the first worksheet abject in our Worksheets collection. Worksheets(1) Delete The first worksheet at the bottom left ae of the Excel window will be removed zz swcont’d sig a foop to dllted the mainder wi IF ou wih o delete tem a delete them backwords fs) sould be se the -geere Object ‘ype, eg. Dim wks As Ob isnot recomended i spe Another quite amazing feature of the collection object is its ability to renumber itself when an object is added or removed. Accordingly, you will need to keep in mind that Worksheets (3) for example, will not remain Worksheets (3) ifa sheet has been added or removed before it, We can declare a variable asa Worksheet type, just as we can declare variables t be of Integer or Range type, ¢. Dim whe As Worksheet Ifa collection is clever enough to know how many items it contains (Count), then perhaps we shouldn't have to specify this number at all - and indeed we don’t! The For Sach...Next loop is a special loop which does not require us to specify the number of objects — ‘twill iterate through the collection until it runs out of object. Private Sub CommandButtont_click() Dim wks As Worksheet For Each wke In Worksheate MagBox wks. Index Next wks End Sub sis fees The Index numbers of the workshee's will be displayed sequentially ‘Teen is another of the properties of a collection, but it is a default property and accordingly, worksheets (1) .Ttem(1) for example, can be written equivalently as Worksheets (2) , which serves exactly the same Furpose. For example, the following two lines are equivalent: MagBox Worksheets. Item(1) .Name MsgBox WorkSheets (1) .Name 6. The Worksheet abject | 62 Cells, columns and rows 24 | Excel VBA in ex step Cells Each individual worksheet can be considered to be composed of cells. Each individual cell is a Range object. To select all of the cells of the first worksheet we could use: Worksheets (1) .Cells.Select —_ Cis retums all of the To select the first cell we could use: cells of a worksheet Worksheets (1) .Celle(1).gelect —_ Cells(1) isthe first cel Columns Notice that above we said that the Worksheet object “can be considered to be composed of cells, because it can also be considered to be composed of columns or rows (each of which is a Range object) depending on what is convenient at the time! ‘The Columns property returns all of the columns of a particular worksheet. Columns (2) for example, would return the second column on a worksheet. We could therefore select column 2 using: Worksheets (2) Columns (2) select Rows Similarly, the Rows property returns all of the rows ofa particular worksheet, so we could select the second row of the first worksheet with: Workslwess(2) -Rows (2) .select Cobra propery wh Fetus 0 Ronge Count Ieis interesting tc use the Count property of Columns to determine the number of columns on a sheet. Note that we don’t bother to specify the worksheet here — it is assumed to be the active worksheet (act Avesheet). MegBox Columns Count ce Similarly, use the Count. property of Rows to determine the number of rows. MsgBox Rows.count ColumnWidth Rows and Colum are themselves properties which return collections of rows and columns respectively. To change the swidth of all of the columns of a spreadsheet for example, we can take advantage ofa collection’s ability to deal with all ofthe ‘objects in the collection as a unit. For example, to change the ‘width of each column of the active sheet we could use Jume.Columiidth = § where 5 is the width of each column in characters. The above is an example of writing to a property. Since ColumnWidth is a read/write (variant) we could also read the property using: Msgbox Colums.Colunnivideh Sheet object | 85 86 | Excel VBA i Worksheet events ject can have ‘As well as having properties and methods, an obj events. An event isan action that is performed by the user, such as cling mou or pressing ky. An event pocede code tha will trigger (via the operating system) whenever the corresponding event occurs. To write a worksheet event (Selection Change) | Make sure that Project Explorer is Visble and then double cick onthe sheet name (Sheet! this cse) 0". Ck onthe Object drop-down and then select Worksheet access its code module 3) The SelectionChange event procedure “template” appears by default. Click nit and write the code shown onthe next page. you inavertey create another ever, delet it and choose the SelectonChange event procedure | The Select ionchange event is triggered whenever the user changes the selection on -he worksheet, for example if the user clicks on another cell on she same worksheet. Like all other Norksheet: events, it will only work for that particular worksheet Negox Target Address : a a ma Sub Note the ine continvat character shown here which you may not require in your code 4 When the user clicks on another cel, the message box appears displaying the address of the cell that the user clicked on, 042 lathe Make sure that the Design Mode button is not depressed — your worksheet event will nat fre ifit is Confirm that this event wor't trigger for another worksheet, by selecting a cell on another skeet. 6. The Werksheet object | 87 The Worksheet_Change event ‘The Change event occurs when the user physically ch ie the user physically changes the contents ofa cell on the sheet Before stating, make sure to comment out or remove the code in the SelectionChange event from the previous example so that it won't trigger when we are testing the new event | Hthe code module is not 2. Click onthe truten youcice ready visible, double-click Procedure drop- Ror ee con the required sheet in down and choose wit ptetire Project Explorer as before the Change event. ‘5 placed in your ode sheet thot you don't want simply highligh and delete Plce some code inthe Change ever which tse ies the contents of 9 cl 2g Cols.) abe = 2~ you vl get chain reaction. Tis reuly-changed cal wl tigger the Change event ~ wil charge the ce ~ wl ngger he C Cis Breck Appcovon EnableEverts wil tenable us to prevent dhs chan reaction as we wise eer 3 Pace this code inthe Worksheet. Change event procedure rs Private Sub Worksheet_change (ByVal Target As Range) Tf Target. Value > § Then Target.vont.ColorIndex = 3 znd sub 4. Typein some number. If esngo version ofxcel fom [1 After a number 2000 on, make [2 4 ee aa sure that Extend 6 es : Is (ae) Ea! entered, it tums red fren and formas tre off (Tools Opis. Ea) to vad spureus formating ef 88 | Excel VBA in easy steps wwcont’d Befreighlck doesnt meen before your BeforeRighlck ond BN sciredowlecick GornmandButon| Ch() event The Worksheet _BeforeRightClick event BeforeRightClick means after the user has right-clicked, but before the right-ciick event reaches the operating system and is acted upon. The default behavior for the right-click of course, is for the context-sensitive pop-up menu to appear on the spreadsheet. If we do not wish this to occur after a right-click, set the Cancel property of the event to rue as shown below. Private Sub Yorksheet_BeforeRightClick (yval Targe: As Range, Cancel As Bool cancel MegBox end sub True ight click” ESE EEEE The Worksheet _BeforeDoubleClick event BeforeoubleClick is very similar to the BeforeRight Click event, except of course to Taise the event, the ser must double~ click a cell and in chi ease setting Cancel = ‘True will cause the dfaule cell editing behavior to be canceled. Private Sub Worksheet_BeforeDoubleClick _ (ayval Target As Range, Cancel As Boolean) cancer Magox "Double Click" End sub 6. The Worksheet abject | 89 -scont’'d The Worksheet Calculate event Microsoft Excel Help (not VBE Help) states “By defaule, Microsoft Excel automatically recalculates formulas when the cells that the formula depends on have changed!” cel it ‘The Workshest_Calculate event will tigger whenever a recafuiote calculation occurs. automaticaly only ad oo i Cateaaten eee (eG eeeei ye erea Gon x see another (se below). Place the Worksheet_Calelate cove = shown below in the code motile ofthe worksheet, voce to pa fay Tate (a) Oe met Private Sub Worksheet _Calculate() MsgBox "Recalculated" Bnd Sub De cares be ke onidicy acts dee ne oe censvild mrete erate Gar ened terface your Caledon rae at set Ate ae Beanie rai cathe Cece ee) Festus This Worksheet_Calculate event only triggers when a recalculation occurs on this particular worksheet. What if we want the Calculate event to trigger on any worksheet? We need the Workbook _SheetCalculate event of the Workbook object which ‘we will meet in the next chapter. 90 | Excel VBA in easy steps ee Automatic sheet entry We have below a workbook which contains three sheets. The first sheet isthe Invoices sheet which contains records of recent dividend payments for each customer: Caldwell and Crossfire who have their respective account details on the separate, correspondingly-named sheets. We wish to be able to double-click fon a customer's name on the Invoice sheet, and have the respective sheets automatically activated, in order that the payments may then bbe manually entered on that particular sheet, We wish to. aie c A | double-click on jpceout Date Diddend adientrameto 3 [Crossfre""02022004 733.51 activate the pa} sorrespondin S. = ae . i C¥ w\inwoices { Crossfire { Cadwell 7 Ready Place the code below into the BeforeDoubleClick event of the Invoices sheet. Private Sub Werksheet_BeforeDoubleClick _ (eyval Target As Range, Cancel As Boolean) cancel = true Worksheets (Target Value) Activate End Sub The value in the target cell will be the name of the client, which corresponds to the name of the sheet to be activated ‘When we double-click on Caldwell (cell A2) for example, in the: Invoices sheet, the Caldwell sheet should become activated as shown: Seiler TaD Te Date Dividend aEERE| W€ > WIN nwo { Crosstre ), Caldwell, 6 The Worlsheet abject | 91 s-cont’d Sece we re not Using the Select rmatiod to select worksheet is nat essen thot we Acoote tre shes ie we could ame the Worasheets Target Vai) Acate tne unless we wore meditelyvgulcheck the ew ent, At presen fwe cal wih no wl acu, To provide for this we eld ether trop the rnin eo, or in by meors of @ message box that ‘he user doubleclcks ony the pevnssbie ele Both ofthese remedies wil be considered later, 92 | Excel VBA in easy steps Ir would be more usefull perhaps, o also automatically update the entries on the chosen sheet. This could best be achieved using the Offset property of the Range object which will be considered in a later chapter. For the moment, sufce it to say that ‘Target .Offset (0,1) .Value would return the value contained in the cell which is one cel to the right ofa cell that we double-click. ‘With this knowledge, we can actually update the respective sheets as well as choosing them. After double-clicking on the respective names, each of the two sheets ought to be updated with the date and dividend value as is shown here for the Crossfire sheet: ee ee) Date Dividend o2m22004 233 61 in «> iN invoices | Crossfire { Caldwell “The following code should achieve that. Private Sub Worksheet. BeforeDoubleclick(ByVal _ Target As Range, Cancel As Boolean} cancel = True Worksheets (Target. Value) .Activate Worksheets (Target Value) .Cella(2, Target offset (0, 1) .Value Worksheets (Target. Value) .Cel1s(2, 2) .Value = _ Target Offset (0, 2) .value ef * Target Offset(0.2) isthe cell which is 2 cells to the right of the cell double-clicked upon on 1) Value = _ ‘Target Value is the name of the worksheet on which the values ‘will be placed. Celis(2,1) and Cells(2.2) is where the Date and Dividend value will be placed respectively on this sheet the Invoices sheet, which contains the Dividend value (Offset(0,1) contains the Date) Worksheet names ‘A.worksheet has nwo names, one which can be changed by the user, and one wh ch can only be changed by the programmer. To change the former, of course, we proceed as follows. From Excel, change the name of the worksheet by double-clicking on the name and typing a new name ‘We wish to inspect this new name in the VBE, and to also change the CodeName, From the VBE, view the Properties window of the worksheet (choose View, Properties Window), Ensure the Worksheet is selected (Name), with the parentheses, specifies the CodeName of the Worksheet object, Change it to myCodeName The name of the ‘worksheet which we changed ta Income is represented by the Name property of the Worksheet object “The CodeName has now been changed to myCodeName 6. The Worksheet abject | 93, Project Explorer can also be used to view the Name and the CodeName. Choose View, Project Explorer. The Workbook object By considering the Workbook object as 2 member of the Workbooks collection, ‘we can employ methods and properties which apply to all open workbooks. By ‘considering the Workbook itself as an object, we can utilize events which can be Driers Coons) made to trigger for all the worksheets in a particular workbook. 5 ‘Shits (Cadvel) ThewWerboak The CodeName The Name THWeneee ies ese We are familiar with using the Name property to refer toa Workbook properties 97 worksheet from code — for example to protect a sheet: ee Workbook/s methods 98 Private Sub ConmandButton]_Click(} Worksheets ("Income") Protest End Sub Workbook events 99 ‘Workbook in the Excel Object Model 104 This of course is equivalent to choosing, Tools, Protection, Protect Sheet. from the Excel window. To unprotect the sheet, choose Tools, Protection, Unprotect Sheet..., or use the Unprotect ‘method from code. ‘An automatic alert 106 Chapter Seven The equivalent using CodeName would be: Private Sub ConmandButtent_Click() myCodeName. Protect End Sub ‘When writing code, it is good practise to try to use the Codetiame to refer to.a workshect rather than the Name, The problem with Using the Name is that a user is able to change the name of the sheer, in which case your code will surely fail. Since it is very unlikely that the user will change the CodeNVane, this is a better bet Note that the default name for both the Name and the CodeNane are the same initially, e.g. Sheet1, so that for example, Worksheets ("Sheet") . Protect and Sheet 1. Protect would be equally acceptable! 94 | Excel VBA in easy steps The Workbooks collection Workbook properties Just as individual Worksheet objects constitute a Worksheets Path collection, individual Workbook objects are grouped into a Workbooks collection. The workbooks collection represents all of the currently open workbooks. The Hox book object isthe abstract representation ofa physical workbook, much the same as a FullName Worksheet object isa representation of an actual worksheet. The main purpose of organizing Workbook objects into a Workbooks collection object, isto enable us to deal with all (open) workbooks asa whole and to be able to casily refer to them individually using an index (ustas we saw in the cas of the Worksheets collection), Private Sub\ComandButtont_Click() path describes the location of a workbook (usually on the hard disc), Fullane describes the location and name of a workbook. ‘The frst openediereatad workbook has an index of | ogBox Workbooke (1) lane | Create two new workooks and name (save) them Tax20043ts Pecado fal Mogbox Workbooks ("Tax2004. x18") Path and T2005. respectively. Write the code as shown below in Mocrored,— wagbexe Noxkbooke ("Tax2004. Le") | PHLNARe the Commandl_Clck event of one ofthe worksheet modules of eg nd sub x re ‘The Name of a Workbook can be used as either workbook, which wil iterate through all ofthe open Up Sree ieee aera ‘workbooks (two in this case) and display their respective names ‘When the above code is run, we Private Sub Commandsuttonl_Click() LN aera eee Dim wkb As Workbook For Bach wkb In Workbooks the Workbook Name property. Nore ah ~ Name isa propery ofthe folowed bya message box depayng Bnd sub Workbook object The Poth of the path of the workbook. weak il be Run the above code by clicking the command button on the Lhd sheet. Message boxes will appear with the names of the and is (def) eam ad Staines workbooks, including the one from which the code was run, in Nome wl not hove on the order that they were opened (ar created). og Wicrosott Cxcel [X) JM Microsoft Excot (X followed by a message box displaying the aS. path and name (FullName) ofthe workbook ‘Mierosoft Excel Peart rd strstr Socata 20s The Workbook object | 97 96 | Excel VBA in easy steps The code wl fad Tox2005 9h ot the active 98 | Excel VBA in easy steps Workbook/s methods The Workbook object, ike all other objects, has methods as well as properties and events Close ‘The Close method can be used to close a particular workbook, eg the first opened/created workbook as shown here. Private Sub CommandButtonl_Click() Workbooks (1) .Close End sub Workbooks .Close will close all open workbooks. Try it. Ifthere have been changes, of course a prompt will appear. Open ‘The open method is used here to open a workbook which isin the active directory (the one that we are currently saving to and ‘opening from). Ifthe file is elsewhere, we would need to specify the file's path and name. This code would be written in one workbook in order to open another. Private Sub Commandzuttent_click () Workbooks . open ("7ax2005.x15") End Sub Note that open is a method of the Workbooks object, not the Workbook object. If you view the InteliSense drop-down for the Workbook object, other useful methods (and properties) such as Activate, PrintOut, Save and Saves etc. appear Private Sub ConmandBuctonl_Click() Workbooks ("Tex2004.x12") | End Sub e@ ActveCnan Actvesheet 9 AauTOF=vories 1 Application 1 AutoUpdatoFrequency 1 AuloUpdatesaveCnanges Workbook events Presieg Cut from the VBE wl pen Projet Explorer Useful as they are, Worksheet events (of the previous chapter), only trigger for the specific worksheet (which contains the module jn which the events are written). On the other hand, Workbook events will trigger for any worksheet in the workbook. The Workbook SheetSelectionChange event The Hiorksheet event Worksheet_Select Lonchange was encountered in the previous chapter. I fired whenever we changed a selection on a particular worksheet. On the other hand, the Workbook event Workbook Sheet Select-fonchange will occur ‘whenever we change the selection on any worksheet. ‘We will now write a Workbosk_sheetselect ionchange event ‘which will produce a message box displaying the name of the ‘worksheet that was clicked upon, along with the address of the cell selected | order to get to the Workbook event procedures, fist cpen Project Explorer 2, Double-click on TiswWerkbook ‘The ThisWorkbook code module is “visi from every worksheet in the workbook, ie. is code can be run from any sheet in the ‘workbook 7.The Workbook object | 99 event peocedire ‘oppears ie. Open. simply groe ior delete 100 | Excel VBA in easy steps ‘The special ThisWorkbook code module appears as below. Ps 3 Click the Object drop-down and choose Workbook lick the Procedure drop-down and choose SheetSelectionChange. rosoft Visual Basic Hookt xls - [This Workbook (Code)] 5) Write the code in the Workbook SheetSelectionChange procedure as shown below. Private Sub Workbook ShestSelectionchange _ (Byval Sh As Object, Byval Target As Range) MagBox Sh.Nane & " " g Target Address Bas // \ Sh wil represent We have aso Target is a Range object the worksheet placed a space ‘which represents the cell thatis clicked between the two selected, ie. the “target” strings of our mouse click ‘These variables, Sh and Target are passed to our procedure via the ‘Windows operating system, ‘Moke sure tat the Desi Mode tn on yur | Toabox your event wan tigger Comment out or delete ory other ferent cade 50 rigger a5 wel 6 Return to Excel and clk any clon any sheet.The message box appears as below, dslying both the rare ofthe sheet that was clicked upon as wala the adress of the cl (with pace in between) The Workbook SheetDeactivate event | Fotow the same procecure as before to place code in 4 Werkbook procedure but this time choose the ShectDeactvate event in the Procedure drop-down and write the code shown Private Sub Workbook sheetDeact vate (SyVal _ Sh Ae Object) MsgBox Sh.Name End sub DO irerrete ancther shee’ the workbook (eo Sheet) we caer depayng the vare ofthe shet that was the actve 7 sheet «> WN sheets },Sheet2 { Shest3 / 7.The Weribook object | 101 The Workbook BeforePrint event This workbook event enables us to specify an operation that will be carried out between choosing the Print (or Print Preview) Yow piiter command and the print operation itself tiers mist be i ‘nstaled or Prot For example, we may wish to automatically print a footer at the Frevew took. bottom of cach page. This footer, for example, could consist of the : 0 oso will84 file name and its location (the Workbook's Ful INane), a | Pace the code shown below inthe Werkbook BefoePint procedure Todtervette Private Sub Workbook BefarePrint {cancel Ae Beolean) BD) ce27"" noctvesneet.Pagesetup.RightFooter ¢ Yourself recor @ macro ploce 9 footer ot te bona gh of the page ‘ThisNorkbook.FutName Bnd Sub \ oS. ‘The This Workbook object represents the workbook ‘which contains the code ‘The ActiveSheet object represents the current worksheet (the sheet about to be printed) 2. Fun the code by cicking the Pint Preview burton Itevrowe “(or the Pit bution) from Excel Cy se a. pone ee 3. The Workbook Btorerint triggers so that you shoud se the workbooks locaton and name in the bottom righthand comer of each page for ths particular worksheet. \ A Click Close to s dose the Print > cay C:MyDoesiT a2004.xle window. 102 | Excel VBA in easy steps | sscont’d The Workbook Open event ‘This evene will occur when a workbook opens. ‘ference 2 the Open eve and the Open method. The Open method (of the Werkbooks abject) causes @ workbook o open whereas the Worktok_Open event fies hen the workbook spens [| Wte this code ain the Werkbook. Open procedure Private Sub Workbook open) MeGBox "Don’t ferget the April deadline" End sub 2 Sere the wobec (save the changes) and open tain, The floing message box souk appear afer the workeok op Cac Dee eet the fet eadne The Workbook BeforeClose event Similarly the workbook BeforeClose could b « BeforeClose could be used to respond to the closing ofthe workbook, e.g. this code ws : ill cause a message box to appear after File, enn ‘Close is chosen from the Excel menu, Private Sub Workbeok Beforect MsgBox "Only save the Jan sa. Bnd sub ‘lose (Cancel As Boolean) les figures" nso he gs Command bars that we create by code or otherwise, persist, ie. the raat frorkbook opened wil also display them. To aveld thin ce Could place code in the Workbook Open procedure to erece command bars, and correspondingly place code in the Norkbeok_BeforeClose to remove them. Not as easy ast sounds! 7. The Workbook object | 103 Workbook in the Excel Object Model The representation of the Excel Onect ‘Mode in the VBA Help i version specie 104 | Excel VBA in eaty steps ‘Where in the Excel Object Model hierarchy is the Workbook object located? Microsoft Excel Objects See leo ication > > The Workbook abject is a member of the ea ‘Workbooks collectian which is located directly ee ee ie Application object, which we will discuss later, represents Excel itself As previously mentioned, the Excel Object Model is useful when ‘we want to know which objects to place on the left (the parent objects) of our dot operators. Fortunately these parent objects are not always compulsory. For example, recall how we made the font of a cell bold. Range (*A1") .Font.Bold = True If we were for example, currently working in Sheet! of the workbook Tax2005.xls, then we could, if we wished to be more specific, specify (redundantly in this case) the worksheet and workbook explicitly as shown below: Workbooks ("Tsx2005 1s") Worksheets ("sheet1*) Range("Al") .Font.Bold = True ‘As we ean see ftom the Excel Object Model, the Application object isthe parentof the Workbook object so that we could also {redundandy) include it as the parent of the Workbook object ifso desired, as shown here, application Werkbooks (*7a%2005.x16") _ “WorkSheets ("Sheet") .Range ("Al") Font Bold = True Im the case we just aw, the specification of the parent object is ‘optional, but specification of the parent objects may sometimes be essential. For example, we may wish to place text on a worksheet different from our active worksheet, or indeed in a workbook different from the current workbook as shown by the code below. ‘The alternative workbook (Tax2004.xls in this case) would need to be open - recall that the Workbooks collection consists only of open workbooks. Ifit were not open, we couild use the Workbocks..cpen method to open it, {Tox2004a6 Stipe Pork (*rayan04 le") worksheet sheet 2"). vomedstee? Range(¥A1") Value = "income enor would our Parent Property ‘We could use the TypeName fimction to determine the Parent of the Worksheet as shown here. Private Sub ComandButton!_¢lick() MsgBox ‘TypeName {Act ivesheet. Parent) Bnd Sub a = TypeName Parent retums the eeetMEg) | determines Parent object of the S| the type of (Worksheet) abject the abject Workbook is the parent of Worksheet Farthermore, we could determine that Application is the parent of the parent ofthe Wo=ksheet: object, by using MegBox Typetiame (Activesheet . Parent. parent) 7. The Werktock object | 105 An automatic alert 106 Excel VBA We have wo sales teams, Team and Team2. Their respective sales figures ate kept on two worksheets named Team and Team? respectively. The total ofthe sales figures (summed using a SUM formula) appears in the cell B6 on each sheet. Ifthe sum ofthe sales of either team (ic. on either sheet) excceds 20,000, we wish to be alerted as shown below. We need an event which will trigger when either sheet is, recalculated ~ the Workbook SheetCalculate event, Bill AOE al AZ G2 IS 3 oe 11000 E a > if Team) Teame /Shesti Shae] «| Ready We need to check whether the value of cell BG on the particular sheet which recalculated exceeded 20,000. This is achieved by testing the value of Sh. Range ("26") . Value where Sh will represent the particular worksheet on which the recalculation occurred. When a recalculation does occur (ie a value upon which a formula depends is changed), this code should cause an alert to appear when the value in cell B6 of either sheet exceeds 20,000. Private Sub Workbeck sheetCalculate (Byval _ Eh As Object) TE Sh.Range("B6") value > 20000 Then MsgBox "Sales target achieved by " & Sh.Name End If oe Sh represents the sheet (and the name of the tear) which caused the recalculation The Range object ‘We have already briefly met the Range object. Since the Range object can be Used to represent a region on the spreadsheet it is probably i feet its probably the most important NBA object of also inthis chapter we will hve more to say about how you con ‘se Is properties and methods to gain direct control of Excels functionally. Columns 108 Rows 109. Practical examples 110 Value 112 Copy and Paste methods 113 CurrentRegion 114 UsedRange 116 Offset 117 Resize 119 ‘A dynamic selection 129 Intersect 122 Union 123 To testa selection 124 The Areas collection 125 Chapter Eight Columns 108 | Excel VBA in easy steps We previously saw how the Columns property, when applied to the Worksheet object, was used to select a whole spreadsheet column. When applied to a Range object however, the Columns property will return a column of that particular range, e.g Private Sub CommandButtont_click() Range (*B2:D¢") .Colums (2) .elect. End Sub will select the second column of the specified range as shown here. ‘The second column of the range BI:B3 (the range BI:83 has been formatted here for ilustration) is selected ea ‘The following code will format the cells (make them blue and bold) of the first column of a table. aoe DEE Colorindex for blue Private Sub Commandeutton1_Click() Range ("B2:D4") . Columns (1) . Pont .ColerIndex Range ("B2:D4") .Columns (1) .Font .Rald = True Bnd Sub = s 2s aera |e] Pr [2 fanuary | 2838 305 a lFebruary | 25,345 34.480] 4 [March 36,700 28,340] Similarly, the Rove property can be used to return the row of a specified range, eg. Private Sub CommandButtont_ Click () Range ("B2:D4") .Rows (2) Select end sub ‘The second row of the range BI:B3 is selected A EEE i] ; a i =| [8] We could, for example, place formulas into the bottom row of a table as shown below to add the values directly above and ‘embolden the result. Private Sub ComandButtont_click() ith Range ("B2:D4") .Rows (3) -Formala = "=Sum(B2:B3)" Font Bold = True Bnd With End Sub Note the use ofwith .. Bnd with which simply saves the retyping of Range ("B2:D4") .Rows(3).. With... nd With is of course ‘more usefl wit larger programs. Tage =SuMEr BS, cies pa eSaE ITS! Use) 34,550] ‘The formula to sum each column has been copied across to each cell in row 3 of the table 8. The Range abject | 109 Practical examples N10 | Excel VBA in exsy steps Example | ‘We wish to find the maximum value in a list of numbers First place some numbers in the range BIBS whose maximum we wish ta find 7S to) ETO oO PTS 4 vy 3 5 commanBaton # a [3 6 5 5B One way of finding the maximum is as follows. First set a temporary maximum variable (ro) to the value ofthe fist cell, and thon iterate through the remainder. Ifa number larger than mis encountered, ascribe that value to ms, thus replacing roe with the “maximum so far”. Move down the list, repeating the process Private Sub ConmandButtont_Click() Dim rng As Range, i As Integer, mx As Variant Set rng = Range("B1:86") x = rng.Cel1s(1) .Value ————— xis set to the For i = 2 To rng.Count value in the Tf yng.Cells (i) Value > mx Then very first cell x = rng.Celis(i).Value —e End If er Ifa bigger number MsgBox "Max value is " & 1 is encountered, End Sub then mx is replaced with this A After the loop has been completed, the value of mis displayed new value Mining te amber of fie program code Improves program rmaintarabiy ond “Forward compart’ The Colatndex for Bue wil be 5 con forthe eft polete if Ue palette hos nt ben changed wig the Calrs propery. ‘This use of a Range variable (ens in this case), allows us to easily specify another range if desired, i.e. we can easily change the line Set mg = Range ("B1:B6") to specify a new range, ©. set rng = Renge("A1:A6") which contains aset of numbers whose maximum we now wish to find, Conveniently, ng.Count in the program code would ‘automatically adjust to represent the number of cells in this new: range. Similarly, if we wished to select a range manually before running the code we could use: set rng = Selection Example 2 In this second example, using the same column of numbers as in the previous example, we wish to change the font color of cells to blue if they have a value of 50 or more. Private Sub CommandButtont_Click() Dim eng As Range, ol As RAGE — a ial set rng = Range ("B1:B6") For Each cl In rng TE cl.Value >= 50 Then cell (l) is also Range object End If — If the value in the cell is an cas = 50, then make it blue [Serer RO SIU So Cs [ee | a] a 2) 0 a \4a| Ei [6 | cy t z 8. The Range object | 111 112 | Excel VBA in easy steps We have previously used the Value property for single values, A lize surprisingly, the Value property can also conveniently be Used to accommodate multiple values. Copying a set of values to a new location using the Range object with the Value property is simplicity itselé, ae VC a ee aT [S| 1 2 3 4 CommandButtont ‘To transfer the values shown above to the range D4:E5, we would use: GeeEEBE Private Sub Conmandauttonl_Click/() Range ("D4:E5") .Value = Range ("A2;B3") .Value Bnd sub Ea] 1 2 4 {[Commandéutant | ejofalehe|= Whereas vatue isa default property of the Range object, it cannot be omicted in this case ~ at least not on the right hand side (lest we attempt to put one Range object equal to the other). ‘We can also (redundantly) include the Cet Ls property which simply returns all of che cells (themaselves Raunye objects) ofthe Range object, as shown below to produce exactly the same rest. ange ("D4 Range ("A2 5") Celle.Value = _ 3") Cells. Value Copy and Paste methods Ie is of interest to record a macro to perform the same copy operation, but using the Excel Copy and Paste commands, The result of recording a macro to copy the values can be seen below. Note the VBA Copy and Paste methods which result ‘We could incorporate these methods in our own code (along with cut. if necessary) to transfer values, but the technique utilizing Range value which we saw previously is much more cfficient and stra ghtforward. oft Visual Basic - Rook xls - (Mod ‘sup maerot ange ("42:23 Selection-copy, Range ("DA") Select devivesbect Paste 8.The Range object | 113 CurrentRegion According to the VBA Help, “The current region is a range bounded by any combination of blank rows and blank columns”, Private Sub CommandButtont_Click(} Dim rng Ae Range, cl As Range i ice. the rectangular region around a group of cells. [a] (be get rng = Range ("BI") .CurrentRegion : ‘square brackets For gach cl In rng.Cells ~~~. ‘When using Excel we can select the current region by men eect!) Xf Tettnecic(el-Value) Thea Any cl inthe range | eo ee come ch tots cotorinder = BIB? coalbe ee chosen as the “seed” Al, and pressing the Cir'+Shift+* key combination Range ("Bi"). oF Cee End Sub blue fit is numeric bolertcha Note that instead of rng.Cel1, we might equally just have rng, ‘The advantage of using CurrentRegion is that the user could make additions to the data, contiguous with the current data and | zo alteration to the code would be necessary before running it. All ‘numeric values will be turned blue as shown below. ‘The same effect a above could be achieved fom VBA using: Yosrgoveron [“] A-|_B | © | | Range ("Bi") .CurrentRegion. Select Pim) of Exce! fom + ‘on make currentRegion is usefil when we don't know in advance, the fe het ewe . ea xt coact boundaries of the range that our code will be asked to deal (doo ree) FE | with fara 7d frais red of (ool, Options. Edt) to ‘vcd spurious farmozing effets hts case For example, say that we wane to write a program that will change the fone color ofa range of lls which contain numbers (a ditact from text), blue as shown below. 3EEREPEERE o — Data can be added before clicking the button | Commandatont [ — whereupon these numbers should turn biue as well If, rather than color the numeric values blue, we wished to color the non-numeric values blue, we could use: 4€ Not TeMuneric (cl.Value) ‘Then ee ePP PS Lf-we wished to manually selecta cell in our column of numbers cel VBA in easy steps ‘The following code, which utilizes CurrentRegion, should do just that, The ZsNune=ic function tests whether a cell's contents is numeric, eg. Tstvumeric (23.34) would return True since 23.34 is numeric, whereas tsNumeric ("Diva") would return False, before ranning the code, rather than specifying a “seed” cell in code, we could replace the corresponding line above wit Set ung ~ Selection.CurrentRegion 8. The Range object | NS UsedRange sedan ot oboe elie VBAIn en 5 eps UsedRange is a property which returns the range of used cells on a sheet. More specifically, it returns a range bounded by the rectangle whose comers are the most extreme cells. In the example below, these comers are the top-left and bottom-right cells. Private Sub CommandButtont_Click() ActiveSheet .UsedRange Select Bnd Sub The top-left cell forms the top-left comer of the UsedRange rectangle Canaan | ‘The bottom-right call forms the bottom- right comer of the UsedRange rectangle Useakange is a property of the Worksheet object and not of the Range object, but it returns a Range object. UsedRange has shortcomings and should be used with care. For example, if cell is formatted as bold, and then made unbold, as distinct from clearing the formatting using Fait, Clear, Formats (and any content removed), itis unfortunately still considered as a used cell, and UsedRange would include it in its rectangular boundary. ‘The Bnd property of the Range abject can be used to ascertain the boundaries of a range, e.. Range ("C2") . Bnd (x1Down) Select ‘would select cell C4 in the example data above, ie. the cel at the bottom of the region containing C2 (the equivalent of mantilly selecting cell C2 and pressing the End key along with the down arrow key). See Help on the End property for more details. ‘The offset preperty will return a Range which has the same size, ‘but which is offiet by a number of rows and columns, ¢ offset (4,1) will return a new Range object with the same dimensions, but offset four rows down and one column across: Private Sub ConmandButtonl_ Click () Range ("B2:D4*) offset (4,1) Select End sub The range offset by 4 rows and | column. from the original range is selected eI] ‘This new range at present has no “permanence”. Accordingly, we could seta varicble equal to the new Range object as follows: Dim rag As Range Set rng = Range("B2:D4") .offset (4,1) Specifying only one index will cause the range to be offset by that number of rows, ¢g- set rng = Range ("B2:D4") .offset (4) will return a Range moved down four rows. ‘To offset by a number of columns only, we can either use zero as the first parameter, or omit it altogether, ¢ g these two lines of code are equivalent and either will return a range offset by one column, Set rng = Range(*B2:D4") offset (0,1) Set rg = Range("B2:D4") offset (,1) The Range object | 117 -scont’d Using offset, we could for example, emulate/extend the behavior of the Excel VLOOKUP worksheet fimetion. With reference to the table of numbers below, we could display the Amount corresponding to “dfg” using the code shown, [oe omar is er eS [a a] i 2 ‘Amount Code 3 232 asd 4 31.32 des CommandButtont o 343 ig : ARerg 7 Private Sub Commandbutton}_Click() Dim rng As Range, code As Variant Dim 4 As Integer code = "deg" Set rng = Range (WC3:c6") For i = 2 To rng.Count If mg.Cells (i) .Value = code Then MsgBox rng.Cel1s (i) offset (0,-1) .Value Bnd Tf a Next i The value which is one cell End sub to the left of the cell containing “cfg” is displayed ‘When the code above is run, a message box displaying the amount corresponding to “df” should appear. 118 | Excel VA in easy steps Resize ‘The Resize property will physically change the size of a range toa specified number of rows and columns. The top left cell of the new range remains fixed in place; itis the “anchor point” about which the range is contracted or expanded. Private Sub CommandButtonl_Click () Range ("B2:Dé") .Resize(2,2) Select. pnd sub “The original range (here formatted with a border), is contracted to 2 rows and 2 colurnns in total size. ‘The top left cell remains as the “anchor point ns Daa ed 4 5 Specifying only ane index will canse the range to be resized t0 that specified number of rows, ¢.g. Resize (1) will return a range of ‘one row only. We could set a variable to such a new Range object {and select it) as shown: Private sub CommandButton1_click() Dim rng As Range set mg = Range("B2:D4") Resize (1) mg.select, znd sub Te] a Ss i “To resize to one column for example, we could simply omit any row specification and use Resize (, 1) 8, The Range object | 119, A dynamic selection 120 | Excel VBA in easy steps We wish to be able to click among any rectangul: any rectangular group of cells and then click a command button on the sheet. i 7-13 Cea eer] 2 | fal sof aa 2a ¢ 34873234532 23433445 45.32 5 ee) 5632343 23.21 M67 3423 45.32 ce 34.45 0532 Once again we will write and test our code in easy steps. | Pece a command button onthe sheet and write some code in ts procedire which wl simpy select the CurrentRegion aroun the cel hat he user clicks upon Private Sub Conmandbuttont_ Click ) he el 9 Sao set ing = Selection. CurrentRegion mg. Select End sub (5 AN seeing cell containing data and running a Bas aay 34g? 3423. agaa|__the code, the 23433445 45 current region is selected roam Selec acelin the table before cdeking the ‘emand button toninthe 2, include code in the command button procedure to increase ‘the number of raws in the range by one (and select it) Private sub CommandButton_Click() Dim rng As Range set rng = Selection.CurrentRegion Set rng_s mg.Reeize(zng.Rows.count + 1) S ids rmaflowsCaun wil be 3 redefined when execution reaches this line (and 4 immediately ater) 3 Change the ine ofcode to sect the ast row ofthis new range Private sub CormandButtonl_Click() Dim rng As Range Set rng = Selection.CurrentRegion Set rng = rig.Resize(rng.Rows.Count + 1) ng-Rows (rng.Rews.Count) .Select End Sub mows: Count will be 4 after resizing hens inthe bli seleced em me 7g) te command Be BE BE button ceten te Bs 445. A532, _- last row will be Fy eT EE aaa a selected ‘This code should work for any sized table, anywhere on the sheet. 8. The Range object | 121 Intersect 122 | Excel VBA in easy steps ‘The intersection of two ranges is the region where they meet. Borders have been placed around the ranges ‘whose intersection we wish to find gi D E F CommandButtont This code will color the intersection of the two ranges. Private Sub Conmanasuttonl_Click () Intersect (Range ("B2:D4") ,Range ("D3:P5")) _ VInterior.Colorindex = 33 End sub Interior is used when we wish to apply a solid color to the cel interior. Colorindex 33 is Sky Ble in the defautt palette ‘When the program is run, the range intersection is colored blue ee A EE mi ees [sess fee eae Commeanduttont Union ‘The union of ewo ranges is the “amalgamation” of the two ranges. Modify the previous code to that shown below (replace Intersect with Union) private Sub ConmandButtont_Click() Union (Range ("B2:D4") Range (*D3:F5")) __ Interior.ColorIndex = 33 End sub ‘When the command button is clicked, the union is colored blue Ey SPRY PC = al CL ate 2 ey 4 5 6 a ‘Com 6 cs intersact and Union are methods which return Range objects, so ‘we could assign Range variables as shown, Dim mgi As Range, rng2 As Range Set mgl = Intersect (Range ("B2:D4") ,Range("D3:F5")) Set_mg2 = Union (Range ("B2:D4") ,Range("D3:F5")) 8. The Range object | 12 To test a selection 124 | Excel ve exsy steps The objective here is to ensure that a user will click in a certain range. IF the user does not, a message box will appear, requestin, that the correct range be sclected Private Sub Worksheet_SelectionChange (ByVal _ ‘Target As Range) Dim rng As Range Set rng = Range("B2:D4") If Intersect (eng, Target) Is Nothing Then NegBox "Please select a cell/in the range * ¢_ mg. Address Elae IFthere is no intersection, Meseoe NOR the range will be Nothir End If . ane Bnd Sub the user clicks on a cell which is not in the required range, a reminder appears Microsoft Excel Please selec acelin the range $842:40$4 (aecelaal ‘To ensure that the user selects only a single cell, we could include this code just before the ise statement. ElseIf Target .cells.count <> 1 Then MsgBox "Please select a single cali" Elsel£ provides another alternative to the ise, ie. ifthe user does either thing wrong, the Tf or the Elser will be chosen, whereas if the user makes a correct selection, £1 se will be chosen, The Areas collection According to the VBA Help, “Areas is a collection of the areas, or contiguous blocks of cells, within a selection. There is no single ‘Arca object; individual members of the Areas collection are Range objects” ‘On an Excel spreadsheet, when we make one selection and then hold down the Ctrl key to make another, we are creating two areas oe 4 5} vote caefuly he The equivalent of this in code would be: tof the Range ("B2:B3, 02:83") .Select ‘The two members of this Areas collection have index values of 1 and 2 reszectively, i. Areas (1) and Areas (2). Correspondingly, the Coun: property of the Areas collection returns the number of these discrete Range objects in the collection — in this case 2. For example, the following code will cause the respective addresses of the two areas to be displayed. Private Sub Commandeuttonl_Click() Dim rng As Range, i As Integer Set mpg = Range("B2:B3,D2:83") mgAreas Count is 2 For i = 1 To rng.Areas.Count MsgBox rng.Areas(i) Address Next i End Sub ‘When the code is run, the address of each area is displayed Wicrosoft Excel [X] Wicrosoft Excol [ ‘essere kes 8. The Range object | 125 126 Excel VBA in easy eps ‘As a practical example, we wish to ensure that a user makes a selection of exactly wo single cells (nsing the Ctrl key) A oc o a a ‘SalePerson Sales 2 ay] Dale cz [4 McKenna 4540 The Selection object represents the Ifa selection of more or less user’s choice of one or more areas _than two cells is made Private sub/CommandButtoni_Click() If Selection.Areas.Count <> 2 Then MegBox "You mist make exactly 2 selections" ElseIf Selection.Areas(1) .Cells.Count <> 1 Or Selection.Areas(2).Cells.Count <> 1 Then MsgBox "You must select single cells" EL Maghex "OK" IF either range has more than For example, if more than one cell is selected in one of the areas and the command button then clicked, ac ee | i SalePerson Sales 2 3 Dale 2387 a MoKenna 2 i] You asset ral cele ca a warning appears: To farther ensure that the selections were from the correct column and the same row, we could check the CoLunn and Row properties respectively, eg, Selection Areas(1) .column and Selection.Areas(1) .Row ActiveX controls This chapter describes controls such as text boxes, combo boxes and option buttons which can be placed on the worksheet to improve functionality. Command button 128 Changing a property at design-time 129 Textbox 133 Spin button 135 Check box 137 Option buttons 138 Combo box 139 Using option butcons 141 Command button 128 | Excel VBA in easy steps Controls found on the Control Toolbox (shown below) are ActiveX controls. We have already met one ActiveX control - the CommandButton object. if you hold your mouse cursor steady over the buttons on the Control Toolbox, the types of ActiveX controls will be revealed (You may wish to draw a few of these on your sheet) check ax We have met the c1ick event of the CommandButton control. ‘These controls are objects, and accordingly, besides events, have properties and methods, For example, we can change the Caption property of a CommandButton object using this code: Private Sub ConmandButtonl_Click() CommandButtonl Caption = "Enabled" End sub - Abr EApe amon naa Commmandéuttont | When we click on the command button, ] the caption changes Changing a property at design-time k woy of geting the the Excel widow i 0 mode) and Moke sx ‘mode in order to he the Properties Wi sop down, So far we have seen how to change a property while the program ‘was running — at run-time. It is also possible to change properties before we run the program ~ at design-time - as shown below. Ieis particularly desitable to change the captions of command buttons if ‘we have more than one, in order to distinguish their function, e.g [Eas c D , aa HS 2 i 2) popy Fomatting | Remove Forttina | [4 [e | Place twe command buttons on a sheet and access the Properties Window from the VBE by clicking on the Properties Window button (or choosing View, Properties Window from the VBE menu). 2. Choose Command.ston! from the drop-down ‘Your Properties Window may or aA (Change the Caption property anes to Apply Formatting as shown, 4, Repeat (from Step 2) for the second ‘CommandButton’s Ception property. Change it to Remove Formatting. 9, AativeX controls | 129 cont'd 130 | Excel VBA in easy steps -scont’d The Caption property is simply the text which appears on the button, The Wane property on the other hand, is how the ConmandBut:ton object is programmatically identified. In the previous example shown here again, the Name property of the CommandButton object was ConmandBut ton. Private Sub ConmandButtont_Click() ConmandButtonl Caption = "Enabled ma sub \ ‘CommandButton! is the Name of the ComandButton control ‘We will now change the Name property of our two command Duwons at dsign-ime, The Properties Window should sil be | From the Properties Window, change the Name properties ofthe corresponding command buttons to cemdApplFormat and cmdRemoveFormat respectively percolay ae ee poe Fale CD exeooo000r. T-FnBackstyleop ‘op Frmating| Tue sail | Mi creo.000120, | 345 a 2. From the Exel window, double lick on the fist command button (ensuring that you are stil in design mode), Repeat for the second command button. The respective code procedures will appear in the \VBE es shown. Itis also possible to create the respective Click procedures by simply selecting them in the object drop-down Bnd Sub ae Private Sub cmdRenoveFormat_Click(] End Sub Giving the respective ConnandBut-ton objects appropriate Nanes of course enables us to more easily identify the respective procedures. ‘This becomes more useful as programs become larger. We can now place appropriate code in the two procedures as shown. Private Sub omdapplyFormat_Click() Selection.font ColorIndex = 3 Bnd Sub Dy | rset code into the is procedure which will set the font color of selected cells red, private oub catenoverornat_click() selection Cleartormate = N rer code into the second procedire ich il clear te fonnating ofthe selected cells. 9. ActiveX controls | 131 cont'd Exit design mode. To demonstrate the program's versa will apply formatting to a multiple selection rather than just a single selection. First place some numbers on the sheet which we wish to selectively format as shown below. Make a multiple selection (using the Ctrl key) and then click the Apply Formatting button. Remove Formatting 5 Apply Formatting | 4 In this example, the Ist, 3rd and 4th cells will be formatted (made red) 4, To clear the formatting, make the same selection and then click the Remove Formatting button Alll of the cells’ font color should now return to the default, 132 | Excel VBA in easy steps Text box ‘We will now place a text box control onto a sheet, and use it to display some text when a command button is clicked. First place a ‘command button on the sheet and then. / | cick: text box conto button on the Control Toolbox 2. Drawa tex box on the set ae [Sab ee | \eosn am pe ees CommandButtont | °° 3 Right-click onthe text boxcon the sheet and choose Properties. In the Properties box, change the Name property to batSales, As an expedience, you may wish to now copy (Ctr+C) this Name and later paste it into your code (see over) to reduce the prospect of a typo. 9, Activex contrals | 133 -cont' In order to see te properties of 1 parator carivok make conor is selected on ropes snot Fer one thing your cade ess readable, but could a lead to combi ng defoult 134 | Excel VBA in easy steps 4, Wite this code inthe CommandButton procedure Private Sub ConmandButtonl_Click() txtSales.Text = "Sales Results are good" nd sub extales is now the Nane by which the text box can be referred to in the program ~at least in this particular code module. Text is a property of the text box control. You can see it listed in the Properties box for this text box. It is the default property of the ‘TextBox object and could therefore be omitted 5 After exiting design mode, click the commanc button, The text should appear in the text box ‘We have thus seen how to give a control (the TextBox control) a name by which we can later refer to it. It would have been perfectly (OK to leave the name as the default (TextBox! in our case), and use that name to subsequently refer to our TextBox control, If, instead of transferring data to our text box, we wished to ‘transfer input data from our text box into a spreadsheet cell, we could for example use: Cells(1,1).Value = txtsales.Text. To test this code we need to exit design mode and make sure that there is some text in the text box first. ‘Text boxes are more usefull when they are placed on a user form, which we will discuss later. Spin button ‘We will plsce a spin button control on the sheet which will be used to increment and decrement an invoice number in a spreadsheet cell (B2) by utilizing the spinup and spinDown events of the spin button, Use the Control Toolbox to draw a spin button control on the sheet 2. Double-cck on the spin button control The (default) SpinButton |_Change() event procedure wil I be created. This is he event which responds to the “up” or the “down” arrows being clicked, We want to be more specific, Delete (or ignore) this event procedure. 3. Make sure that SpinButtonl is chosen in the Object drop-down. Choose the SpinUp and SpinDown events from the Procedure drop-down (you may né the SpinBiutton|_Change() event again) and jeed to delete write the code in the respective procedures as shown, [Spinouttont a = = =z [ option Expitcie Private Sub SpinButeoal_Spinip() Ceilsi2, 2).Value = Cells (2, 2) Va End Sub f vrxvate Sub Spinduttoni_Spiadom) Cellsi2, 2) Value = celle(2, 2) Va End Sub tue +2 ue - 1 9. ActiveX controls | 135 re Before zing ths ake sue thot, You delete! comme the Spreuun!_Spep cond SPinBUtan! SpinDoun rent code ud simply be pice @conmand baton procedure More practical, yatzcton code coud be ced the Worse Aciate fo WoRDOK_ Open procedire xc Ifthe Workdonk event is Sposens make sure ther 20 ale by the Works woksees Spinduron et 136 | Xe! VBA in easy steps A. From Excel, make sure that the Design Mode button is not depressed and clck on the “up” and ‘down’ arrows of the spin button. The value in cell B2 should be incremented and decremented. We could achieve the same effect by utilizing the spin button’s built-in value property, which is automatically incremented and. decremented upon clicking the spin button's “up” and “down” arrows respectively. Using this method we can utilize the Nin and Max properties ~ the minimum and maximum values that Value can take — which can be set at design-time ~ or at run-time using code such as: SpinButton1.Max = 200 SpinButtoni.Min = 100 and similarly, the incremental value can be altered from the default of I by changing the sna11 change property (at design-time or run-time eg, SpinButton1.SmallChange = 5). The value could then be displayed in the cell using: Private Sub SpinButtonl_change() Cells(2,2).Value = SpinButtont. value End sub In this case, the value displayed in the cell could only change from 100 to 200, in increments determined by the value of Snal1.Change. Check box | Prace two check boxes on a sheet. Double-click on one, and from the VBE choose the Change event procedure from the Procedure drop-down, You may wish to delete the default Click event procedures as they appear. Choose the other check box object from Object drop-dawn, choose its Change event and write the respective code in each as shown below. Private Sub CheckBoxl_change () Range ("D3") Value = CheckBox1.Value End sub Private Sub CheckBox2_Change () Range ("D6") Value = Checkbox2. Value End sub D. From Excel, exit design mode and clck the respective check boxes. The corresponding Value properties will appear in column D ~ True comesponding to checked, and False corresponding to unchecked, Note that the check boxes (compared to optian buttons which we will ‘meet soon) act independently, i, checking/unchecking ne has no effect on the state of the other, CheckBoxt TRUE 1 CheckBox2 TRUE. 9. ActiveX controle | 137 Option buttons Soe we have nat yet assigned button t oppear selected by deft ets Value has not been se to Trae you wll need ta marualy select ‘one ofthe option burton fst when the pregrom fst nn You moy wish delete the defaut event (Clek) procedures if they ‘pear 138 | Excel VBA in eaty steps ‘These are almost identical to check boxes, but there is one major difference. When we change one, the other changes automatically. | Place two option buttons on a sheet — without any code. Exit design mode and choose one by clicking it. Click on the other bution and the former button changes state automaticaly c D Em] [2] ra OptionButtont a 5 Le © OptionButton2 > 2. Revert to design mode and double-click on one ‘option button. Choose the Change event for each cone and write the respective code as shown, Private Sub OptionButton1_Change() Range ("D3") .Value = OptionButtont. Value End Sub Private Sub OptionButton2_Change() Range ("D6") .Value = OptionButton2. Value End Sub 3. Exit design mode and select one of the options. Both values in column D change, since (unlike a check box) changing cone option button will cause the other to change — thereby causing the Change event to trigger in the other as well Combo box (Our simple combo will provide a choice of three items in its drop- down. The combo will be populated with items provided from a list in Column D on the sheet. When an item is chosen from the combo drop-down, it will be made to appear in BS. | Usrgtne Control Toobox, daw a combo box on 3 sheet nd place thee ites in colar D as shown, So meee eS) ee ee] ra Stock at ay Expenses [3 ° Dividends 4 5] 2. Right-ick on the combo > The result of our box (still in design mode) combo choice is to and choose Properties. appear in BS 3 In the Properties box, set the ListFilRange to D1:D3 which is the range that will be used to provide the combo box's altemative choices. Set the LinkedCell property to BS which isthe cell we have chosen to display the choice made, fara ee 4, From the Excel spreadsheet exit desigr mode, click on the combo drop-down and make a choice. fay ira Expenses 3) Didends 4 5 [e) 9. ActiveX controls | 139 --cont’d 5 The choice that we made from the combo drop- Make sure down should appear in cell BS as required. reece cel TR oe a igh sass Stock 2 Expenses 3 Didends a Ls Expenses 6 More advanced combo box features geo & Werwish to make a choice from two columns. Pace the extra an ear Import / ay i 2] © 204 ImportSheet 4 5 iam iit 1H | lace conmand button onthe Inport sheet. Change its Caption to InpotSheet and ite Name to emdmporiSheet 2. Pace two option butons on tis sre sheet. Change thei ‘Captions to 2004 and 2005 respectively. Leave the Names as the default, OptionButton! and OptionButton2. 9, ActiveX controls | M4 Double-click on the command button and write this code Private Sub omitaportshest_click() ~ Tf OptionButtonl.Value = True Then ae shName = OptionButton1.Caption shName sire = opt lonutton. caption oan he es le Noskbooka (Company. xcs") -Morkaheet (shake) copy _ Wsercoot After:= ThisWorkbook. orksheets (Worksheets. Count) z ee Acolon and equal Company-xls is the Copy isa ce eve hppes Senidenes workbook from which method of the ee fer asaramed the shest willbe copied Worksheet parame object (discussed later) Make sure that.both workbooks are open, After selecting a year and clicking the ImporiSheet button. xyou should find that the selected sheet has been copied from Company.x!s to this workbook. 142 | Excel VBA in easy steps Procedures Procedures allow us to compartmentaize and organize our code. We discuss the ‘two main types, subs and functions along with their practical use. Subs 144 Functions 146 Passing ByRef and ByVal 147 Usingasub 148 Using a function 149 Variable scope 150 To color the minimum value 152 Variable lifetime 153 The MsgBox function 154 Named parameters 155 User defined functions 156 Chapter Ten Subs 144 | Excel VBA in sy steps ..cont’d Procedures are self-contained blocks of code. Procedures become ‘more useful as program size increases. They are of two main types subs and functions, As we will see, the difference between a sub and a function is that a function can retum a value whereas a sub cannot. wi ing a sub Write this code. option Explicit Private Sub CommandButton1_Click() ee Use Debug to ae singe step (F8) to nd sub ‘Square is the name of our sub Reach the’ sneer of program Sub Square () ofp au nie AS we type “sub Square” and then aoa Dim x As Double xe3 press Enter, as well as being capitalized, xox*2 parentheses and End Sub (formatted og bh wutomatical NegPox *___— blue) appear automaticaly ‘The Square statement in the CommandBut-ton procedure has the effect of “calling” the sub. The called procedure simply squares 3 to give 9, which is then displayed by the message box. ec) ° Generally speaking, in the course of program development, itis useful to be able to “wrap” code which has been tried and tested into subs (or functions) with identifiable names, and place them, outhide the main calling program. That way, our main code area should consist of a series of procedure calls (with recognizable names) with the corresponding encapsulated procedures placed after the main program area. Passing a value to a sub At present our sub can only square 3. We could modify it so that it could square any number by passing the number to be squared to the sub as follows. option Explicit Private Sub CommandButtonl_Click() Square 3 End stb 3 is passed to x Sub Square (x As Double) x=x*2 S MegBox x x As Double is the equivalent aes of Dim x as Double ‘The variable which accepts the passed value (x in this case), is known as a parameter. Strictly speaking, the 3 which is passed is known as an argument, but both are often referred to as parameters ae cay ‘Change the line Square 3 to Square 4 to show that another value can be passed. The result, of course, in the later case, should be that 16 is displayed. 0, Procedures | 145 Functions A funcion nome appears on the gh hard ide eg y = Square(3) or MsgBox wre 146 | Excel VBA in easy steps Functions differ from subs in that they can return a value. Writing a function Modify the code as shown, Note that afier Function is typed, End Function appears automatically! option Explicit Private Sub ConmandButton}_Click () Dim y As Double y = Square (3) Msghox y _-—— This time the value is End Sub retumed to y and displayed Function Square(x As Double) As Double sekghal x The retum type (also Double) is also specified when square = x End\ Function The name of the function (Square) is always “repeated (usually at the end of the function) and usualy put equal to what ist cing a function. it be retumed (In this case ») See vet retum type is assumed Creole eS) ° Note that we could replace the command button code with: Private Sub ConmandButtonl_Click() MsgBox Square (3) End Sub We can even include our function name in an expression such as MsgBox 2 * Square(3) in which case we could regard the function name as a variable with value 9, so that 18 would be displayed. Try it. Passing ByRef and ByVal Altough ‘seuss in ‘elation Furcvons, ByVal cond ByRef have ‘exact the some effect when sed with subs Possng 0 vorable 2 sub Bye (oy reference), can permanenty change the variable passed whereas passing ByVal (by byes te @| deft Your sone may get changed permanent i they are passed by ByRe Technical speaking. Ret causes the the vanable tobe passed Modify the code as shown to pass a variable rather than a constant. option Explicit Private Sub CommandButtonl_Click() Dim v as Double ve MsgBox 2 * Square(v)_ The variable vis being mnd suis passed to the function Function Square (x As Double) As Double x-x*2 Square = x End Function After Maqzox 2 * Square (v), which causes 18 to be displayed, include the line tisqBox v in order to display the value of v. ‘When the program is run and 8 has been Fics splayed as expected, quite surprisingly, the value of vis displayed as 9, not 3, i. the value of v has been permanently changed (squared) by the function to 9. Reverse remote control Include ByRe? in the corresponding line above so that it becomes: Function Square (ByRef x Rs Double) As Double Ie won't make any difference, ayre® is the default Now change the ByRef to yVal so that it becomes: Function Square (ByVal x As Double) As Double ByVal ensures that the value is passed by value and not modified inside the procedure, Ths time, when the code is run (and after the 18 has been displayed), the value of vis displayed as 3 and shown to bbe unchanged after the function call 10. Procedures | 147 Using a sub 148 | Excel VBA in easy steps ‘Asan example, we wish to color any 2's which appear in a set of | numbers red, We will pass the 2, along with the range to be searched to a sub which we will call Colorcel is. ‘We will search the range AI:A6 and color any 2's found red Commas are used to separate arguments Two arguments are Private sul)\Commandbuttona_chick() passed. The range Gelereaian 3 aes iain) sae >: Raton End Sub Sub ColorCells(x As Variant, rng As Range) Dim cl as Range For Bach cl In rng TE cl.Value = x Then clFont ColorIndex = 3 Next cl End sub Note that che 2 has been passed asa Variant. This would allow us to search for text as well as a number if we wished. ‘The advantage of using a procedure here is that we can easily change the number that we are searching for, as well as the range that we are searching. Whereas we have searched a column of numbers, itis possible to search any range, and also carry out more than one search, so that we would use the same procedure and modify our calling, coxle soasctsnys like this Private Sub CommandButtonl_Click() Colorcells 2, Range (¥A1:A6") Colorcells 4, Range(¥c1:n4") Bnd sub Using a function The spurious space onthe lefthandside Introduced by Sv the lefthond.sde of be avided by using of Se ) can ‘tw organize your just fhe ‘As an example, we wish to find the number of 2's in a certain range. We will pass the 2, along with the range to be searched, to a function which we will call Findtium. As shown below, we use a function rather than a sub, since we wish to return the number of 2's found to the calling procedure. rae] pana Microsoft Excel (%) CommandButtont | | se nunberof2'sfaundis 9 Desccrs] Private Sub ConmandButtoni_Click() Dim mum As Integer, fnd As Variant ae > num is the mum = Finavum(End, Range ("at:agt)) — NM IN MsgBox "The number of " & End & _ "'s found is* & Str (num) occurrences End stb of fd eunction FindMu(x As Variant, rg Ae Range) _ Rees pin c As integer, ch As Range oe counter if a 2 found Fer gach el tn mg SA Tf cl.Value = x Then ¢ = o¢ 1 Next el ination = ¢ Bnd Function Increment the a xdNum is the number of occurrences of x which is passed back to num Summary ‘When using functions: * Use the same fianction name to return the value, e.g Findmun = + Use parentheses when passing the arguments, eg, FindNum(fnd, Range ("A1:A6")) [not with a sub]. + Specify the return type, e.g. As Tnteger as above. (0, Procedures | 149 Variable scope hos procedire fev scope 5 steps ‘The scope of a variable determines where in the program it is valid. variable is only “known” at the “level” at which itis declared. This code below will fail with the message shown. Try it, Option Explicit Private Sub CommandButton1_Click() subi aa Cea ed Code is End Sub re on tr ed Sub subi () \aritienet defines Koreas) Dim 4 As Integer before ca eel (oe) End Sub The problem is that iis not known in sub sub2() Sup uP?) the second procedure, since it was End Sub declared in the fist procedure only Include a Dim statement in the second procedure as well, as shown below. It is important to realize that the second i variable is thereby completely.independent of the 4 in the first procedure. option Explicit Private Sub CommandButtonl_Click() subl sub2 End sub Sub subi () Dim i As Integer ree Magbox i End sub Sub aub2() Dim i As Integer daa Msgbox i End Sub | i --cont’d stonderd code Pablc instead of Dim eg Public 1 os integer. Such o vanable woul then be ovalable 1 every mode and ac defre the variable (eg. = 3) na ‘What if we did want the 4 in the first procedure to also be known, and retain its value, in the second procedure? We need to declare it in the General Declarations section (at the top of the module), Remove the Dim statements from each sub and modify the code as shown below. Place the Dim statement in the General Declarations. i will then be known throughout the whole module option Explicit Dim i As Integer Privace Sub ConmandButtonl_Click() subl sub2 End Sub sub subi () ie Maguox 4 End Sub known in the second procedure sub sub2 Poe MagBox 4 End Sub ‘The value of i was defined as | in the first procedure, so this value will also be Wicrosoft Excel [X]] ‘When the program is run, a message box will appear twice displaying | each time It is very strongly recommended that variables are declared as locally as possible, resisting the strong temptation to use the easy option of module-level variables as above, where the variable is declared outside the procedures that use it (in the General Declaratons). One alternative to using module-level or global variables is to pass variables as arguments from one sub to another. The objective of a programmer is not only to write a program that ‘works, but to make contingency for when it doesn’t. Declaring variables as locally as possible is one of these contingencies. Using tion SxpLicit is another. Knowing precisely where variables are declared and defined helps us to localize the source of any potential errors that may occur. 10. Procedures | 151 To color the minimum value Change the Names ond Capon of ‘command buttons aig the Propernes window. (lear Formos 152 | Excel VBA in easy steps This program will color the smallest value in a selected set of numbers blue. Since the range variable is declared at module level (in the General Declarations), it will be available to all command button procedures in that module, and the selection need not be repeated before clicking the second button to clear the formatting, After declaration in the General Option Explicit Dim yng As Range — Private Sub emdFindMin_click() Dim i As Integer, mn As Single Dim ¢ As Integer Range variable is Set mg = Selection ——— defined in the first mm = rng.Cel1s(1) .Value eat For i = 2 To rng.Count If yng.Cells(i) Value < mn Then mm = rng.Cells{i) .Value Declarations, the procedure After the index (© of the cell apaat containing the Bnd If se smallest value has Next i mg.Cells(c).Font.colormndex = 5 Deen determined, End sub itis used to color that particular Private Sub cmdClearFormats_Click() cell blue xng.Cells.ClearFormats End sub ss ‘mg will aso be known in this procedure First select the range, and then click the Find Min button. The minimum value (22 in this case) should be colored blue ia le] Th 2 ; Sees 7 2] / eee) 3] 2 40 62 a Clear Formats 48 a Since mg has module-level scope, there is no need to re-select the range before clicking Clear Formats Variable lifetime Lifetime determines where in the program the value ofa variable is remembered. If we declare a variable in a procedure using static instead of Din, the variable value will be remembered next time the procedure is called. First we'll not use static. Private Sub Conmandsutton}_Click() Dim i As Integer MsgBox i Each time that the command button is isied licked, the same value of i (0) appears End Sub “The effect of Dim is to set the value back 10.0 each time that the button is clicked 7 |2) [34 4 5 5 if fal Now chenge Dim to static, Private Sub ConmandButtonl_Click () Static 4 As Integer feliat MogBox 1 ~ Static ensures thatthe vale i Bnd Sub remembered from the last time that the procedure was called If we now continue to click the Microsoft Excel [X command button, the value displayed will be incremented by one each time If the workbook is closed (saved), and reopened, the value of 4 is forgotter, ie. it resets to 0, 10 Procedures | 153 The MsgBox function We have met the MsaBox statement, e.g. MsgBox "Click". We could regard this as calling the built-in MegBox sub and passing it the parameter "Click". MagBox can also be used asa function, whereby a value is returned, e.g, Wen cling X = MsgBox ("Click",4,"Test") furctons, use ae ‘ eee The Prompt The Title (“Test”) will appear at the crprents. is "Click" top of the message box (see below) ere The Buttons value of 4 determines that two RD vores. buttons, Yes and No will appear on the message fp sbVesNo box (see the VBE Help for more detais) tested of 4 ‘Type in the code as shown below: eion Explicit Private Sub CommandButtont Click) Dim x As Integer X= MogBox "click", 4, "Test _MsgBax(Prompt[autons As VoMsqBoxS¥e ma Sib tance, ‘As we type into the VBE, Auto Quick Info. At Quick provides a guide to the correct syntax (as from the VBE well as listing the vb constants available) exit, choose Took Opons Tile is Test Prompt is Click Buttons is Yes/No The value of x returned is determined by the button pressed. If Yes is clicked, the value returned is 6 (vb¥es). If No is clicked, the value returned is 7 (vbNo). To confirm this, you may wish to use another MegBox statement to display the value of x. = MsgBox ("Click",4,"Test") MagBox x 154 | Excel VBA in easy steps Named parameters +n omit What if we did not want to specify YeYNo buttons but instead ire Buttons accept the default of an OK button? We could omit the Buttons eeeike atgumen: altogether as follows. default we could se @ Batons wale of 0 (sOKOnb), X = MegBox("Click", , "Test") me: ‘An extra comma indicates a missing argument. The defauit OK button only Keeping the arguments in strict order, and providing the required extra commas, can be a litte tedious — especially as the number of | parameters becomes larger. Named parameters obviates this. The sive inci eaivalent ofthe above, using named parameters is: the con with the x = MsgBox (Prompt :="Click", Title:="Test") 0.0 sgn wen usinoms Note that if named parameters are used, the order of the parameters arguments no longer matters, e.g, the following statement would bbe equivalent to the above: x = MsgBox (Title:="Test", Prompt :="Click") In a practical situation, we could test for the returned value, For example, if we wish to confirm that we want to delete the contents of the cels in a selection, we could use: Private Sub CommandButton1_Click() Dim x As Integer X = MsgBox (Prompt. Buttons :=vbYesNo) If x = vbYes Then Select ion.ClearContents End Tf totherwiae do nothing End sub Delete the cell contents?", _ (0. Procedures | 185 User defined functions Ifwe write a function in a standard code module, it can be called from Excel just as we would call a normal worksheet function, From the VBE menu, select Insert, Module. ‘Write this function code in the module to perform a simple currency conversion, mam ‘rst — pim rate as single p End Function rm the the name of our function, along Type an = sign. followed by with the source cell reference. Ifa steding amount is now entered into A2, the equivalent dollar amount will immediately appear in B2 Writing the user defined function (UDF) in a standard code module (as well as being essential) immediately qualifies the function as being available for any sheet in the workbook, Limitations User defined functions are very useful for providing your user with encapsulated code which the user can access by simply typing the function name into the formula bar as we have seen, but they have restrictions. Foremost of these is that UDFs cannot be used to Ret] 95st change the structure of the spreadsheet in any way. This means RE) "2 that not only can we not change the formating of any cells, UDF cannot be used to place a value in a cell. Worse still, we may not get any indication of the error if we try! Using arrays Arrays are useful for holding data. In this chapter we consider the different types of array and how they can be manipulated. We also intraduce other objects which can relate to, and take advantage of their succinctness as well as employ a technique to warn if their capacity is exceeded, [-D arrays 158 2D arrays 160 ReDim 161 Variant arrays 162 The Array function 163 The UserForm 164 Run-time errors 167 Names 170 Chanter Flayven 1-D arrays ‘An array is a set of indexed variables. The variables could be Integers, Variants, etc, but must be of a single type. One- dimensional arrays have only one index which is used to assign and access the individual elements. For example, we could define an array of three Strings as shown below. This Dim declaration reserves space in memory for 3 String elements, indexed from | to 3 option axpiicit / Dim Company(1 to 3) As String Private Sub CommandButtent_Click() Company (1) = "Business systems" Company (2) = "Best Image" Company (3) = "Analytical systems" End Sub Vorables decreed Note that the declaration Dim Company (1 to 3) As string in in the — this case has been placed in the General Declarations area rather Pecovovons F than inside the command button procedure, in anticipation of Hess making the array available to other (command button) procedures in that module, To display the third element of the array for example, (using a second command button) we could use: Private Sub CommandButton2_Click() MsgBox Company (3) End Sub in our example ifthe fst ‘command burton isnot eicked (10 ino the ane) before (ee) ee thie ching the second Aare displayed A major advantage of storing variables in an array is that they can be conveniently processed using a loop. For example, if we wished to attach the same string to each element in the array, using a 3rd command button, we could use: 158 | Excel VBA in easy stepe i i | vara ae zerobosed by eft, Use Opeien Base | in Decorations if you wish your ‘rays ta be one-based, Private Sub ConmandButton3_Click() Dim i As Integer For i= 1103 Company (i) = Company(i) & " Ltd" Nex: i \ 7 End suo Strings are concatenated Similarly, we could conveniently display all of these array elements using a simple loop (modifying the code in button 2) as shown below. Private Sub ConmandButton2_Click() Dim i As Integer For i= 1703 Msgox Company (i) Next 4 End sub ‘After clicking the three command buttons (in the order |, 3 and then 2), the amended names will be displayed pee Z eee ees uses Stone et nao Instead of declaring our array using: Dim Company(1 to 3) As String we could use: pim Conpany(3} As String ‘This will give us an element for free! — clement zero — in this case Company 10). We could assign another company name to, Company 0), but on the other hand, we may wish to ignore clement zero altogether, in order to be consistent with the indexing of Excel spreadsheet cells (which of course do not have zero rows or columns). To officially signal the absence of element zero, we may wish to specify option Base 1 in the General Declarations, in which :ase all arrays (at least in that code module) will now be ‘based rather than O-based. 11. Using arays | 159 2-D arrays declared inside procedure, wil only be avaabe to thet procedure heros fits declared athe General Decorations, wil be ‘valble to al procedures in that module Te access cements ofa 2.0 ameoy use two incces eg Compary,2) woul cccess the element in row ‘one and column tw. Morne the BR sions nor Code by ing UBound 160 | Excel VBA in easy stepe 2-D arrays have one index which denotes the row, and one index which denotes the column, and therefore can be likened to the Excel spreadsheet structure itself. For example, to input the range of spreadsheet entries shown below to an array, aaa I [1 Business Systems 29 2 Best Image 31 Curtin Ave | 3 [Analytical Systems 28 Drayton Gdns 4 hr ‘we would use: rows columns / \ Dim Company(1 To 3, 1 To 2) As string Dim xw As Integer, cl As Integer For rw = 1703 For cl = 1 To 2 Company (rw, cl) = Cells (rw, cl) .Value Next el Next rw The alternative declaration of Dim Company(3, 2) As String, ‘would reserve space for an array of 4 rows and 3 columns, i. the elements Company (0, 0), Company (0,1) , Company (2,0) etc. ‘would also be available (unless we specify option Base 1), VB arrays can have more than 2 (up to 60) dimensions. For example, we could declare a 3-D array which could be used to represent cells in a single workbook of 3 sheets using Dim BookValues(3, 1000, 256) As Variant for a workbook containing 3 sheets of 1000 rows and 256 columns, of data — elements with 0 index simply being ignored. UBound Asanalternative to Por rw = 1 To 3.we could use Por rw = 1 To (Rand (Company, 1), where Bound (Company, 1) indicates the size of the 1st dimension of the Company array which is 3 in this case ~ the number of rows. Similarly UBound (Company, 2) would represent the value of the 2nd dimension which is 2 in this case ~ the number of columns. ‘LBound is used in a similar manner to specify the lower limit, ReDim here can only be sed 0 input a String type. To be able to nput othe types and have move flexibly, we could use the InputBox method ofthe Application obec. See the VBA Help for move deta N ReDim but cy the very lst dimension can be changed when using ReDim wth Presene Sometimes we don’t know in advance how big an array is going to be, for example when we are entering data into an array using a UserForm. The trick is to first Dim the array without a dimension, Dim Company() As String and then ReDim when we know the size, eg. ReDim Company (3) If we wish to preserve the contents of the array however, we must include the Preserve keyword or else the contents will be lost, Lc ReDin 2reserve Company (3) This can be repeated, e.g, ReDim Preserve Company (5) ‘When inputting data using an input box, an array size could be dynamically adjusted as more data is input. In the example below, an input kox will appear each time with the prompt “Sales Figures?”. As data is input, the array size is dynamically increased by one each time to accommodate the new element. Sales is declared ee in the General Declarations option Explicit Option Base 1 Dim Sales() As String Private Sub ConmandButtonl_Click() static 4 As Integer ica a gree Repim Freserve Sales (i) Sales(i)\= InputBox("Sales Figures?") ~ Since we are using a Static Lope variable ts value is The ReDin statement ensures that the enenered ray siz isinereased by one each time eee Microsoft Tce! Eee Using ays [164 Variant arrays When o ined o ronge the resting based Variant ays ‘a sngle row or a single column. 162 | Excel VBA in easy steps ‘An array, of course can hold Variant types, but also a single variant variable can hold an array! A set of spreadsheet values can be assigned to a Variant in one line of code. x I 5 T [1 Business Systeme 29 Highgrove rd [2 [Best image 31 Curtin Ave ‘Analytical Systems 28 Drayton Gdns ‘The following program segment will assign the values shown on. the sheet above to the Variant variable Company, and arbitrarily display the first one. option Explicit Private Sub ConmandButtoni_Click() Dim Company As Variant Company = Range(*A1:B3") Value MsgBox Company (1, 1) S End Sub The array is assigned to a variant in one ine ees suse tens We can also do the reverse, ic. fill a spreadsheet range with the values of a variant array ~ also in one line of code, e.g. Range ("C1:D3") .Value = Company We can put a variant array variable (named Titles in this case) equal to a single column of values, e.g. Dim Titles As Variant Titles = Range(*A1:A3") .Value In this case of course, the number of columns is one. So to access the 2nd element for example, we would use Titles (2,1). Similarly, ifa Variant variable is assigned a row of values, the row number is always one. To access the 2nd element in the row, we would use Titles (1,2) The Array | The Azoy function based by default function The Array function allows us to quickly and easily initialize a variant array. The code below initializes two variant arrays, Company and Sales, Option Explicit Private Sub CommandButtonl_Click() Dim Company As Variant, Sales As Variant Company = Array("Business Systems", "Best Image", _ "analytical systems") Sales = Array(2.34, 3.42, 5.62) MsgBox Company (0) MagBox Sales (0) Bnd Sub . The first elements have index 0. If Option Base were set to I, the first element would have an index of | een Arrays are faster Generally speaking, another advantage of using arrays is that they can handle data more quickly chan manipulating data on the spreadsheet. To that end, it is advantageous to read in the data from the spreadsheet to an array, perform the required operations on it, (e.g sort it) and finally return it to the spreadsheet. wgarrays | 163 The UserForm ‘A UserForm is a customizable dialog box that can be used to input and display data. We will now make a very simple UserForm containing alist box which will display some company names, UserForm) ‘Wee will use a variant array in our code to hold the values used to populate this lst box To make a UserForm | From the VaE menu, click Insert, UserForm [a aren ‘edie Dee ery conte sheets (Seet] | He hobo The UserForm designer appears (see over). Excel VBA in easy steps cont'd User . Clek the ListBox control button on the UserForm ToolBox, Melt and draw alist box on the form. View the Properties (Laan window and note the name of ths list box (ListBox!) VBE menu, of 9 convo, select View, Properties Window from the VBE paca ett) 1B) seaz sheen) Shee (Sheet) wero ED sero! 3. Note that the name of this UserForm 4, Double-click on the is UserForm|. If at any time we wish to return to the UserForm designer, double-click this name. UserForm to access the UserForm's code module, [5 Ensue that UserForm is chosen inthe Object box. Choose the hitalize event procedure inthe drop-down and write the code shown, [WeorForm Option Explicit _ Private Su) UserForm Initialize() Dim Company AS Variant Conpany = Array("Business Systems", _ "Best Inage", "imalytical Systems") UserForm! .ListBoxi.Liet = Company End Sub f The ist property of the list box is used to optiate the list box. It requires a variant array 1, Using arrays | 165 cont'd The Ustad propery coud be Ra) pany onay index 166 | Excel VBA in easy steps G Place a command button on the spreadsheet and place the code in it as shown, in order to simply display the UserForm. Private Sub Conmandsutton1_Click() UserForm.show End Sub 7 Totest he above code, retum to the Excel sheet, exit design made and clck the command button. Qur UserForm with its lit ‘box should appear as shown below. Clic its Close button, Return to the UserForm designer by double-clicking UserForm! in Project Explorer from the VBE. Double-click the lst box on the UserForm in order to access the ListBox! _Click event. Write the code shown below. Private Sub ListBoxl_Click() Listindex indicates the row MsgBox ListBox1.Value number of the lst box MegBox ListBox1.ListIndex —— entry ~ starting with zero End Sub : Alter making our UserForm appear once Si es more (as per step 7, or by clicking the Run button in the VBE), dick on one of ‘the list box entries et ins oad Syste The list box’s Value and Listindex property values will be displayed icrosatt Excot (X) MM WicroroftExcol X} Run-time errors Programming errors are of two main types, syntax and run-time. Syntax enrors arc those which occur at development time, eg. omittinga Next ina For...t=xt loop. We have seen (only t00 often!) how these errors will be detected by the syntax checker ~ the program will not be allowed to run, Run-time errors on the other hand, are errors which occur when the program is actually running. For example, consider this code segment which will divide 10 by the value in cell Al Private Sub ConmandButtoni_Click() MsgBox 10 / Cells(1, 1) .Value End stb If there isa zero (or no value) in cell Al, aru occur and the following message will result: Take note of the error number ‘Whereas this is invaluable information to us as program developers, itis not what the user/customer wants to see. This run- me ertor reporting can be temporarily turned off by including on Error Resume Next before the offending line. This will cause program execution to continue undaunted after an offending error. Private Sub CommandButtonl_Click() On Error Resume Next MsgBox 10 / Cells(1, 1).Value a Sub In this case, with non-zero values, the result of the division will be displayed, whereas a division by zero will go unannounced, i. no message box! Such error “trapping” is automatically turned off when a procedure terminates. Alternatively, on Error Goto 0 ‘can be used to turn error trapping off. 1 Using arrays | 167 Aner with Number (3 wi resut texts es.) instead of number 168 | Excel VBA in ex steps cont'd The user could therefore be alerted, but not given the option of debugging or terminating the program by modifying the code as follows: Private Sub ConmandButtonl_Click() on Error Resume Next Msgzox 10 / Cells(1, 1).Value If Brr.Number = 11 Then GoTo divzero Exit Sub divzero: MsgBox "Al mist contain a non-zero number" End Sub The line 1f Srx.Munber = 11 Then Gofo divzero causes control of the program to be transferred to the line with the label divzero. Label names are always followed by a colon. Ifan error ever occurs, the Err object is filled with information about the current error. Number is a property of this Brr object which, indicates the assigned number of the current error. Note the use of Exit sub, without which the line with label divzero would be executed, even if there were no error. ‘The above program code should work correctly for all non-zero numbers, but give an error message, as shown below if zero (or nothing) is entered into cell Al. Microsoft Excel | must cntan a non-zero ruber CommandButtont eo] We could also use the Description property to describe the error, i.e. we could replace the corresponding line above with, divzero: Msgbox Brr.Description in which case we would get the message “Division by zero”. Arun-tine error will occur if we try to initialize an array clement beyond the array’s capacity. For example, if this code were run, an error message would result since element 3 does not exist. Dim Sales(2) As Variant Sales(3) = 32.34 "— "Subscript out of range” would result Ifthe ussr were for example, inputting array elements using an input bx, we could write error trapping code to give an alert if too many entries were attempted Option Explicit option Base 1 Dim Sales(2) As Variant Private Sub CommandButton1_Click() on Ercor GoTo overRange ‘An error number Static i As Integer of 9 indicates nae "Subscript out Sales(i) = InputBox("Bnter Sales") . Bxit Sub — ofrree’ overRange: If Brr.Number = 9 Then _ MsgBox "Only 2 entries allowed" Bnd sub Ie the command button is clicked forthe third time and an attempt is made to erroneously enter a third sales figure, a friendly message appears Using arrays | 169 Names ‘A Name defined in Excel (Insert, Name, Define..), eg “Sales” provides us with a way of communicating with Exeel from VBA. We could refer to an Excel range from VBA using Range ("Sales") for example. This code will increase the values in a range named “Sales” by 10% and format the numbers correct to two decimal places. Private Sub CommandButtonl_Click() Dim ¢l as Range For Each cl In Range("Sales") cl.Value = cl.Value ¥ 1.1 cl.NumberFormat = ".00" NumberFormat achieves the same effect as Using the Format Cells dialog box from Excel (Format, Cells. Number [tab], Custom) Here isa novel way of storing your secret data in a Name which persists from session to session! First place some data in the range ALAS, Clicking the first command button defines a Name (adds it to the workbook Neines collection) called mytvame which stores a variant array, which itself contains the values in the range A1:A3. If the workbook is then closed and reopened (the values in the range ALAS having perhaps been deleted), the values are still available ‘when the second command button is clicked! Private Sub Commandauttent_Click() Dim m As Variant m = Range (*A1:A3") .Value i ay m Names Add Name:="myName", Re sub The Name Private Sub ConmandButton2_Click() containing the Dim n As Variant variant aray is = [myNome] Evaluate” ({]) ia NagBox (2, 1)~ to assign the values in added to the End Sub : i the array to the variantn Workbook Names The 2nd element in the array will be displayed collection Date and Time Excel already has an extensive range of functions which manipulate date and time.As well as being able to customize this functionality, VBA can extend it to provide extra capability. Now, Date and Time 172 Separating date components 173 ‘Assembling date components 174 ‘Adding and subtracting dates 175 The number of weekdays 176 The Mod operator 177 Anniversaries 178 Chapter hyelve Now, Date and Time Now Even vhough ‘Now specifies the current date and time. Nom( is BSS] icin jou may Private Sub CommandButtont_Click() ormay not MagBox Now() ince Bnd Sub Microsoft Exe! (X] Parentheses, ie, Megécx Now wil sfc The format of the date actually displayed, US or otherwise, will depend upon the Windows Regional settings otonz004 1:52:10 ‘To explicitly format a Date, use the Format function, ¢.g. MsgBox Format (Now, "mnnn") would display “September” in this case and MegBox Format: (Now, *nmm") would display “Sep”. See VBA Help on the Format function. Excel stores dates internally as a Date type (which is of the rmoke en { 1909 same 8-byte form as a Double type), the integral part of which vy -1e Dec 3! js the number of days since Dec 30 1899, and the decimal part of which represents the fraction of the day after midnight. samen cud F0 2° atehogh dates are Mored as decimal number, the way that we Jaton, so Dec 30 1899 wos View them depends on how they are formatted. We can force a node estar dete type Conversion to a Double data type using: Private Sub CommandButtonl_Click() The VBA Cob, MSGBOX CDbI (Now) (Ceonvert 10 End sub Double) furction Fraction of the day since midnight Number of days since Dec 30, 1899 croroft Lxcel covert ory de ble date type Date and Time ‘The Date function returns only the current date withoue the time, eg. MsgBox Date would display 09/09/2004" or similar (again the format displayed will depend on the Windows Regional setting), whereas MsgBox ‘Time would return “15:53:20” or similar. 172 | Excel VBA in easy step j Separating date components ‘We use the correspondingly-named fictions to extract the required parts as Integer values. Examples are given below. Year, Month, Day eed Private Sub CommandButtont_click() | ao MagBcx Year (Date) Bnd ub Hour, Minute, Second Private Sub Commanazuttom_ciick() (EMERY MegBcx Second (Time) End Sub Of course we could have used Now as an argument in both cases instead of Date and ‘Time respectively. DatePart DatePact performs identically to the above functions, e.g. DatePact ("yyyy", Date) would also extract the year as did DotePar isso ¥8AX (Date) above, It does have some special uses however, for ctu pewsang example to find the day of the year: \O Bi mate ee Private Sub CommandButtont_Click() Daten" Magbcx DatePart ("'y", Date) Date) wil etum the present «End Sub umeric quaner (1,2 304). Today is the 253d — day of this year DateValue, TimeValue ‘These extract just the date and time components respectively, e.g, Private Sub ConmandButtonl_Click() MsgBox DateValue (Now) znd sub The date part only of the current datertime is extracted (dentical to MsgBox Date) Similarly, TimeVatue would extract only the time part. 12. Date and Time | 173 Assembling date components DateSerial Whereas Year, Month, etc. split a date into its components, DateSerial does the opposite. For example, DateSerial (2004, 12, 1) would form the date Dec 1, 2004. Ifa message box were used to output such a date, it would be presented according to your particular Windows Regional settings, i.e, either 12/1/2004 (US) or 1/12/2004 (UK). Similarly, MagBox Timeserial (1, 2, 3) would display Car 3 seconds after 2 minutes past | To find the date of first day of the current month use: MsgBox DateSerial (Year (Date), Nonth (Date) ,1} = The date of the first day of the Day | month of Sept 2004 (cisplayed here in US format). The present date in this case is 9/9/2004 eet Date Delimiters Gurnee) ‘The number sign (#) can be used as a delimiter to enclose a pate Vad wi perm type, eg. #10/30/98#, but it must conform to the American format n.e% — (mmidd/yy), It obviously doesn’r, it will be changed before your oe ato eyes! For example, if WegBox Day (#30/20/888) is typed, it wil ae immediately change. Due to this ambiguity, date literals are best avoided. Using double quotes as a delimiter, e.g, “10/30/98” also introduces ambiguity, as well as requiring an extra step to convert it toa date. To convert a String toa Date, se DateValue, eg, DateValue( "December 1, 2006"). As well as being preferable to using date literals, DateVallue is forgiving of the format of che String, eg. MsgBox Datevalue("Dec 1, 2004") will display the date in a format determined by the Regional settings. 174 | Excel VBA in easy steps Adding and subtracting dates Since the integer portion of a Date type represents the number of days, we can simply add or subtract an integral number of days to find another date, e.g. to find tomorrow's date we could use: MagBox DateValue (Now + 1) DateAdd ‘To add intervals other than days, we must use Dateadd. For example, to work with weeks, use the “ww” interval code and to display the date one week hence use: MegBex Dateadd("ww", 1, Date) Dateada interval ode ® See the VBE Help for the other interval codes for Datead. i for months nfo DateDiff ‘We can use DateDi¢ to find the number of days between two Dates. As well as taking into account the different lengths of the various months, DateDi ft also takes into consideration the presence or absence of leap days between the two date intervals, Privete Sub CommandButtoni_Click() Dim strtDate As Date, fnshDate As Date Dim a Ae Integer strtDate = DateValue("Dec 1,2004") fnshDate = DateValue ("Mar 1,2005") n= DateDif£("d", strtDate, fnshDate) MsgBox n End sub find crosoft Excel ‘The number of days between 00:00 hrs Dec 1, 2004 and (00:00 hrs "Mar 1, 2005" is 90 DateDiff can also be used to find the number of months between ‘two dates for example, by changing the interval specifier to "a", eg DateDiff("m", strtDate, fnshDate) Sce Help on the Daten F¢ function for the other interval specifiers. 12, Date and Time | 175 The number of weekdays We could omit DateDif ond BSS] ci tre cove the oop anDate Use VB b wherever possble eg wSundoy ord BS] 6/84 cxarmpes Tiy sping "Excel VBA Dore ana 176 | Excel VBA in easy steps WeekDay WeekDay will determine the day of the week as a number between Land 7 —where Sunday is 1 by default, e.g Private Sub ConmandButtonl_Click() MsgBox Weekday (Date) nd sub In this case, today is Thursday ~ the Sth ~ day of the week (with Sunday as day 1) ‘We previously found the number of days between Dec 1 2004 and March 1 2008 to be 90. We now wish to find the number of working days (Monday to Friday) ~ perhaps for a project ~ between these two dates. March 1 2005 itself will this time be included Private Sub CommandButtonl_Click() Dim strtDate As Date, fnshDate As Date Dim dt As Date, n As Long, i As Long Dim nunWlorkDays As Long strtDate = DateValue("Dec 1,2004") fnehDate = DateValue("Mar 1,205") numiorkDays = 0 n= DateDiff("a", strtDate, fnshDate) For i= 0 Ton ‘n since March 1 is included dt = Weekday(strtDate + i) TE (dt <> 7 And dt <> 1) Then — nunWorkDays = numWorkDays + 1 End tf Next i MsgBox nunWlorkDays End sub If not a Sat and not a Sun then. increment the number of warkdays The number of working days between project start and finish (inclusive) is 65. ~ As it stands, our program does not take account of any public holidays in the period, e.g. Christmas day. These would need to be explicitly, individually accounted for by the code. The Mod operator Thy MsgBox (1900 Med 4 = SS 0) to confren that i espoys Ta We could also determine fa BS] yecris op ty testing Morth(DoteSeriat (yr 2,29)) = 2, whch seams to be forging of the bogus 1900 leop yeor! False. Or wil evoluote to Tre ether expression evaluates to Tre. Try Msg (Te And Fase Or To test the code futher, ty changing yr to 1901, 1904 2000, et. Hod gives the remainder after a division. In this example 13 is divided by 3 (4 times) to give a remainder of 1 which would be displayed. Private Sub CommandButton1_Click() MagBcx 13 Mod 3 End cub Nod is an arithmetic operator, not a Date function but it could be used for example, to determine whether a year is leap or not. Mod. can be used to determine whether a number is exactly divisible, e.g, 1900 Nod 4 would return o, indicating that 1900 was exactly divisible by 4 ‘This would suggest that the year 1900 was a leap year, since itis divisible by 4, but in addition, in 1582, Pope Gregory decreed, that years divisible by 100.were not to be leap years. Ifa variable yr were 1910 or 2000 for example, also stipulating that (yx Mod 100) <> 0, ic. yx is not divisible by 100, would rule out 1900 and 2000 since they are. “However, to further compensate for the earth's non-exact rotation, the good Pope decreed that every 400 years was to be a leap year, i.e. ifwe also allow the condition yr Mod 400 = 0, ie. yr could be divisible by 400, 2000 would now qualify, but 1900 would not. ‘Combining these conditions into one logical expression, we could test for a leap year (e.g. 1900) using: Private Sub CommandButton1_Click() Dim yr As Integer previsss * Troe for 1900 MsgBcx (yr Mod 4 = 0) And (yr Mod 100 <> 0) _ or (yr Mod 400 = 0) x End sub ~ False for 1900 False for 1900, since 1900 is since 1900 is not divisible by 400, ie. 1900 divisible by 100 does not qualify on this basis icrosof ~ 1900 is not a leap year 12, Date and Time | 177 Anniversaries To find your age, you could subtract the year of your birth from the present year. ‘The only problem is that you may or may not have had your birthday yet this year. If you haven’t had your birthday, you will need to subtract a year. How do we determine if you have had your birthday this year or not? We need to test whether today’s date (Date) is less than the date of your birthday this year “The date of your birthday this year will be given by Dateserial (Year (Date), Month (dob) , Day (dob) ), where deb is your date of birth, ie. your date of birth with the current year substituted for your year of birth, so Date < DateSerial (Year (Date), Month (dob), Day (dob) ) will be if your birthday has yet to come this year ‘This program should display your age if you use your date of birth. Private Sub CommandButtonl_Click() Dim age As Integer Dim dob As Date, bday As Date dob = DateValue ("Oct 30, 1966") bday = DateSerial (Year (Date), Month (dob), Day (dob) ) age = Year(Date) - Year(dob) + (Date < bday) MsgBox age & " years old" End Sub Ag ae EEE) §— the numeric value of -1 B pacer (True) if your birthday has not yet passed, and (Date < bday) will have the VBA commesion 0 (False) if t has Speaking of birthdays, you could determine the day of the week {Msplor Chute) that you were born using this code with your date of birth aoe ivate Sub CommandButtonl_Click () Dim dob As Date dob = DateValue("0ct 30, 1966") MegBox Format (dob, "dddd") End sub Cee 178 | Excel VBA in easy step i i The Application object The Application object represents Excel itself,As well as having many useful _genieral purpose properties and methods, the Application object gives access to the many well-known Excel worksheet functions, Application properties 180 WorkSheetFunction 182 Methods 184 Volatile 186 NE 8 gg Application properties ‘The App! icat ion object is the parent of all objects in the Excel Object Model BSS] 022007 in Becet (Tools Options.) npreprite cong Ke) Noto opin proper DisployGiicines for excmple is 2 propery ofthe Window abject, wich tel ko child object of the Applicaton object, The deel @) worksheets ‘lays be 5 unless iis se otherwise using Too’, Optens.. Genera tab 180 | Excel VBA in easy steps Option settings Since it represents the entire Excel application, the Application object can give access to many of the application-wide settings of the Excel Tools, Options... dialog box. For example, we can set the number of worksheets in a (new) workbook using the Sheet eTnNewtorkbook property as follows: Private Sub CommandButton1_Click() Application. SheetsInNew#orkbook = 5 End sub If this code is run and a new workbook opened, it will contain five worksheets as showh below. [e's > wi\ Sheets /sheet2 {Sheet { Sheats {Sheets /~ StatusBar This property is used to set the text which appears on the status bar at the bottom left of the screen. Private Sub ConmandButtonl_Click() Application.statusBar = "Calculating..." Bnd sub When the code is run, the text will appear in the status bar of the Excel —_ window > Wi\ Sheets { shest2 {sheet 7 oxen Te Autashapes> \ % OO ae ScreenUpdating To avoid screen flicker and make your code run faster, the screen can be frozen when your code is running using: Application.ScreenUpdating = False ‘Whereas screentpdat.ing will revert to Tue automatically when the code terminates, it is good practise to do this explicitly with: Appl:cation.ScreenUpdating = True DisplayAlerts ‘Under normal circumstances, when we close a workbook, we will be asked for confirmation if changes have been made, he Seem tenia Ce | eel IfDisplayalerta is set to False, this dialog box is suppressed, and any changes are lost, as running this code will demonstrate. Private Sub ConmandButtont_Click() application.Displayalerts = False Act ivelorkbook.Close Rpplication.DisplayAlerts = 7 id au iy Returning DisplayAlerts to True is not essential since it vill be done automatically on ext from the procedure ‘Try running the above code afier making a change to a sheet. ome Aeptee¥?” Reopen the workbook and note that the changes have not RS oss been saved ie Setting DisplayAlerts to False is particularly useful if we Applccion eg rer than wish te avoid the possibility of a user canceling an operation Arpicionseetin ven whise code is running, thereby possibly avoiding subsequent code conflict. 13. The Application object | 18 VWorksSheetFunction WorkSpeetfurcion Werksheetfuncoon object. The Worksheetfuncion object con be found in the Excel Object ‘Medel diagram 0 child of Appicaton abject Dont erraneousy se Seng fictions where @ ge type is expected WorksheetFuncin object gies us ‘access tothe mathematcal (e—, MINVERSE), stonivcal (2g. STDEY), and (eg. NPY) Excel 182 | Excel VBA in easy steps ‘We can access most of Excel's worksheet functions using VBA’ s Worksheet Funct ion. Sum For example, we can obtain the result of Excel’s SUM function shown here, by using the code shown beneath. Note that the formula itself is not inserted. Private Sub CommandButtoni_click() cells (4, 1).Value = _ Worksheet Function. Sum (Range ("A1:A3"}] Bnd Sub o Take note that the argument of Sum is a Range object — not a String To determine which of the Excel worksheet functions are available, type “worksheetFunct ion.” into your VBE editor and scroll through the IntelliSense suggestions which appear. Pravace Sub CamandButtont_clicke() BorksheeeFunce ion. Ena Sub 8 ipmt al sin “8 Ise <9 IoEnor IsLosical “IGNA “9 IsNonTed ‘Many Excel functions are duplicated in VBA and serve the same purpose, e.g, Excel’s ABS and VBA’s Abs. Some are not represented at all, eg. the Excel CONCATENATE is not available from VBA using the Worksheet Funct ion object since ‘VBA has a perfectly good & operator to concatenate strings. VBA Hep et Help on PMT From VBA we can access the PMT Excel worksheet function which will allow us to calculate mortgage payments. For example, we cotld calculate the monthly payments on $100,000 over 20 years at 5% interest using: Private sub CommandButtoni_Click() Dim rate As Double, nper As Integer Dim paymnt As Double rate = 0.05 / 12: nper = 20 + 12 paynnt = WorksheetFunction.Pmt (rate, mper, 100000) MsgEox paymnt mnd sub Note that rate is the rate per period, ic. the monthly interest rate which is the annual interest rate divided by 12, and nper is the total number of monthly payments over 20 years, ie, 20x 12. ‘A negative value indicates that payment must be made Microset cal) IF t is desirable to present this result as a positive value correct to two decimal places, for Magox paynnt we could substitute: MsgBox Format (Abs (paymnt}, ".###) “4 aS ‘Abs will return positive “.##" will format correct to 2 decima values only places, but compared with ".00" will not insert 0 placeholders The payment would then be displayed as shown: 3. The Applica Methods (Chose Insert ‘Melle fom the VBE menu to Procedures that ‘ore caled by nTime and Onkey muse be standard code modu Since the W have the the worksheet before pressing the Tab key (or dhematvel Set the CommandBurtens TeakeFecusOnClek prope to Fae). 14 | Cacel VBA in easy steps OnTime CnTine allows us to run some code at a time of our choosing. | Create a procedure ina standard code modi that ‘we wish to run some time in the future. sup nzoxy / vegeon "Sub cated te Sub 9D inet cae drs bow fiche normaly cal ts Bia ab vec scones ser Ue arts bdo sic ore epee eee ee Application.OnTime Now() + _ ‘Timeserial(0, 0, 3), "mBox" snd sub x i TimeSerial returns a time of O hours, The name of the (0 minutes and 3 seconds procedure to be run PERT ec secon ter te Shsiied, command button is clicked, this message box appears OnKey onkey allows us to run a procedure by simply pressing a key. For example, after this code is run, we could subsequently run the ‘mbox procedure (assuming that it is in the standard code module) by simply pressing the Tab key. Private Sub Commandputtonl_click() applicacion.unkey “{ras}~, "muox” End sub To return the Tab key to its default functionality, use: Application.Onkey "(TAB)" til Take cove thot there is no frpporcne data ia cel tothe ge When using a Worksheet Orange event which itselP changes the contents of ace ApplcavonEnobleEvents should beset to Fake inthe procedsre, lest a chain reaction ccs The selection rove down (or whatever was the pressing Enter, sce that ‘peraon was aso undone. Teg Offset!) Select could be Whereas iis Excel Sameching of a lost eso Undo undo will undo the last action taken by the user. Here’s a novel, program which saves values that you overtype. It places the ‘overtyped value in a cell to the right, In this case, Undo causes the typed-over value to temporarily reappear in the same cell, Private Sub Worksheet Change (ByVal Target As Range Dim x As Variant Application. Bnablezvents - False x = Target.Value — Rpplication.tndo Target .Offset(, 1) .Value = Target.Value Target.Value = x Re pois eetciinias True» After the Undo, Soe Target Value wil hold the old value which is then place in the cell one ~~ The new value entered is saved in x Target Value = x causes the saved (typed-in) value to be returned to the cell column to the right After a new number is entered into a cell, the ‘overtyped value will appear in the cell to the right ee SendKeys ‘The Sendxeys statement can be used in code to send keystrokes t Excel. The effect is exactly the same as physically pressing the corresponding key/s on the keyboard. For example, the Alt-+h key combination from the Excel window causes the Help menu to drop down. The VBA code SendKeye "th" same effect. would have exactly the s ‘The ¥ character represents the Alt key. See Help for others 1. The Application object | 1 Volatile The Excel S function Rand is into 9 cel. A fdecime Perform a cakuation elsewhere fon dhe sheet using an arbirary formula ie update a vale ypon Ishich a formula depends (see age 90), Anew random ruber wil oppear showing that Randi «volte fareton You can also demensrate that Now isa vlan Excel worksheet function, Ate entering =Now0 into cel you vl eed t formato show seconds 50 that yeu wl be able se thot the time updated when a recakcuation ccs 186 | Excel VBA in Avolatile function is one which is automatically called when a sheet is recalculated. UDFs (user defined functions) are not volatile by default, Consider this UDF which simply displays the iname of the active sheet in a cell. Type the UDF shown below into a standard code module (as described on page 156); Function GetWorksheetName() As Variant GetWorksheetNane = Activesheet Name End Function ‘The sheet name will appear in cell ‘Al when the function is entered Unfortunately, if the worksheet name is now changed, whereby a recalculation is deemed to have occurred, the UDF will not, automatically trigacr, and the new name will not be displayed in cell AL. Try it. To remedy this, include application. Volatile as the first line in the UDF as shown below: Function GetWorksheetName() As Variant Application.Volatile GetWorksheetName = ActiveSheet .Name End Function At (VI =GetworkSheetNamed ry eran geet Now the new name is displayed at once in cell Al when the sheet name is changed, thereby demonstrating that our UDF is volatile A 18, 50, 66, 149, 182 + +s 26 < 37,39, 49 <> 47, 176-177 ~ 26 1-Darays 158-159 2D&3-Datrays 160 Alsyyle 59 Abs 182-183 Activate 84, 91-92, 98 ‘ActiveCell 71 ActiveSheet 80, 85, 105 ‘Add $2, 170 Address 60 And 35, 176-177 Application 57, 105, 126, 180-186 Areas 125-126) Argument 145 Arithmetic operations 26 Arrays 158-170 Array function 168, Auto Daca Tips 30) ‘Auto List Member 24 ‘Auto Quick Info 154 ‘Auto Syntax Check 13 BeforeClose 103 BeforeDoubleClick 89 BeforePrine 102 BeforcRtightClick 89 Bold 56-57 Boolean 22, 42 BoundColumn 140 Breakpoints 31 ByRef 147 ByVal 87, 147 Caleulate 90 Cancel 89 Caption 128-130, 141 Date 174 Db 172 Cells 29, 63-64, 84, 92, 112 Change 88, 135, 137-138 Check box 137 Cine 178 ClearContents 55, 155 ClearFormats 131 Close 98 Code module 11, 70, 72, 156 CodeName 81, 93-94 Collection 57, 81-83, 96, 104, 170 Color property 62 Color palleste 61-62, 111 Colorindes 61, 65, 108, 122-123, 131, 148 Colors property 61-62, 111 Column propery 126 ColumnCount 140 Columns 84-85, 108 ColumnWidth 85 Combobox 139-140 Command bution 128 Comment 19 Index | 1 CONCATENATE (Excel function) 182 Concatenation 50, 182 Continuation character 45, 87 Control Toolbox 9, 13, 128, Copy 113, 142 Count 54, 82, 85, 111, 125-126, 142 Counter 47 Se 149 Currency 74, 76 CurreneRegion 114, 120 Customize dialog box 19 Data Type Summary 25 Date 22, 172-178 Date delimiters 174 Date literals 174 DateAdd 175 DateDiff 175 DatePart_ 173 DateSerial 174, 178 DareValue 173-174, 178 Day 173, 178 Debug Prine 32 Debugger 14, 30 Declaring variables 16, 22-23 Default properties 11, 112, 134 Delete 80, #2 Delete blank cells 46-49 Design mode 9 13, 87 Design-time 129 Dim. 16, 23, 150-151, 153 DisplayAlens 18 Do 36 Do Until 36 Do While 37 Dock 72 Dot operator 54, 56 Double 22, 26 188 | Excel VBA in easy steps Ele 34, 124, 126 Blself 124, 126, 142 EnableEvents 88, 185 End 16 End Function 146 EndIf 33-34 End Select 38 End Sub 11, 144 Err 168 Errors 14, 22, 167-169 Events 86, 99 Excel 97 61, 65 Excel Object Model 57, 104, 180, 182 Exit Design Mode 12 Exit For 45 Exit Sub 168 Exponentiation 26 Fikey 25 False 22, 24, 37, 42, 177 Flg 42 Focus 13 Font 56, 61-62, 108 For Esch..Nest "83 For..Next 28, 73 Format 172, 178, 183 Formulas 26 Formula, Property 58 FormulaRICl 59, 71 FullName 97, 102 Functions 144, 146-147, 149, 154, 156 i General Declarations 21, 151-152, 158-159 Global variable 151 Globals (Application properties) 18 Got 168 Help 25, 38, 57 Hierarchy, Object 57 Hour 173 IE.Then 33, 42, 73, 126 legal variables 16 Immediate window 32, 38 Indent 41 Index 81, 96-97, 117, 119, 125, 190 Initialize event 165 Initializing variables 16, 23, 136 Inputbox” 161, 169 InStr 50 Integer 16, 22, 28 IntelliSense’ 11, 24, 35, 98 Interior 122-123 Toternet 8, 176 Intersect 122, 124 b< 3839 > 38.39 IsNumeric 114 hom 83 key 97 Keywords 16 Left 50 Len 51 Liferime 153 Line continuation character 45, 66, 87 LinkedCell 139 List property 165 ListBox control 165 LisillRange 139-140 ListIndex 166 Logical operators 35 Long 22, 29 Loop 36-37 Loop Until 36 Loops inside loops 44 Macro 8, 68-78 Macro, Run 69 Macto, Edit 70-71 Max property 136 Methods, Application 184-185 Methods, Collection 81-82 Methods, Object 54-55 Methods, Workbook 98 Methods, Worksheet 80 (Microsoft Excel Object Model 57, 104, 180, 18 Index | ‘Mid 51 Min property 136 Minute 173 Mod operator 177 Module, Code 11, 70, 72, 156 Module-level variable 151 Month 173, 177-178, MsgBox statement 18 MsgBox function 154 Name 80-83, 93-94, 96, 190, 133, 170, 186 Names 170) Named parameters 142, 155 Not 35, 115 Nothing’ 124 Now 172-173, 178, 184, 186 Number 168 NumberFormat 170 Object 54, 56-57 Object, Application 105, 161, 180 Object’ box 88, 165 Object, Collection 81, 83 Object, Error 168 Object, Range 87, 107-125 Objece, Worksheet | 80-81, 84 Objece, WorksheetFunetion 182 Object, Workbook 0, 98 Object Browser 62 Objectvariables 63 Object-oriented 53 Objects 56: Offset 92, 117-118 On Error Got 0 167 190 | Excel VBA in easy steps ‘OnKey 184 OnTime 184 Open 98, 108, Operator symbols 26 Option Base 159, 160-161 Option buttons 138, 141-142 Option Explicit 11, 20, 151 Or 35, 177 Onrdent 41 PageSeesp 102 Palette, Color 61-62, 111 Parameter 145 Parent 105 Parentheses 26 Paste 113 Path 97 Personal Macro Workbook 68 Personalids 75-76 PMT 183 Preserve 161 PreView 80) Prine 32 PrintOut 80 Prine Preview 80, 102 Private 11 Procedures 144-156 Project Explorer 10, 72, 75, 88, 99, 165 Prompt 18, 154-155, 161 Properties, Application 180 Properties, Collection $2 Properties, Range 108-109, 114-119 Properties, Workbook 97 Properties, Worksheet 80 Properties window 98, 129-130 Protect 94 Public 151 RICK style 59 Rand 186 Range 11, 36, 87, 108, 111 Read, Property 58, 85 ReDim 161 RefersTo 170 Regional settings 172 Registry 72 ‘Requite Variable Declaration 21 Resize 119, 121 RGB fimnction 62 Right 50 RightFooter 102 Row, Property 81, 126 Rows 81, 84-85, 109 129 Run-time errors 167-160 Scope 150 SercenUpdating 181 Second 173 Security setting 12 Select 54, 63, 71, 84, 108 Select Case 38, 66 Selection 60, 111, 115, 120, 126, 121, 152, 181 SelectionChange 86-87, 124 SendKeys 185 Ser @ SheetDeactivate 101 SheetSelectionChange 99-100 SheetslaNewWorkbook 180 Single 22, 26 Single step 31 SmallChange 136 SpinDown 135 SpinUp 135 Static 153, 161, 169 StatusBar 180 Step Into 31 Stop button 14 Stop Recording button 69 Sir 18, 28, 66, 149 String "13,'16 String handling 50-52 Sub 1, 16, 144-152, 154 Sum 109, 182 Swap variables 17 Syneacerror 13, 167 Tab 41, 184 ‘TakeFocusOnClick 61, 65, 184 ‘Target 87-89 ‘Task bar 11 ‘Textbox control 133-134 TextBox object 134 ThisWorkbook 99-100, 102 Time 172 TimeSerial 174, 184 ‘TimeValue 173 ‘Toolbar, o run a macro from 77 Tim 49 True 22, 37, 42, 177 “Type, Variable 16 “Type-declaration characters 23 ‘TypeName 105 index | 19 UBound 160 UDF 156, 186 Uncomment Block 19 Undo 185 Union 123 Unprotect 94 UsedRange 116 UserForm 164-166 User defined function 8, 156 Value 11, 112, 134, 138, 166 Variable 16, 83 Variane (Variable ype) 22-23 Varian array 162, 164, 170) WCHLE 66 wbGreen 62 vbOK 155, vbOKOnly 155 wbSaturday 176 vbSunday 176 vb¥es. 155 vb¥esNo 154-155 View Code 10, 13 Virus protection 12 Visible 170 Visual Basie 8 Visual Basic Finor 10, 24 VLOOKUP (Excel function) 118 Volatile 186 WeekDay 176 With... End With 109 Workbook 57, 96-106 Workbook BeforeClose 103 Workbook BeforePrint 102, Workbook Open 108 Workbook SheetCalewlate 106 Workbook SheetDeactivate 101 Workbook SheetSelectionChange 99-100 Workbooks, Collection 96 Worksheet object 57, 80-94, 105, 116 Worksheet BeforeDoubleClick 89, 91-92 Worksheet BeforeRightClick 89 | Worksheet Calculate 90 Worksheet_Change 88 Worksheet SelectionChange 86-87 WorkSheetFuesion 182 Worksheets 82-83 Write, Property 58, 85 xiColorindexAtomatie 61 xDown 116 XLStare folder 76 Year 173, 178 In The leading Mi ste} ‘Access 2003 in easy steps Bulking PC in easy steps Cit in easy steps (C+ Programming in easy steps ‘Computing for Seniors in easy steps (CSS in easy stops Digital Photography in eary steps ~ Sth Exton Digtal Phocagraphy for Seniors in eaty sept Digtal Scrapbooking in easy stepe Dreamwesver Bin easy steps Excl 2003 in easy tepe Excel VBA in easy steps FrontPage 2003 in easy steps HITML in easy step istrator C52 in easy steps InDesign C52 in easy steps Incernet for Seniors in eny stepe Len easy stops ~ 3rd Edition Mac OS X Tiger in easy steps (Online Poker in easy sep Sin easy seps ~ 6th Eaton Photoshop CS2 in easy steps Photoshop Elements 4 In easy steps SOL in easy stops Upgrading & Repairing PCs in easy sep Windows XP in easy stops - $P2 Eatin Windows XP Tips & Tricks in easy steps Wireless Home Networking in ey steps Check out the full selection at www. Computer Books Series 1820782722 e<07e7919 1840781505 ea07e2951 1840782500 1a407e201x 1690762506 eao7e2214 1990783036 1940783125, eaorares eeorerri4 630762692. aeo7ansaa 1ea07e3028 50783044 aao7a3ie 1890783052 1320780943 ‘es07e2060 1es0720932 1840783001, ve907@0117 189078296% 1840783079 1210720870 es07e2978 1940782897 yeasysteps.com

Vous aimerez peut-être aussi