Vous êtes sur la page 1sur 154
° es veelrr PvTLTD. IT TRAINING & SERVICES _ #207, (2 Floor), HUDA Maithrivanam, Ameetpel, Hyderabad ~ 500 038. Ph # 28743392, 23751199, 40340000, E-Mall:enq@peérstech.com,URL: wwwepeerstech.com a ae e Peers Technologies Private Limited COURSE MATERIAL #207, 24 Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500 038 Phone : +91 - 40-2374 3392/ 2375 1199/ 4031 0000 Peers -VBA- Excel VBA-Excel Excel VBA is a programming application that allows you to use Viswal Basic code to run ‘the many features of the Excel package, thereby allowing you to customize your Excel applications. Units of VBA code are often referred to as macros, More formal terminology is covered in this chapter, but you will continue to see the term macro as a general way to refer to any VBA code. In your day-to-day use of Excel, if you cary out the sam@: sequence of commands repetitively, you can save a lot of time and effort by automating those steps using macros. If ‘you are setting up an application for other users who don’t know Much about Excel, you can use macros to create buttons and dialog boxes to guide them through your application as well as automate the processes involved. If you are able to perform an operation manually, you can use the macro recorder to capture that operation, This is a very quick and easy procéss and requires no prior knowledge of the ‘VBA language. Many Excel users record and zun macros and feel no need to learn about VBA. However, the recorded results might not be very flexible, in that the macro can only be used to carry out one particular task on one particular range of cells. In addition, the recorded ‘macro is likely to run much more slowly than code written by someone with knowledge of ‘VBA. To set up interactive macros that ean adapt to change and also run quickly, and to take advantage of more advanced features of Excel such as customized dialog boxes, you need to eam about VBA. . . se compression that we are dismissing the macro recorder. The macro recorder iy one of the most valuable tools available fo VBA programmers. It is the fastest way to generate working VBA code, but you must be prepared to apply your own Knowledge of VBA to edit the secorded macro to obtain flexible and efficient code. A recurring theme in this book is recording an Excel macro and then showing how to adapt the recorded code, In this chapter, you Jeam how to use the macro recorder and you see all the ways Excel provides to run your macros. You see how to use the Visual Basic Editor to examine and change your macros, thus going beyond the recorder and tapping into the power of the VBA language anid the Excel object model. You can also use VBA to create your own worksheet functions. Excel comes with hundreds of builtin functions, such as SUM and IF, which you can use in cell formulas. However, if you have a complex calculation that you use frequently and that is not included in the set of standard Excel functions—such as a tax calculation or a specialized scientific formula you can write your own user-defined function. Using the Macro Recorder Excel's macro recorder operates very much like the recorder that stores the greeting on your telephone answering machine. To record a greeting, you first prepare yourself by rehearsing —— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 1 Peers -VBA- Excel ee the greeting to ensure that it says what you want, Then you switch om the recorder and deliver the greeting, When you have finished, you switch off the recorder. You now have a recording that automatically plays when you leave a call unanswered. Recording an Excel macro is very similar. You first rehearse the steps involved and decide at what points you want to start and stop the recording process. You prepare your spreadsheet, switch on the Excel recorder, cary out your Excel operations, and switch off the recorder. ‘You now have an automated procedure that you and others can reproduce at the press of a button, Recording Macros Say you want a macro that types six month names as three-letter abbreviations, Jan to Jun, across the top of your worksheet, starting in cell B1. I know this is rather a silly macro because you could do this easily with an AutoFill operation, but this example will serve to show you some important general concepts: 1 First, think about how you are going to carry out this operation. In this case, itis easy— ‘you will just type the data across the worksheet, Remember, a more complex macro might need more rehearsals before you are ready to record it. OQ Next, think about when you wan to stétt recording. In this case, you should include the selection of cell:B1 in the recording, because you want to always have Jan in BI. If you don’t . select BI at the start, you will record typing Jan into the active cell, which could be anywhere ‘when you play back the macro. Q_ Next, think about when you want to stop recording. You might first want to include some formatting such as making the cells bold and italic, so you should include that in the recording. Where do you want the active cell to be after the macro runs? Do you want it to be in the same cell as Jun, or would you rather have the active cell in column A or column B, ready for your next input? Assume that you want the active cell to be A2, at the completion of the macro, s0 you will select A2 before turning off the recorder. Q_ Now you can set up your sereen, ready to record. In this case, start with an-eriipty worksheet with cell Al selected. If you can’t see the Developer tab above the Ribbon, you will need to click the round Microsoft Office button that you can see in the top left comer of the Excel screen shown in Figure 1-1. Click Excel Options at the bottom of the dialog box and select Personalize, Select the checkbox for Show Developer tab in the Ribbon and click OX. Now you can select the Developer section of the Ribbon and click Record Macro to display the Record Macro dialog box, shown in Figure 1-1. See PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 2 Peers -VBA- Excel in Sys “| 3 Figure 1-1 In the Macro name: box, replace the default entry, such as Macro], with the name you iwant for your macro. The name should start with a letter and contain only letters, numbers, and the underscore character, with maximum length of 255 characters. The, macro name must not contain special characters such as exclamation points () or question marks ¢?), nor should it contain blank spaces. It is also best to use a short but descriptive name that you will recognize later. You can use the’underscore character to separate words, but it is easy to just use capitalization to distinguish words, Call the macto MonthNames1, becouse you will ereate another version later. In the Shorteut key: box, you cai type in a single letter. This key can be pressed later, while holding down the Ctrl key, to run the macro, Use a lowercase m. Alternatively, you can use an uppercase M. In this case, when you later want fo run the macro, you nced to use the keystroke combination Citl+Shift+M. It is not mandatory to provide a shorteut key; you can run a macro in a number of other ways, as you will sec. In the Description: box, you can. add text that will be added as comments to the macro. These lines will appear at the top of your macro code. They have no significance to VBA, but provide you and others with information about the macro, All Excel macros are stored in workbooks. You are given a choice regarding where the recorded macro will be stored. The Store macro in: combo box lists three possibilities. If you choose New Workbook, the recorder will open a new empty workbook for the macro Personal Macro Workbook refers to a special hidden workbook, which is discussed in a moment. Choose This Workbook to store the macro in the currently active workbook. ‘When you have filled in the Record Macro dialog box, click the OK button. You will see a new Stop Recording button appear on the left side of the status bar at the bottom of the soreen, as shown in Figure 1-2. You will also notice that the Start Recording button in the Ribbon has been replaced by a new Stop Recording button. ———S— Page 3 PEERS TECHNOLOGIES PVT LTD, HYDERABAD Peers ~VBA- Excel nn Were Fa) ret eet Pb stree, Founain. ia Rescns vee | onusger | age Sioa Recerging. 1 Gino Sa Res “You should now click cell BL, tye in Jan, and fill in the rest of the cells as shown in Figure 1-2 Then select B1:G1 and click the Bold and lalic buttons on the Home tab of the Ribbon. Click the A2 cell-and then stop the recorder, You can stop the recorder by clicking the Stop Recording button on the Ribbon or by clicking the Stop Recording button on the status bar. It is important to remember to stop the recorder. If you leave the recorder on and try to run the recorded macro, you can go into a loop where the macro runs itself over apd over again. If this is does happen to you, or any other error occurs while testing your macros, hald down the Ctel key and press the Break key to interrupt the macro. You can then end the macro or go into debug mode to trace errors. You can also interrupt a macro with the Esc key, but it is not as effective as Ctrl+Break for a macro that is pausing for input. : You could now save the workbook, but before you do so, you should determine the fle type you need and consider the security issues covered in the next section. You can’t save the workbook as the default Excel Workbook (*.xIsx) type. This file format does not allow macros to be iticluded. You can save the workbook as an Excel Macro- Enabled Workbook (*.xlsin) type, which is in XLM format, or you can save it as an Excel Binary Workbook (*.xlsb) type, which is in a binary format. Neither of these file types is compatible with previous versions of Excel. Another alternative is to save the workbook as an Excel 97-2003 Workbook (*.xls) type, which produces a workbook compatible with Excel versions from Excel 97 through Excel 2003. Macro Security Ta develop macros with minimum interruption, work with Office 2007's secutity restrictions. Without getting into the complications of digitally signing your workbooks, you have a PEERS TECHNOLOGIES PV? LTD, YDERABAD Page 4 \ | | ps ee + Peers ~VBA- Excel a couple of simple options, Select the Developer tab on the Ribbon and click the Macro Security button. You will see the Trust Center dialog box, where you can select Macro Settings, Here you can enable all macros. This is not recommended because it leaves you ‘wide open to macro viruses, A better alternative is to nominate a specific directory as a trusted location, Click Trusted Locations to the left of the Trust Center dialog box. You probably already have a number of trusted locations, including your XLSTART directory and templates directories. Use the Add new location button to specify a suitable directory for storing your ‘workbooks. You should now save the workbook containing the newly recorded macro into the trusted location. Click the Microsoft Office button and select Save As. In the Save as type drop-down, select the xlsm type and save the workbook in the trusted location as Recorder.xlsm. ms If you can’t see the file extensions, such as .x/mis, in the Save As dialog box, you should open Windows Explorer, click the Tools menu, and choose Folder Options. In the View tab, remove the check against Hide extensions for known file types. The Personal Macro Workbook Id you choose to store your recorded macro in the Personal Macro Workbook, the macro is added to a special file called Personal.xlsb, which is a hidden file that is saved in your Excel Startup cirectory when you close Excel. This mieans that Personal.xisb is automatically loaded when you launch Excel and, therefore, its macros are always available for any other ‘workbook to use. * If Personal.xlsb does not already exist, the recorder will create it for you. You can use the Unhide button on the View tab of the Ribbon tc see this workbook in the Excel window, but it is seldom necessary or desirable to do this because you can examine and modify the Personal.xisb mactos In the Visual Basic Editor window. An exception where you might want to make Personal.xlsb visible is if you need to store data in its worksheets. You can hide it again, after adding the data, with the Hide button on the View tab of the Ribbon. If you are creating a genecal-purpose utility macro, witich you want to be able to use with any workbook, store it in Personal xisb. If the macro relates to just the application in the current workbook, store the macro with the application. Running Macros “To nun the macro, either use another worksheet in the Recorder.xlsm workbook or open a new empty workbook, leaving Recorder.xlsm open in memory. You can only run macros that are in open workbooks, but they can be run from within any other open workbook. You can run the macro by pressing Ctrl#M, the shortcut you assigned at the start of the recording process. You can also run the macro by clicking the Macros button in the View tab of the Ribbon or by clicking the Macros button in the Developer tab of the Ribbon. Both buttons open the dialog box shown in Figure 1-3, You can run the macro by double-clicking the macro name, or by selecting the macro name and clicking Run. ———— PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page S Peers -VBA- Excel Figure 7-3 ‘The same dialog box can be opened bye presi AIWF. Shortcut Keys ~ ‘You can change the shortetit kéy assignéd toa macro using the Macto dialog box shown in Le. Figure 1-4 tis possible to assign the same shorteut key to more than one macro in the same workbook using this dialog box (although the dialog box that appears when you start the macro recorder will not let you assign a shortcut that is already in use). Itis also quite likely that two different workbooks could contain macros with the same shortcut key assigned, If this happens, which macro runs when you use the shortcut? The macro that comes first alphabetically, Shortcuts ate appropriate for macros that you use frequently, especially if you prefer to keep ‘your hands on the keyboard. It is worth memorizing the shortculs so you won’t forget them if you use them regularly. Shortcuts are not appropriate for macros that are run infrequently or es PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 6 I Peers ~VBA- Exce] NS are intended to make life easier for less experienced users of your application, It is better to assign meaningful names to those macros and rum them from the Macro dialog box. ‘Alternatively, they can be run from buttons that you add to the worksheet, You Jean how to do this shortly, Absolute and Relative Recording When you run MonthNames!, the macro returns to the same cells you selected while typing in the month names. It doesn’t matter which cell is active when you start; if the macro contain 5 the command to select cell BI, that is what it selects. The macro selects B1 because you recorded in record mode. The alternative, relative record mode, remembers the position of the active cell relative to its previous position. If you have cell Ai0 selected, urn on the recorder, and go on to select B10, the recorder notes that you moved one cell to the right, rather than. noting that you selected cell B10. ES Record a second macro called MonthNames2, There will be Unee'ifferences in this macro compated with the previous one: Q Click the Use Relative References button on the Developer tab of the Ribbon. You can o this before you start recording or while you ate recording, Do not select the Jan cell before typing, You want your resored macro to type Jan into the active cell when yourun the macro, * O Finish by selecting thé cel under Jan, tater than 2, just before toning off the recorder. Stact with an empty workStiet and select the BI cell. Tum on the macro recorder and specify the macro name as MonthNames2. Enter the shortcut as uppercase M—the recorder won't let you use lowercase m again, Click OK and select the Use Relative References button on the Developer tab of the Ribbon. Type Jan and the other month names, as you did when recording idonthNames!. Select cells B1:G1 and click the Bold and Italic buttons on the ‘Home tab of the Ribbén. Make sure you select B1:G1 froga left to right, so that BI is the active cell. There is a small Kink in the recording process that can cause errors in the recorded macro if you select cells from right to left or “from bottom to top. Always select from the top left omer hen recording relatively, Ths has been a problem wih all versions of Excel VBA. Finally, select cell B2, the cell niet Jan, and turn off the recorder. Before running MonthNames2, select a starting cell, such as A10. You will find that the macro now types the month tiames across row 10, starting in column A, and finishes by selecting the cell under the starting cell. Before you record a miacro that selects cells, you need to think about whether to use absolute or relative reference recording. If you are selecting input cells for data entry, oF for a print area, you will probably want to record with absolute references, If you want to be able to nm your macro in different areas of your worksheet, you will probably want to record with relative references. If you are irying to reproduce the effect of the Cir}+arow keys to select the last cell in a column or row of data, you should record with relative references, You can even switch between relative and absolute reference recording in the middle of a macro, if you want. You might want to select the top of a column with an absolute reference, switch to relative eed PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 7 —————— TO OO Peers -VBA- Excel references, and use Ctrl+down arrow to get to the bottom of the column and an extra down arrow to go to the first empty cell, Excel 2000 was the first version of Excel to let you successfully record selecting a block of cells of variable height and width using the Ctrl key. Ifyou start at the top left-hand corner of 4 block of data, you can hold down the Shift and Cir] keys and press the down arrow and then the right arrow to select the whole block (as long as there are no gaps in the data). If you record these operations with relative referencing, you can use the macro to select a block of different dimensions, Previous versions of Excel recorded an absolute selection of the original block size, regardless of recording mode. - ae The Visual Basic Editor foe It is now time to see what has been going on behind the scéneé. If you want to understand macros, be able to modify your macros, and tap into the full ower of VBA, you need 0° know bow to use the Visual Basic Editor (VBE). The VBE runs in its own window, separate from the Excel window. You can activate it in many waysFirst, you can activate it by clicking the Visual Basic button on the Developer tab of the Ribbon. You can also activate it by holding down the Alt key and pressing the FI key. Alt+F11 acts as a togele, taking you between the Excel window and the VBE window. If you want to edit a specific macro, you can use the Macros button on the Developer tab of the Ribbon or the Play Macro bution on the left of the status bar to apen the Macro dialog box, solect the macro, click the Edit button. ‘The VBE window will look sometbing like Figure 1-5, " Facyeensih Setect Reegeeres te Jtis quite possible that you will see nothing but the mens bar when you switch to the VBE window. If you can't see the toolbars, use View®>Toolbars and click the Standard toolbar. PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 8 Peers -VBA- Excel Use Views? Project Explorer and View®Properties Window to show the windows on the lef If you can’t see the code module on the right, double-click the icon for Module in the Project Explorer window. Code Modules ‘All macros reside in code modules like the one on the right of the VBE window in Figure 1- 5. There are two types of code madules—standard modules and class modules. The one you sce on the right is a standard module. You can use class modules to create your own objects. ‘You won't need to know much about class modules until you are working at a very advanced level. Some class modules have already been set up for you. They are associated with each ‘worksheet in your workbook, and there is one for the entire workbook. You ean see them in the Project Explorer window, in the folder called Microsoft Excel Objects. You will find out more about them later in this chapter. You can add as many code modules to your workbook as you like. The macro recorder has inserted the one named Modulel. Each module can contain many macros. For a small application, you would probably keep all your macros in ‘one module. For larger projects, you can organize your cade better by filing wnrelated macros in separate modules. Procedures In VBA, macros are referred to as procedures. There are two types of procedures—sud procedures and function procedires. You will find out about function procedures in the next section. The macro recorder can only produce sub procedures. You can see the MonthNamesi sub procedure set-up by the recorder in Figure 1-5. Sub procedures start with the keyword ‘Sub, followed by the name of the procedure and opening and closing parentheses. The end of asub procedure is marked by the keywords End Sub. Although it is not mandatory. the code within the sub procedure is normally indented to make it stand out from the start and end of the procedure, so that the whole procedure is easier to read. Further indentation is normally used to distinguish sections of code such as If tests and looping structures. For example: Jf ActiveCell. Value = 10 Then ActiveCell.Font.Bold = True End If Any lines starting with a single quote are comment lines, which are ignored by VBA. They are added to provide documentation, which is a very important component of good programming practice. You can also add comments to the right of lines of code. For example: Range(“B1”) Select ‘Select the B1 cell At this stage, the code may not make perfect sense, but you should be able to make out roughly what is going on. If you Jook at the code in MonthNamest, you will see that cells are being selected and then the month names are assigned to the active cell formula. You can ‘edit some parts of the code, so if you had spelled a month name incorrectly, you could fix it; or you could identify and remove the line that sets the font to bold; or you can select and delete an entire macto. Notice the differences between MonthNames] and MonthNames?2. MonthNames! selects specific cells such as B1 and Cl. MonthNames? uses Offset to select a ———————— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page? Peers -VBA- Excel _ cell that is zero rows down and one column to the right from the active cell. Already, you are starting to get a feel for the VBA language. The Project Explorer ‘The Project Explorer is an essential navigation tool. In VBA, each workbook contains a* project. The Project Explorer displays all the open projects and the component parts of those projects, as you can see in Figure 1-6.You can use the Project Explorer to locate and activate the code modules in your project. You can doubleclick a module icon to open and activate that module, You can also insert and remove code modules in the Project Explorer. Right- click anywhere in the Project Explorer window, and ftom the gontext menu select Insert to add a new standard module, class module, or UserForm. 2 To remove Modulel, right-click it and choose Remove Module!" Note that you can’t do this ‘with the modules associated with workbook or worksheet objects.-You ean also export the code in a module to a separate text file, or import code from a text file. "YaaProject (Recorderoom) 55 trac Eee Ober 1) Shert2 heet2) sheets (Sheet) ‘Weta 5 Ey Modes bode Figure 1-6 The Properties Window "> ‘The Properties window shows you the properties that can be changed at design time for the currently active object in the Project Explorer window. For example, if you click Sheet! in the Project Explorer, the Sheet! properties are displayed in the Properties window, as shown in Figure 1-7. The Scrolldrea property has been set to /:D/0, to restrict users to that area of the worksheet. Figure 1-7 es PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 10 i | i i i | Peers -VBA- Excel You can get to the help screen associated with any property very easily. Just select the property, such as the Seral/Area property, which is selected in Figure 1-7, and press Fl. ‘Other Ways to Run Macros ‘You have seen how to run macros with shorteuts and how to run them from the Ribbon and status bar macro buttons. Neither method is particularly friendly. You need to be very familiar with your macros to be comfortable with these techniques. You can make your macros much more accessible by attaching them to buttons. Ifthe macro is worksheet-specific, and will only be used in a particular part of the worksheet, then itis suitable to use a button that has been embedded in the worksheet at the appropriate location. If you want to be able to use a macro in any workshect’or workbook and in any location in a worksheet, itis eppropriate to attach the macro to a button on the Quick Access Toolbar. ‘There are many other objects that you can attach macros to, including combo boxes, list boxes, scrollbars, checkboxes, and option buttons. These are all referred to as controls. You can also attach macros to graphic objects in the worksheet, such as shapes created with the Shapes button on the Insert tab of the Ribéon. Worksheet Buttons Excel 2007 has two differénf séis.of controls that can be embedded in worksheets. One set has been inherited from fhe Forms toolbar in previous versions, and the other has been inherited from the Control ToolBox toolbar in previous versious. The Forms toolbar appeared in Excel 5 and 95, The-Forms controls can be embedded in a worksheet and are also nsed with Excel 5 and 95 dialog sheets to create dialog boxes. Excel 97 introduced the newer ActiveX controls on the Control ToolBox toolbar. You can, embed ActiveX controls in a " worksheet or use them on UserFonms, in the VBE, to create dialog boxes. To create controls in Excel 2007, select the Developer tab on the Ribbon. In the Controls ‘group, click the Insest button to open the window shown in Figure 1-8. Form Contrals Age (ae al ActiveXContrets «BREN BcAm@e® Figure 1-8 For compatibility with the older versions of Excel, both seis of controls and techniques for creating dialog boxes are supported in Excel 97 and higher. If you have no need to maintain ‘backward compatibility with Excel 5 and 95, you can use just the ActiveX controls. Forms Controls ‘A good reason for using the Forms controls is that they are simpler to use than the ActiveX controls, because they do not have all the features of ActiveX controls, For example, Forms controls can only respond to a single, predefined event, which is usually the mouse-click eee PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 11, Peers ~VBA- Excel event, ActiveX controls can respond to many events, such as a mouse click, a double-click, or pressing a key on the keyboard. If you have no need of such features, you might prefer the simplicity of Forms controls. To create a Forms button in a worksheet, click the top-left button in the Controls dialog box, opened from the Insert button on the Developer tab of the Ribbon, ‘You can now draw the button in your worksheet by clicking where you want a comer of the ‘button to appear and dragging to where you want the diagonally opposite comer to appear. ‘The Assign Macro dialog box will appear as shown in Figure 1-9, and you can select the smacro to attach fo the button. ile Es i 3 a 3] coy Click OK to complete the assignment. You can then edit the text on the button to give a more meaningful indication of its fimction. After you click a worksheet cell, you can click the button to run the attached macro. If you need to edit the button and it is not already selected, tight-click it to select the control and display a context menu, If you don't want the context menu, hold down Ctrl and left-click or right-click the button to select it. (Don't drag the mouse while you hold down Ctl, or you will create a copy of the button.) If you want to align the button with the worksheet gridlines, hold down Alt as you draw it with the mouse, If you have already dravn the button, select it and hold dowm Alt as you drag any of the white boxes that appear on the comers and edges of the button. The edge or comer you drag will snap to the nearest gridline. ActiveX Controls:To create an ActiveX command button control, click the top-left button in the ActiveX Controls section of the Controls dialog box, opened from the Insert button on as PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 12 Peers -VBA- Excel the Developer tab of the Ribbon. When you draw your button in the worksheet, you enter into design mode. When you are in design mode, you can select a control with a left-click and edit =, g it, You must tum off design mode if you want the new control to respond to events. You can do this by clicking the Design Mode button on the Developer tab of the Ribbon so it is no longer highlighted. Figure 1-10 shows the Design Mode button as it appears when design mode is active, after the insertion of the ActiveX control, Recarleraim - Wezoeoh ste! len Bidarincrdeoe | ime et A eect | Sheet Sheet? sheets £2. ae Figure 1-10 ‘You are not prompted to assign a macro to the ActiveX command button, but you do need to vite a click-event procedure for the button, An event procedure is a sub procedure that is ‘executed when, for example, you click a button, To do this, make sure you are still in design ‘mode and double-click the command button to open the VBE window and display the code module behind the worksheet. The Sub and End Sub statement lines for your code will ave been inserted in the module, and,you can add in the code necessary to run the MonthNames2 ‘macro, as shown in Figure. krivave Sar Cemmandiucront_slack() Call MontiNanesé End Sab oo PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 13, ——————— ee TTT Peers -VBA- Excel. Figure 1-14 Torun this code, switch back to the worksheet, turn off design mode, and click the command button. Ifyou want to make changes to the command button, you need to return to gesign mode by clicking the Design Mode button. You cap then select the command button and change its size and position on the worksheet. You can also display its properties by right-clicking it and choosing Properties to display the window shown in Figure 1-12. Figure 1-12 ‘To change the text on the command button, change the Caption property. You can also set the font for the caption and the foreground and background colors. if you want the button to ‘work satisfactorily in Excel 97, jt'is a good idea to change the TakeFocusOnClick property from its default value of Tgyg.té False. If the button takes the focus when you click it, Excel 97 does not allow you to assign values to some properties, such as the NumberFormat property of the Range object. Quick Access Toolbar In versions of Excel prior to Excel 2007, you can attach macros to toolbar buttons. Because toolbars and memus have been replaced by the Ribbon in Excel 2007, this ability no longer ‘exists, with the exception of the Quick Access Toolbar. The Quick Access Toolbar sits either above or below the Ribbon, and you can add any button from the Ribbon to it to give you direct access to the button. When you right-click a Ribbon button, you can choose Add to —— L PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 14 Peers -VBA- Excel a, Quick Access Toolbar from the pop-up menu, The same pop-up menu offers a second choice, which is Customize Quick Access Toolbar. This choice opens the dialog box shown in Figure 113. Select Macros from the Choose commands from: drop-down menu. You can now assign ‘macros from open workbooks to the Quick Access Toolbar by selecting them and clicking the ‘Add button. The icon associated with the macro can be changed by clicking the Modify button, which provides a selection of icons and a text box where you can enter a quick tip for the button, Feouinsentsonaerest Feuneabmiverniome? i Event Procedures Event procedures are special macro procedures that cespond tg the events that occur in Excel Events include user actions, such as clicking the mouse on a button, and system actions, such as the recalculation of a worksheet. Versions of Excel since Excel 97 expose a wide range of events for which you can write code, ‘The click-event procedure for the ActiveX command button that ran the MonthNames2 ‘macro, which you have already seen, is a good example, You entered the code for this event procedure in the code module behind the worksheet where the command bution was embedded, All event procedures are contained in the class modules behind the workbook, worksheets, charts, and UserForms, You cam see the events that are available by activating a module, such as the ThisWorkbook module, choosing an object, such as Workbook, from the left drop-down list at the top of the ‘module, and then activating the right drop-down, as shown in Figure 1-14. The Workbook Open() event can be used to initialize the workbook when it is opened. The code could be as simple as activating a particular worksheet and selecting a range for data ~ input. The code could also be more sophisticated and construct new buttons in the Ribbon. For compatibility with Excel 5 and 95, you can still create a sub procedure called Auto_Open(, in a standard module, that runs when the workbook is opened, If you also have a Workbook Open( event procedure, the event procedure runs first. eee PEERS TECHNOLOGIES PVT I.TD., HYDERABAD Page 15, ———— ee. — OO Peers ~VBA- Excel ——— As you can see, there are many events to choose from. Some events, such as the BeforeSave and BefereClose events, allow cancellation of the event. The following event procedure stops the workbook from being closed until cel] A] in Sheet! contains the value True: Private Sub Workbook BeforeClose(Concel As Boolean} If ThisWorkbook Shests("Sheet!").Range("Al").Value <> True Then Concel = True End if End Sub ern nae eT 12 Mocotdsrxlsih . Thistvectbbaal {ud I fvorkuoaie i > saaUninstan prdyace Sub Wexkbook_cpeni) [ateremespon. [SheetMeferetoubeCicx, IsneeetoreRignicscs Figure 1-14 This code even prevents the closure of the Excel window. User-Defined Functions, Excel has hundreds of built-in worksheet functions that you can use in cell formulas, You can select an empty worksheet cell, select the Formulas tab of the Ribbon, and click one of the buttons in the Function Library chunk to see a list of functions. Among the most frequently used functions are SUM, IF, and VLOOKUP. If the function you need is not already in Excel, you can write your own user-defined function (or UDF) using VBA. ‘UDFs can reduce the complexity of a worksheet. It is possible to reduce a calculation that requires many cells of intermediate results down to a single function cal] in one cell. UDFs PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 16 Peers -VBA- Excel can also increase productivity when many users have to repeatedly use the same calculation procedures. You can set up a library of functions tailored to your organization. Creating a UDF Unlike manual operations, UDFs cannot be recorded—you have to write them from seratch using standard module in the VBE. If necessary, you con insert a standard module by right- clicking in the Project Explorer window and choosing Insert->Module. A simple example of a UDF is shown here: Function Fohrenheit(Centigrade) Fahrenheit = Centigrade * 9/5 + 32 End Function Here, a function called Fahrenheit() is created that converts degrees Centigrade to degrees Fahrenheit. In the worksheet, you could have column A containing depres Centigrade and columa B using the Fahrenheit() fonction to calculate the corresponding temperature in degrees Fabrenheit. You can see the formula in cell B2 by locking at the Formula bar in Figure 1-15. 3 URE: pn@eae Brae Phaetayoa — Fomias E | satvenhenaay Figure 1-15 ; ‘The formula has been copied into c¢lls-B3:B12. ‘The key difference between g.siib procedure and a function procedure is that a function procedure retums a value, Fahrenheit() calculates 2 numeric value, which is retumed to the worksheet cell where Fahrenheit() is used. A function procedure indicates the value to be retumed by setting its own name equal to the retum value. Function procedures normally have one or more input parameters. Fahrenheit has one input parameter called Centigrade, which is used to calculate the return value. When you enter the formula, Fahrenheit(42), the value in cel] A2 is passed to Fahrenkeit() tough Centigrade, In the case where the value of Centigrade is 0, Fahrenheit) sets its own name equal to the caleulated result, which is 32. The result is passed back to cell B2, as shown in Figure 1-15. The same process occurs in each cell that contains a reference to Fahrenheit). es, PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 17 eee TOOT Peers -VBA- Excel ‘A different example that shows how you can reduce the complexity of spreadsheet formulas for users is shown in Figure 1-16. The lookup table in cells A1:DS gives the price of each ‘product, the discount sales volume (above which a discount will be applied), and the percent discount for units above the discount volume. Using normal spreadsheet formulas, users ‘would have to set up three lookup formulas together with some logical tests to calculate the ‘invoice amount. 2 lPreduct” — Price Discount Volume Biscount [2 |Arates ost Mangoes so” 0K lovacees wn 3% 8 2 pas infers hopes | Laingces Figure -18 The Jnvoicedmorint i Volume is the number of units sold, and Table is the Tookop table. The formula in cell C9, in : Figure 1-16, defines the ranges to be used fot casi Function InvoiceAmount(Product, Volume, Table) “Find price in table Price = WorksheetFunction, Veaekup(Product Table, 2) ‘Find discount volume threshold. : DiscountVolume + WorksheetFunction. VLookup(Product, Table, 3) “Apply discount if volume above'fhreshold If Volume > DiscountVolume | ee “Calculate invoice with di DiscountPet = ‘WarksitstPuncton.VLookupProdct, Table, 4) InvoiceAmount = Price * DiscountVolume + Price * _ (1- DiscountPet) * (Volume - DiscountVolume) Else “Caleulate invoice without discount InvoiceAmount = Price * Volume EndIf End Function PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 18 Peers -VBA- Excel SSS ‘The range for the table is absolute so that the copies of the formula below cell C8 refer to the same range. ‘The first calculation in the function uses the VLookup function to find the product in the lookup table and reram the corresponding value from the second coluran of the lookup table, which it assigns to the variable Price. Ifyou want to use an Excel worksheet function in a VBA procedure, you need to tell VBA where to find it by preceding the function name with WorksheetFunction and a period. For compatibility with Excel 5 and 95, you can use Application instead of WorksheetFunction. Not all worksheet functions are available this way. In these caves, VBA has equivalent functions, or mathematical operators, lo earry out the same calculations, ‘Tn the next line of the function, the discount volume is found in the lookup table and assigned to the variable DiscountVolume. The, If test on the next line compares the sales volume in Volume with DiscountVolume. If Volume is greater than DiscountVolume, the calculations following it, down to the Else statement, are carried out. Otherwise, the calculation after the Elseis carried out. If Volume is greater thon DiscountVolume, the percent discount rate is found in the lookup table and assigned to the variable DiscountPet. The invoice amount is then calculated by applying the full price to the units up to DiscouniVolume plus the discounted price for units above DiscountVolume, Note the use of the underscore character, preceded by a blank space, to indicate the continuation of the code on the next line. ‘The result is assigned to the name of the function, InvoiceAmount, so that the value will be retumed to the worksheet cell. If Volume is hot greater than DiscountVolume, the invoice amount is calculated by applying the price to the units sold, and the result is assigned to the name of the function. Direct Reference to Ranges When you define a UDF, it is possible to directly refer to worksheet ranges rather than through the input parameters of the UDF. This is illustrated in the following version of the Jnvoicedmount () function: Fonction InvoiceAmount2(Product, Volume) ‘Create object variable referring to table in worksheet Set Table = This Workbook. Worksheets("Sheet2").Range(“A2:D5") ‘Find price in table Price = WorksheetFunetion, VEookup(Product, Table, 2) ‘Find discount volume threshold . DiscountVolume = WorksheetFunction. VLookup (Product, Table, 3) “Apply discount if volume above threshold If Volume > DiscountVolume Then ‘Calculate invoice with discount DiscountPct~ WorksheetFunction. VLookup(Product, Table, 4) InvoiceAmount2 = Price * DiscountVolume + Price *_ a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 19 ———— OO OOOO Peers -VBA- Excel (1- DiscountPet) * (Volume - DiscountVolume) Else. ‘Calculate invoice without discount TnvoiceAmount2 = Price * Volume End if End Function Note that Table is no longer an input parameter. Instead, the Set statement defines Table with a direct reference to the worksheet range. Although this method still works, the retumn value of the function will not be recalculated if you change a value in the lookup table, Excel does not realize that it needs to revalulate the function when a lookup fable value changes, because it does not see that the table is used by the function. £ Excel only recalculates a UDF when it sees its input parameters change. If you want to remove the lookup table from the function parameters and still have the UDF recalculate automatically, you can declare the function to be vail onthe fis line of the Fonction, as shown here: Function InvoiceAmount2(Product, Volume) Application. Volatile Set Table = This Workbook. Workshects("Sheet2”) Range(“A2:D5") However, you should be aware that this feature comes at a price. If a UDF is declared volatile, the UDF is recalculated every time any value changes in the worksheet. This can add 8 significant realoujaton burden tothe worksheet ifthe UDF i used in many cells. What UDF Céitmot D6” ‘A.common mistake ynacle by users ie in arent to create a worksheet function thar changes the structure of the wuths.. iple, copying a range of cells. Such attempts will fail. No error messages are provtuced becouse Excel simply ignores the offending code lines, so the reason for the failure is not obvious. UDFs, used in worksheet cells; are not permitted to change the structure of the worksheet, meaning that a UDF eannot return a value to any other cell than the one itis. used in, and it cannot ehange a physical characteristic of a cell, such as the font color or background pattern. In addition, UDFs cannot carry out actions such as copying or moving spreadsheet cells, They cannot vven carry out some actions that imply a change of cursor location, such as an Edit®¥ind. A UDF can eall another function procedure, or even a sub procedure, but that procedure will be under the same restrictions as the ‘ODE. It will still not be perguitted to change the structure of the worksheet. A distinction is made (in Excel VBA) between UDFs that are used in worksheet cells and fumetion procedures that ate not connected with worksheet cells. As long as the original calling procedure was not a UDF in a worksheet cell, a function procedure can carry out any Excel action, just like a sub procedure, Tt should also be noted that UDFs are not as efficient as the built-in Excel worksheet functions, If UDFs are used extensively in a workbook, recalculation time will be greater compared with a similar workbook using the same number of built-in functions. a PEERS TECENOLOGIES PVT LTD. HYDERABAD Page 20 th ae es 8, to te Peers -VBA- Excel The Excel Object Model ‘The Visual Basic for Applications programming language is common across all the Microsoft Office applications. In addition to Bxcel, you can use VBA in Word, Access, PowerPoint, and Outlook, Once you learn it, you can apply it to any of these. However, to work with an application, you need to leam about the objects it contains. In Word, you deal with documents, pacagraphs, and words. In Access, you deal with databases, recordset, and fields. In Excel, you deal with workbooks, worksheets, and ranges. Unlike many programming languages, you don’t have to create your own objects in Office VBA. Each application has a clearly defined set of objects that are arranged according to the elationships between them, This structure is referred to as the application's object model. ‘This setion is, an introduction to the Excel object model, which is fully documented in Appendix A. ?é Objects : First up, this section covers a few basics about Object-Oriented Programming (OOP). This ot a complete formal treatise on the subject, but it covers what you need to know to work with the objects in Excel. GOP's basic premise is that you can describe everything known to us as objects. You and I are objects, the world is an object, and the universe is an object. In Excel, a workbook is an object, a worksheet is an object, and a range is an object. These objects are only a small sample of around two hundred abject types available to us in Excel. Look at some examples of how to refer to Range,¢bjeclg jn VBA code, One simple way to refer to cells B2:Ca is as follows: Range(‘"B2:C4")"” Se Ifyou give the name Data toarange 2.72 ne name ina similar way: Range¢‘Data”) ‘There are also ways to refer to the currently active cell and selection using shortcuts. Jn Figure 1-17, ActiveCei! refers to'the B2 cell, and Selection refers to the range B2:E6. For Fennsie Oe — PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 21 Collections , Many objects belong to collections. A city block is a collection of high-rise buildings. A high-rise building is a collection of floor objects. A floor is a collection of room objects. Collections are objects themselves objects that contain other objects that are closely related, Collections and objects are often related in a hierarchical or tree structure. Excel is an object itself, called the Application object. In the Excel Application object, there is Workbooks collection that contains all the currently open Workbook objects. Eoch Workbook object has a Worksheets collection that contains the Worksheet objects in that workbook, gs Note that you need to make a clear distinction between the plural Worksheets object, which is a collection, and the singular Worksheet object. They are quite different objects. Te A If you want to refer to 2 member of 2 collection, you cai tefer to it By its position in the collection, as an index number starting with 1, or by its name, as quoted text. If you have opened just one workbook called Data.xls, you can refer to it by either of the following: ‘Workbooks(1) Workbooks(“Data.xis") If you have three worksheets in the active ‘workbook that have the names North, East, and South, in that order, you can réfes to thé second worksheet by either of the following: Worksheets(2) 3 ° ‘Worksheets("“East”) © If you want to refer tn» worksheet éalled Datalmput in a workbook called Sales.xls, and Sales.tt3 is iss wethbook, you must qualify the worksheet refesence with the ‘workbook reference. censrating them with a period, as follows: ‘Workbooks("‘Sales.xls"). Worksheets("Datalnput") ‘When you refer to the B2 cell in Dafalnput, while another workbook is active, you use: Workbooks("“Sales.xls”). Worksheets{“Datalnput") Range(“B2") The following section examines cbjeots more closely and explais bow you can manipulate them in VBA code. You need to be aware of two key characteristics of objects to do this. They ate the properties and meltiods asocinted with an object. Properties Properties are the physical characteristics of objects, and can be measured of quantified. You and Ihave a height property, an age property, a bank balance property, and a name property. Some of our properties can be changed fairly casily, such as our bank balance, Other properties are more difficult or impossible to change, such as our name and age. ‘A worksheet Range object has a RowHeight property and a ColumnWidth property. A Workbook object has 2 Name property, which contains its filename. Some properties can be rT PEERS TECHNOLOGIES PVT LTD, HYDERABAD . Page 22 Sap RES Peers -VBA- Excel ee ee changed easily, such as the Range object’s Column'idth property, by assigning the property a new value. Other properties, such as the Workbook object’s Name property, are read-only. ‘You can’t change the Name property by simply assigning a new value to it You refer to the property of an object by referring to the object, then the property, separated by a period. For example, to change the width of the column containing the active eell to 20 points, you ‘would assign the value to the Column Width property of the ActiveCell using: ActiveCell, Column Width = 20 To enter the name Florence into cell C10, you assign the namie to the Value property of the Range object: Pe ‘Range(“C10"). Value = “Florence” If the Range object is not in the active worksheet ini the aétive workbook, you need to be more specific: ‘Workbooks("Sales.xls"). Worksheets(“Datalnput")-Range(“C10"). Value = 10 In the previous examples, you have seen how to assign values to the properties of objects. ‘You can also assign the property values of objects to variables or to other objects” properties, ‘You can directly assign the column width of one cell to another cell on the active sheet, using: Range(“Ci”).ColumiWidth = Range(“A1") Column Width ‘You can assign the value in Cl i sheet to D10 in the sheet named Sales, in the active workbook, using" Workshects( Sales”) Range(“D10").Value = Range(“CI").Value ‘You can assign the value of a property to a variable so it can be wsed in later code. ‘This example stores the current value of cell M100, sets M100 to a new value, prints the auto- recalculated results, and sets M100 back to its original value: OpeningStock = Range("M100").Value Range(M100").Value = 100 ActiveSheet PrintOut Range("M100").Value ~ OpeningStock ‘Some properties are read-only, which means that you can’t assign a value to them directly. Sometimes there is an indirect way. One example is the Text property of a Range object. You can assign a value to a cell using its Valve property, and you can give the cell a number format using its NumberFormat property, , ‘The Text property of the cell gives you the formatted appearance of the cell, The following example displays $12,345.60 in a Message box: ‘VBA can do what is impossible to do manually. It can enter data into worksheets that are not visible on the screen. It can copy and move data without having to make the Sr ns PEERS TECHNOLOGIES PVT 1,TD., HYDERABAD Page 23 ——_—$——$—————L—LSLSLL———L——L Peers -VBA- Excel sheets involved active, Therefore, itis very seldom necessary to activate a specific ‘workbook, worksheet, or range to manipulate data using VBA. The more you can avoid activating objects, the faster your code will run. Unfortunately, the macro recorder can only record what you do and uses activation extensively. Range(“B10"), Value = 12345.6 Range(“B10"), NumberFormat = “$#,##0.00" ‘MsgBox Range(“B10").Text ‘This isthe onty means by which you can set the value of the Text property. Methods ‘Whereas propertics are the quantifiable characteristics of objects, methods are the actions that | can be performed by objects or on objects. If you have a linguistic bent, you might like to think of objects as nouns, properties as adjectives, and methods as verbs. Methods offen change the properties of objects, I have a walking method that takes me from A to B, changing my Jocation property. I have a spending method that reduces my bank balance property and a working method that increases my bank balance property. My dicting method reduces my weight property, temporarily. A simple example of an Excel method is the Select method of the Range object. To refer to a method, as with properties, put the object fist, add a period, and then add the method. The following selects cell G4: , Range("“G4") Select - Another example of an Excel method is the Copy method of the Range object. The following copies the contents of range A1:B3 to the clipboard: Range("A 1B2"}.Copy ‘Methods often have parameters that you can use to modify the way the method works, For example, you can use the Paste metipd of the Worksheet object to paste the contents of the clipboard into a worksheet, but if. you do not specify where the data is to be pasted, it is inserted with its top-left comer in the active cell. This can be overridden with the Destination parameter (parameters are discussed later in this section): ActiveSheet Paste Destination:=Range(“G4”) Note that the value of a paranteter is specified using :=, not just =. Often, Excel methods provide shortcuts. The previous examples of Copy and Paste can be carried out entirely by the Copy method: Range(“A1:B3”),Copy Destination:-Range("G4”) ‘This is far more efficient then the code produced by the macro recorder: Range(“AL:B3") Select te PEERS TECHNOLOGIES PV? LTD, HYDERABAD Page 24 ing Sor the is the be Peers ~VBA- Excel ES ‘Selection.Copy Range(“G4") Select ActiveSheet Paste Events Another important concept in VBA is that objects can respond to events. A mouse click on a ‘command button, 2 double-click on a cell, a recalculation of a worksheet, and the opening and closing of a workbook are examples of events. All of the ActiveX controls can respond to events. These controls can be embedded in worksheets and in UserForms to enhance the functionality of those objects. Worksheets and workbooks can also respond to a wide range of events, If you want an object to respond to an event, enter VBA code into the appropriate event procedure, for that object. The event procedure resides in the code module behind the Workbook, Worksheet, or UserForm object concerned. : “Ey For example, you might want to detect that a user has selected a new cell and highlight the cell's complete row and column, You can do this by entering code in the Worksheet SelectionChange() event procedure: 4, First activate the VBE window and double-click the worksheet in the Project Explorer : 2, From the drop-doym lists at the top of the worksheet code module, choose Worksheet and SelectionChange, and enter the following code: Private Sub Worksheet :SelectionChange(ByVal Target As Range) Rows Interior. ColorIndex = xiColorindexNone “Tanget.Ent'sc¢ ‘Target EntireRow amtetius roswisuidex = 36 End Sub This event procedure runs everytime the user selects a new cell, or block of cells. The parameter, Target, refers to the selected range as a Range object. The fist statement sets the ColorIndex property of all the* worksheets cells to no color, to remove any existing background color. The second and'third statements set the entire columns and entire rows that intersect with the selected cells to'a background color of pale yellow. This color can be different, depending on the color palette set up in your workbook. ‘The use of properties in this example is more complex than you have seen before. Now analyze the component parts, If you assume that Target is a Range object referring to cell BIO, then the following code uses the EnfireColumn property of the B10 Range object to refer to the entire B column, which is the range B1:B1048576, or B:B for short: ‘Target. EntireColumn Interior ColorIndex = 36 Similarly, the next line of code changes the color of row 10, which is the range A10:XFD10, oF 10:10 for short: ‘Target EntireRow Interior-ColorIndex = 36 er PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 25 Peers -VBA- Excel ‘The Interior property of a Range object refers to an Interior object, which is the background of a range. Finally, set the Colorindex property of the Interior object equal to the index umber for the required color. This code might appear to many to be far from intuitive. So how do you go about figuring out how to carry outa task involving an Excel object? Getting Help ‘The easiest way to discover the required code to perform an operation is to use the macro recorder. The recorded code is likely to be inefficient, but it will indicate the objects required and the properties and methods involved, If you tum on the recorder ta find out how to color the background ofa cll, you will get someting ike the folowing With Selection Interior Pattern = xiSolid PattemColorIndex = 56 Color = 65535, -TintAndShade = -PatternTintAndShade = 0 End With ‘This With..End With construction is discussed in more detail ister in this chapter. It is equivalent to: ‘The fines of code that specify Pattern, TintAndShade, and PatternTintAndShade are unnecessary, because they specify default values, The macro recorder is not sophisticated ‘enough to know what the user does or doesn’t want, so it includes everything. However, the recorded code provides the clues you need to get started. You only need to figure out how to change the Range object, Selection, into a complete row or complete column. If this can be done, it will be accomplished by using a property or method of the Range object. The Object Browser i ‘The Object Browser is a valuable-tool for discovering the properties, methods, and events applicable to Exes] objects. Todeplay the Object Browser, you need to be in the VBE window. You can use View" Object Browser, press F2, or click the Object Browser button on the Standard toolbar to see the window shown in Figure 1-]8.The objects are listed in the ‘window with the ttle Classes. Objects ate instances of classes. You can click inthis window and type an r to get quickly to the Range abject. Alternatively, you can click in the search box, second fiom the top with the binoculars to its right, and type in range. When you press Enter or click the binoculars, you will see a list of items containing this text. When you click Range, under the Class heading in the Search Results window, Range wil be highlighted in the Classes window below. This technique is hhandy when you ae searching for information on a specific property, method, or event. ey PEERS TECHNOLOGIES FVT LTD. HYDERABAD Page 26 ( i ! is Fetes Peers -VBA- Excel ember 2) AlonEaiRanges rEiTeROW Ferre Property EntireCotunn As Rone pars s Heme of Brea) Bens Figure 1-78 You now have a list of all the properties, methods, and events (if applicable) for this abject, sorted alphabetically. If you right-click this list, you can choose Group Members to separate the properties, methods, and events, which makes it easier to read. If yon scan through this list, you will see the EntireColumn and EntireRow properties, which look to be likely candidates for your ‘requirements. To confirm this, select EntireColurin and click the question mark icon at the top of the Object Browser window to go to the window in Figure 1-19 Fig Colin #ropercy Fett [Seveomcrcmsetnce | Sutras [srccanepimatnstomen | Rng taticohme hopety r “evn otearoet sium teevecana ben taerniecetdiee kee, 1 Stan homeo tae | manatee | oe Ce Figure 1-19 — PEERS TECHNOLOGIES PVT LTD, HYDERABAD . Page 27 Peers ~VBA- Excel ‘See Also can often Jead to further information on related objects and methods. Now, all that remains to do is connect the properties you found and apply them to the right object, Experimenting in the Immediate Window I you want to experiment wilh code, you can use the VBE's Immediate window. Use View immediate Window, press Ctrl+G, or click the Immediate Window button on the Debug. ‘toolbar to make the Immediate window visible. You can tile the Excel window and the VBE. window so you can type commands jnto the Immediate window and see the effects in the Excel window, as shown in Figure 1-20. A Figure 1-20 ‘When command is typed in and Enter is pressed, the command is immediately executed. To execute the same command again, click anywhere in the line with the command and press Enter again. Here, the Value property of the Aq ‘want to display a value, you pr Print: ‘PRange("B2").Value This code has printed Sales on the next line of the Immediate window. The last command has copied the value in B2 to 12. The VBA Language In this section, you see the elements of the VBA language that are common to all versions of Visual Basic and the Microsoft Office applications. The section uses examples that employ the Excel object model, but the aim is to examine the common structures of the language. Cell object has been assigned the text “Sales”. If you fe the code with a question mark, which is a shorteut for ee PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 28 tia ch I that View ‘cbug VBE a the 1. To press “you wt for and as of ‘ploy lage. ye28 ° Peers -VBA- Excel ——— Many of these structures and concepts are common to other programming languages, although the syntax and keywords can vary. This section examines the following: Storing information in variables and arrays Decision-making in code Using loops Q Basic error-handling Basic Input and Output First, look at some simple communication techniques you can use lo make your macros more flexible and useful. If you want to display a message, use the MsgBox function, which is useful if you want to display a warning message or ask a simple question. Im the first example, you want to make sure that the printer is switched on before a print operation, The following code generates the dialog box in Figure 1-21, giving the user a chance to check the printer, The macro pauses until the OX button is clicked: - ‘MsgBox “Please make sure that the printer is switehed on” Raita eB] Plgase make: cure that lie printer i= switched on "2 experiment, you can ise the Immediate window to execute single lines of code, . Altemstively, you can insert your code into a standard module in the VBE window. In this ease, you need to include Sub and End Sub lines as follows: Sub Test() MsgBox “Please make sure that the printer is switched on” End Sub ‘An easy way to execute a sub procedure is to click somewhere in the code to create an insertion point, then press F5. Box bs may options tat ‘control the types of buttons and icons that appear in the dialog " If you want to get help with this, or any VBA word, just click somewhere in the word and press the F1 key. The Help screen for the word will immediately appear. Among other details, you will ee the input parameters accepted by the function: MsgBox(prompt{, buttons] [, ttle] [, helpfile, context]) Parameters in square brackets are optional, so only the prompt message is required. If you Want to have a ttle atthe top of the dialog box, you can specify the third parameter. There are two ways to specify parameter values: by position and by name. a ge PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 29 Peers -VBA- Excel a OEE Parameters Specified by Position If you specify a parameter by position, you need to make sure that the parameters are entered in the correct order. You also need to include extra commas for missing parameters. The following code provides a title for the dialog box, specifying the title by position and producing the result shown in Figure 1-22: MsgBox “Is the printer on?” Figure 1-22 Parameters Specified by Name There ace come advantages and some special consdertions required when specifying potameters by name: © Youcan enter them in any order and donat need to include extra commas with nothing between them fo allow for undefined parameters 1 You do need to use t= rather. than tween the parameter name and the value, as ¢ ‘The following code generates the sanié dialog box as in Figure 1-22: MsgBox Title:="Caution!”, Prompt: Another advantage of specifying parameters by name is thatthe code is better documented. “Anyone reading the code is more fikely to understand it, J you want more information on the bultons parameter, you wil find a table of options inthe fielp soreen as follows: Constant Value Description ‘vbOKOnly, 0 ‘Display OK button only vbOKCancel i "Display OK and Cancel buttons ‘vbAbortRetrylgnore 2 Display Abort, Retry, and Ignore buttons vbYesNoCancel 37" Display Yes, No, and Cancel buttons ‘vbYesNo 4 Display Yes and No buttons ‘vbRetryCancel 5 Display Retry and Cancel buttons vbCaitical 16 Display Critical Message icon | [voQuestion. 32 Display Warning Query icon _| | voExclamation 48 Display Waming Message icon vyoinformation a Display Information Message toon ‘voDelaultBiutton! 0 First button is default rc PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 30 — - Peers -VBA- Excel a ES = ‘yeDetaoltButton?2 256 _——~Second button is default ° vbDefaultButton’ 512 ‘Third button is default a YoDefsulButtond —_—“768_——~Fourth button is default . ‘Application modal; the user must respond to the message od 0 : enh vbApplicationModal box before continuing work in the current application. ‘System modal; all applications are suspended until the ‘vbSystemModal 4096 ser responds to the message box VWMsgBoxHlelpButton 16384 Adds Help button to the message box ‘voMsgBoxSet Specifies the message box window as the foreground 65536“ na Foreground window : ‘voMsgBoxRight 524288 Text is right-aligned Specifies text should appear as right-to-left reading on veMspBorRilResding 1048576 re and Arabi systems Values 0 to 5 control the buttons that appear. Avalue of 4 gives Yes and No buttons, as shown in Figure 1-23: "8 MsgBox Prompt:="Delete this record?”, Buttons:=4 ; “Microgont Diatethis record? as > values 16 to 64 control the icons that appear; 32 gives a question mark icon. If you want both value 4 and value 32, add them to see the dialog box in Figure 1-24: a MsgBox Prompt:="Delete this record?”, Buttons: . be > + Figure 1-24 ™ am Constants | Specifying a Butions value of 36 ensures that your code is indecipherable to all but the most baitle hardened programmer. This is why VBA provides the constants shown to the left of the + button values in the help screen, Rather than specifying Butions by aumerie value, you can 4 ‘use the constants, which provide a better indication of the choice behind the value. The 4 following code generates the same dialog box as the previous example: a : —_—________ 5 t PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 31 Peers -VBA- Excel ——S————————————————— ee MsgBox Prompt:="Delete this record?”, Buttons-vbYesNo + vbQuestion, ‘The VBE helps you as you type by providing a pop-up list of the appropriate constants after you type Buttons, Point to the first constant and press the plus key (#), and you will be prompted for the second constant. Choose the second and press the spacebar or Tab to finish the line. If there is another parameter to be specified, enter a comma rather than a space or a Tab. Constants are a special type of variable thabdo not change, if that makes sense, They are used to hold key data and, as you have seen, provide a way to write more understandable code. ‘VBA has many buil® in constants that are referred to as intrnsic-consiants. You can also define your own constants, as you will see later in this chapter, Retum Values ‘There is something missing from the previous examples of AfygBox. You are asking @ question, but failing to capture the user's response to the question. That is because you have been treating MsgBox as a statement, rether than a function. This is perfectly legal, but you need to know some rules if you are to avoid syntax errors. You can capture the return value of the MsgBox function by assigning it to a variable, However, if you try the following, you will get-a syntax error: elete this'record?”, Buttons:=vbYesNo + vbQuestion 4 4 E: Expecte End: 'Statériént, is not really very helpful. You can click the Help button on thé exror'thessage to get a more detailed description of the error, but even then ‘you might not understand the explanation. Parentheses The problem with the previous line of code is that there are o parentheses around the function arguments. It should read as follows: Answer = MsgBox(Prompt:="Delete this record?”, Buttons:=vbY esNo + vbQuestion) ' ‘The general rule is that if you want to capture the return value of a function, you need to put any arguments in parentheses. If you don’t want to use the return value, you should not use parentheses, as with the original oe les of using MsgBox. The parentheses rule also appligs to methods used with objects. Many methods have return ‘values that you can ignoresor-Eapture. See the section on object variables later in this chapter for an example. Now that you have captured the return value of MsgBox, how do you interpret it? Once again, the help screen provides the required information in the form of the following table of return values: Constant Value Description voOK I OK eee — n nwnmkkke—eeeeeeeeoeee PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 32 : ats ou or na gre ve he oo Peers -VBA- Excel aS vbCancel 2 Cancel vbAbort 3 Abort vbRelty 4 Rety vblgnore 3 Ignore voYes 6 Yes vbNo 7 No If the Yes button is clicked, MsgBox retums a value of 6. You can use the constant vbYes, instead of the numeric value, in an If test: Answer = MsgBox(Prompt:="Delete selected Row?”, Buttor If Answer = vbYes Then ActiveCell_EntireRow.Deleto InputBox Another useful VBA function is JnputBox, which allows you to get input data from a user in the form of text. The following code generates the dialog box shown in Figure 1-25; UserName = InputBox(Prompt:="Please enter your name”) wae Figure 1-25 InpuiBox retums a text (string) ‘eau, Even if a numeric value is entered, the result is retumed as text. If you click Cancel or OK. without typing anything into the text box, Jnpu(Bax returns a zero- length string. It is a good idea to-tést the result before proceeding so this situation can be handled. In the following example; the sub procedure does nothing if Cancel is clicked. The Exit Sub statement stops the procedure at that point, Otherwise, it places the entered data into cell B2: Sub GetData() Sales = lpr Se) If Sales =" Then Exit Sub Range(“B2”). Value = Sales End Sub In this code, the If test compares Sales with a zero-length string. There is nothing between the two double quote characters. Don’t be tempted to put a blank space between the quotes. eed PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 33 Peers -VBA- Excel There is a more powerful version of InputBox that is a method of the Excel Application object It has the ability to restrict the type of data that you can enter. Itis covered in Chapter 2 Calling Functions and Sub Procedures ‘When you develop an application, you should not attempt to place all your code in one large procedure. You should write small procedures that carry out specific tasks, and test each procedure independently, You can then write a master procedure that runs your task ‘procedures, This approach makes the testing and debugging of the application much simpler, and also makes it easier to modify the application later. The following code illustrates this modular approach, although ih & pygctical application your procedures would have many mort lines of code: 2 g Sub Master() SalesData = Getlaput(“Enter Sales Data”) If SalesData = False Then Exit Sub Postlaput SalesData, “B3” End Sub Function GetInput(Message) Data = InputBox(Message) False Else GetInput = Data ‘Master uses the Getinput function and the Postinpu sub procedure. Geilnput has one input parameter, which passes the prompt message for the JnputBox function and tests for a zero- length string in the response. A value of False is retuned if this is found, Otherwise, Getinput returns the response. Master tests the ceturn value from, Getinput and exits if it is False, Otherwise, Master calls Postinput, passing two values that define the data to be posted and the cell the data is to be posted to. - Note that sub procedures can accept input parameters, just like function procedures, if they are called from another procedure, You can't run a sub procedure with input parameters directly. ‘Also note that, when callinig PostInput and passing two parameters to it, Master does not lace parentheses around the parameters. Because sub procedures do not generate a return value, ‘you should not put parentheses around the arguments when one is called, except when using the Call statement that is discussed next. ‘When calling your own functions and subs, you can specify parameters by name, just as you can with built-in procedures, The following version of Master uses this technique: ‘Sub Master) a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 34 ation ipter ange each task pler, your put 0- ise, alls off vut see ue, ou Peers ~VBA- Excel ES SalesData = GetInput(Message:~Enter Sales Data”) If SalesData ~ Palse Then Exit Sub Postinput Target:="B3", InputData:=SalesData End Sub The Call Statement “When running a sub procedure from another procedure, you can use the Call statement. There is no particular benefit in doing this; it is just an alternative to the previous method, Master can be modified as follows: Sub Master) SalesData = Gellnput("Enter Sales Data”) If SalesData = False Then Exit Sub Call Postinput(SalesDeta, “B3") End Sub Note that if you use Call, you must put parentheses around the parameters passed to the called procedure, regardless of the fact that there is no return value from the procedure. You can also use Call with a function, but only if the return value is not used. Parentheses and Argument Lists ‘As you have seen, the use of parentheses around arguments when calling procedures is a bit ofa minefield, so the following sections summarize when to use therm, at the risk of opening can of worms and getting lost in mixed metophors. Bear in mind that the same rules apply to argument lists of methods. Without the Call Statement Only place parentheses around the arguments when you are calling a function procedure and are also making use of the retum value from the function procedure: SalesData ~ GetInput(“Enter Sales Data”) Don't place parentheses around the arguments when you are calling a function procedure end are not making use of the retum value from the function procedure: Gotinput “Enter Sales Data” Don’t place parentheses around the arguments when you are calling a sub procedure: Postinput SalesData, “B3” An Important Subtlety Regarding Parentheses The following is correct syntax and leads to untold confusion: ‘MsgBox (“Insert Disk”) ———— PEERS TECHNOLOGIES PVT LTD:, HYDERABAD Page 38 Peers -VBA- Excel eS | It is not what it appears and itis not e negation of the parentheses rules. VBA. has inserted a space between MsgBox and the left pacenthesis, which it does not insert inthe following: Response = MsgBox(“Insert Disk") ‘The extra space indicates that the parentheses are around the argument, not around the argument lst. Tf you pass two input parameters, the following is not valid syntox: ‘MsgBox (“Insert Disk”, vbExclamation) ‘The following is valid syntax: é f MsgBox (“Insert Disk"), (vb2ixelamation) e tis fine to place parentheses around individual arguments, but not around ‘the argument list. However, you might not get the result you expect. Apologies if you are bored, but this is important stuff. It is more intportant when you get to refer to objects in parameter lists. Placing an object reference in parentheses causes VBA to convert the object reference to the object's default property. For example, (Range("B1")) is converted to the value in the B} cell and is not a reference to a Range object. The following is aid syntax to copy AL ip B: Range(“A1").Copy nang) The following ald sya but caused a run-time enror Range(“Al”).Copy (Range(“B1”)) With the Call Statement Hf you use the Call statement, you ‘must place parentheses around the arguments you pass to ‘the called procedure: be Call PostInput(SalesData, “B3”) Because Call is of limited use, ngt being able to process a return value, and muddies the water with its own rule, itis preferable not to use it Variable Declaration“ ~ You have Seen many examples of the use of variables for storing information. It is now time to discuss the rules for creating variable names, look at different types of variables, and talk about the best way to define variables. ‘Variable names can be constructed froma letters and numbers and the underscore character. The name must start with a letter and can be up to 255 characters in length. It isa good idea to avoid using any special characters in variable names. To be on the safe side, you should only use the letters of the alphabet (upper- and lowercase), rs PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 36 Peers -VBA- Excel plus the numbers 0-9 and the underscore (_). Also, variable names can’t be the same as VBA keywords, such as Sub and End, or VBA function names. So far you have been creating vatiables simply by using them. This is referred to as implicit variable declaration. Most computer languages require you to employ explicit veriable declaration, This means that you must define the names of all the variables you are going to use before using them in code, VBA allows both types of declarations. If you want to declare a variable explicitly, do so using a Din: statement or one of its variations, which is discussed shortly. The following Dim statement declares a variable called SalesData: Sub GetDataQ Dim SalesData > SalesData = InputBox(Prompt:="Enter Target Sales”) Most users find implicit declaration easier than explicit declaration, but there are many \dvantages to being explicit, One advantage is the preservation of capitalization, More important advantages are discussed later in this chapter. ‘You might have noticed that if you enter VBA words, such as inputbox, in lowercase, they are automatically converted to VBA’s standard capitalization when you move to the next line. This is a valuable form of feedback that tells you the word has becn recognized as valid VBA code. It is a eed jidea to always type VBA words in lowercase and laok for the changei ; 5 : If you do not illy declare ‘a variable name, you can get odd effects regarding its capitalization. Say you “write the ‘olleing c code: Sub GetData() SalesData = InputBox(Prompt:="Enter Target Sales”) If salesdata="” Then ‘You will find that when you press Enter at the end of line 3, the original occurrence of SalesData loses its capitalization and the procedure reads as follows: Sub GetDataQ) salesdata = InputBox(Prompt:~"Enter Target Sales”) If salesdata="” Then Exit Sub Jn fact, any time you edit the piocedure and alter the capitalization of salesdata, the new version will be applied throfighout the procedure. If you declare SalesData in a Dim statement, the capitalization you use on that line will prevail throughout the procedure. You can now type the variable name in lowercase in the body of the code and obtain confirmation that ithas been correctly spelled as you move to a new line. Option Explicit There is a way to force explicit declaration in VBA. Place the statement Option Explici the declarations section of your module, which is atthe very top of your madule, before any procedures, as shown in Figure 1-26. et PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 37 Peers -VBA- Excel range ("51") Value = Ena 520 Figure 1-26 a, & Option Explicit only applies to the module it appears in. Each iodule requiring explicit declaration of variables must repeat the statement in its fect i ‘When you ty to compile your module or run a procedure using explicit variable declaration, ‘VBA will check for variables that have not been declared, highlight them, and show an error message. This has an enormous benefit, It picks up spelling mistakes, which are among the most common errors in programming. Consider the following version of GeDaa, where thee no Option Explicit al he top ofthe modvle and, therefore, implicit declaration js used: a is e Sub GetData() SalesDati : IfSaleData =" Then Exit Sub Range("B2"):Value = SalesData End Sub This code will never enter anydata info cell B2. VBA happily accepts the misspelled SaleDota in the If test as a new variable that is empty, and thus is considered to be a zero- length string for the purposes of the test. Consequently, the Exit Sub is always executed and the final line is never executed. This type of exter, especially when embedded in a longer section of code, can be very difficult to see, If you inchide Option Explicit in your declarations section, and Dim SalesData at the beginning of GetData, you will get an error message, Variable not defined, immediately after ‘you attempt to run GetData, The uridefined variable will be highlighted so that you can see exactly where the error is. ‘You can have Option Explicit automatically added to any new modules you create. In the ‘VBE, use Toots Options and click the Editor tab. Check the box against Require Variable Declaration. This is a highly recommended option. Note that settting this option will not affect any existing modules, where you will need to insert Option Explicit manually. Scope and Lifetime of Variables ‘There are two important concopts associated with variables: ‘PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 38 Peers -VBA- Excel Q_ The scope of a variable defines which procedures can use that variable Q The lifetime of a variable defines how long that variable retains the values assigned to it ‘The following procedure illustrates the lifetime of a variable: Sub LifeTimeQ Dim Sales Sales = Sales +1 MsgBox Sales End Sub Every time LifeTime is nun, it displays 0 value of one. This is becdiige the variable Sales is only retained in memory until the end of the procedure. The memory Sales uses is released when the End Sub is reached, Next time LifeTime is run, Sales is re-created and treated as having a 0 value. The lifetime of Sales is the time taken to nun the procedure, You can increase the lifetime of Sales by declaring it in a Statie statement: Sub LifeTimeQ) Statie Sales Sales = Sales +1 MsgBox Sales End Sub ‘The lifetime of Sales is now extended to the time that the workbook is open. The more times LifeTime is run, the highér the value of Sales will become. ‘The following two procedures illustrate the scope of a variable: Sub Scopel() Static Sales Sales = Sales +1 ‘MsgBox Sales End Sub Sub Scope20 Static Sales Sales = Sales + 10 MsgBox Sales End Sub The variable Sales in Scope! js not the samo variable as the Sales in Scope2. Each time Scopel is executed, the valué'of its Sales will increase by one, independently of the value of Sales in Scope2. Similarly, the Sales in Scope? will increase by 10 with each execution of Scope2, independently of the value of Sales in Scopel. Any voriable declared within a procedure has a scope that is confined to that procedure. A variable that is declared within a procedure is referred to as a procedure-level variable. Variables can also be declared in the declarations section at the top of a module, as shown in the following version of the code: Option Explicit oo PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 39 Peers -VBA- Excel eee Dim Sales Sub Scopel Sales = Sales +1 MsgBox Sales End Sub Sub Scope2 Sales = Sales + 10 ‘MsgBox Sales End Sub Scopel and Scope? are now processing the same variable, Sales. AVariable declared in the declarations section of a module is referred to as a module-level variable, and its scope is now the whole module, Therefore, itis visible to all the procedures in the module, Its lifetime is now the time that the workbook is open. If.a procedure in the module declares a variable with the same name as a module-level variable, the medule-Jevel variable will no longer be visible to that procedure. It will process its own procedure-level variable. Module-level variables, declared in the declarations section of the module with a Dim statement, arc not'visible to other modules. If you want to share a variable between modules, you need to declare it as Public in the declarations section: Public Sales 3 Public vatiables can algo be ‘iade, visible 49 otter workbooks, or VBA Projegts. To accomplish this, a reference to the workbook containing the Public variable is created in the other workbook; using Tools "References in the VBE. Variable Type Computers store different types of data in different ways. The way a number is stored is quite different from the way text, or a character string, is stored. Differeni categories of numbers are also stored in different ways, An integer (a whole number with no decimals) is stored differently from a number with decimals. Most computer languages requite that you declare the type of data to be stored in ayariable. VBA does not require this, but your code will be more efficient if you do declare variable types. It is also more likely that you will discover any problems that arise when data is converted from one type to another, if you have declared your variable types. ‘The following table has been taker directly ftom the VBA Help fies. It defines the various data types available in VBA and their memory requirements. It also shows you the range of values that each type cati handle: Data type Storage size Range Byte Tbyte 010255 Boolean 2 bytes True of False Integer bytes ~32,768 to 32,767 Long Abytes -2,147,483,648 to 2,147,483,647 (long integer) A a ————————— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 40 the ais ime ible Dim les, To 28 ed we be ed of Peers -VBA- Excel a ~3.402823E38 to -1.401298E-45 for negative values; (Gingle-precision 4 bytes 1.401298E-45 fo 3,402823E38 for positive values. oating-point) Single -1.797693 134862316308 to -4.94065645841247E-324 Double i Ines (double-precision 8 bytes ‘or negative values; Gowler 4.94065645841247H-324 to 1,79769313486232E308 for oating point) positive values Currency 8 -922,337,203,685,477.5808 to 922,337,203,685,477.5 (ealentogen 89 922,337,203,685,477.5808 to 922,337,2 807 17-79,228 162,514,264 337,593,543,950,335 with no Decimal LA dytes desi point 1792281 62514264537593543950335 sim with 28 places to the right ofthe decimal; the smallest ‘non- nuraber is #/-0.0000000000000000000000000001 Date Bbyies January 1, 10010 December 31, 9999 Object Gbytes ___ Any Object reference String 10 bytes = -" (rarableength) — stingiengan 012 3 moximately billion characters String Length of ‘ (iced tengt) sting 1 to approximately 65,400 characters ‘Variant . . {withmonbars)_eit6bMES Any numetie vale upto the range of a Double Variant 22 Bytes + ; ; Si (vida) —_singtengin St Hs or vrisble og Sing User-defined nha! by _ Therange of each elements the same asthe range « (using Type) Clemens” ot Re Ifyou do not declare a variable's type, it defaults to the Variant type. Variants take up more memory than any other type because each Variant has to carry information with it that tells ‘VBA what type of data it is currently storing, as well as store the data itself. Varianis use more computer overhead when they are processed, VBA has to figure out what types itis dealing with and whether it needs to convert between types in order to process the number. If maximum processing speed is required for your application, you should declare ‘yout variable types, taking advantage of those types that use less memory when you can. For ‘example, if you know your aumnbers will be whole numbers in the range of -32000 to +32000, ‘you would use an integer type. Declaring Variable Type ‘You can declare a variable’s type on a Dim statement, or related declaration statements such as Public. ‘The following declares Sales to be a double precision floating-point number: ‘Dim Sales As Double ——— PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 41, Peers -VBA- Excel You can declare more than one variable on a Dim: Dim SalesData As Double, Index As Integer, SiartDate As Date ‘The following can be a trap: Dim Col, Row, Sheet As Integer Many users assume that this declares each variable to be Integer. This is not true. Cof and Row are Variant beeanse they have not been given type. Ta declare all three as Integer, the line should be as follows: Zé Dim Col As Integer, Row As Integer, Sheet As Integer Declaring Function and Parameter Types If you have input parameters for sub procedures or function procedures, you can define each parameter type in the first line of the procedure as follows: Function IsHoliday(WhichDay As Date) Sub Marine(CrewSize As integer, FuelCapacity As Double) You can also declare the:séturn: value jype for a function. The following example is for a function that returns a value of Trg, Function Tedtoligay(Whighpey As Date) As Boolean Constants ‘You have seen that many intrinsictconstants are built into VRA, such as vb¥es and vbNo, discussed previously. ‘You can also define your own ciiistants. Constants are handy for holding numbers or pieces of text that do not change while your code is running, but that you want to use repeatedly in calculations and messages. Constants are declared using the Const keyword, as follows: Const Pi = 3.14159265358979 iy 5 ‘You can include the constants oe the declaration: Const Version As Sting = Reigase 3.99" Constants follow the same rules regarding scope as variables. If you declare a constant within a procedure, it will be local to that procedure. If you declare it in the declarations section of a module, it will be available to all procedures in the module. If you want to make it available to all modules, you can declare it to be Public as follows: Public Const Error666 As String = “You can’t de that” Variable Naming Conventions ——— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 42, = re Peers ~VBA- Excel You can call your variables and user-defined functions anything you want, except where there is a clash with VBA keywords and function names, However, many programmers adopt a systom whereby the variable or abject type is included, in abbreviated form, in the variable name, usually as a prefix, so instead of declaring: Dim SalesData As Double ‘you can use: Dim dSalesData As Double Wherever dSalesData appears in your code, you will be roi thatthe variable i of ype Double, Altewatively, you could use this lie of code: Dim dblSalesData As Double For the sake of simplicity, this approach has not been used so far in this chapter, but from here onward, the examples will use a system to create variable names. This is the convention used in this book: GQ. One-letter prefixes for the common data types: DimiColumn As Integer DimIRow AsLong = Dim dProduct As Double Dim sName As String = DimwValue As Variant Dim bChoice As Boolean Q Two or three-letter prefixes for object types: Dim objExcel As Object Dim mgData As Range Dim wkbSales As Workbook In addition to these characters, a lowercase @ will be inserted in front of array variables, which are discussed later in this chapter. Ifthe variable is a module-level variable, it will also have a lowercase m placed in front of it If it is a public variable, it will have a lowercase g (for global) placed in front of it. For example, maikffect would be a module-evel array variable containing long integer values Object Variables The variables you have seen so far have held data such as numbers and text. You can also create object variables to refer to objects such as worksheets and ranges. The Set statement is used to assign an object reference to an object variable. Object variables should also be declared and assigned a type as with normal variables. If you don’t know the type, you can use the generic term Object as the type: ed PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 43 Dim obj Workbook As Object Set obj Workbook = ThisWorkbook MsgBox objWorkbook Name It is more efficient to use the specific object type if you can, The following code creates an object variable rng, referring to cell B10 in Sheet], in the same workbook as the code, It then assigns values to the object and the cell above: Sub ObjectVariable() Dim mg As Range Set mg = ThisWorkbook, Worksheets(“Shect!”).Range(“C10”) mg Value = InputBox(“Enter Sales for January”) mg. Offset(-1, 0). Value = “January Sales” End Sub If you are going to refer to the same object more than onee, it is more efficient to create an object variable than to keep repeating a lengthy specification of the abject, It also makes code easier to read and write. Object variables can also be very useful for capturing the retum values of some methods, particularly when you are creating new instances of an object. For example, with either the Workbooks object or the Worksheets object, the Add method returns a reference to the new abject. This reference can be assigned to an object Variable so that you can easily refer to the xnew object in later code: Sub NewWorkbook().,.§ 2 : Dim wkb As Workbook, wks As Worksheet Set wkb= Workbooks.Add Set wks = wkb. Worksheets, Add(A fter:~wkb Sheets(wkb Sheets.Count)) wks.Name = “January” wks.Range("Al”).Value = “Sales Data wkb.SaveAs Filename:="JanSales.xisx" End Sub This exemple creates a new empty workbook and assigns a ceference to it to the object variable wkb. A new worksheet is added to the workbook, after any existing sheets, and a reference to the new worksheet is assigned to the object variable wks. The name on the tab at the bottom of the worksheet is then changed to January, and the heading Sales Data is placed in coll Al. Finally, the now workbook is saved as JanSales.xsx. 2 Note that the parameter after the Worksheets.Add is in parentheses. Because you are assigning the return valucrof:the Add method to the object variable, any parameters must be in parentheses. If the return value of the Add method were ignored, the statement would be without parentheses, as follows: wkb, Worksheets. Add After:=wkb Sheets(wkb.Sheets.Count) With...End With Object variables provide useful way to refer to objects in shorthand, and are also more efficiently processed by VBA than fully qualified object strings. Another way to reduce the rs PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 44 i “ ame Peers -VBA- Excel amount of code you write, and also increase processing efficiency, is to use a With..End With structure. The final example in the previous section could be rewritten as follows: With wi . Worksheets. Add After= Sheets(.Shects,Count) End With YBA knows that anything starting with a period is a property or a method of the object following the With. You can rewrite the entire New Workbook procedure to eliminate the wkb object variable, as follows: . ° ‘Sub NewWorkbookQ) Dim wks As Worksheet With Workbooks. Add Worksheets. Add(After= Sheets(.Sheets. Count) Sub NewWorkbaokQ = With Workbooks‘Add 4 With Worksheets. r= Sheets( Sheets.Count)) ‘Name = “January” ° -Range(“A1”).Value = “Sales Data” ; End With SaveAs Filenarie:="JanSales xlsx” End With End Sub If you find this confusing, you can-compromise with a combination of object variables and With,..End With: Sub NewWorkbook() Dim wb As Workbook, wi As Worksheet Set wkb= Workbooks Add With wkb Set wks =. “Worksheets. -Add(After=Sheets(.Sheets.Count)} ‘With wks ‘Name = “January” ‘Range(“AI”). Value = “Sales Data” End With Saved Filename:="JanSales.xlsx” End With End Sub Sy PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 45, Peers -VBA- Excel With...End With is useful when references to an object are repeated in a small section of code. Making Decisions VBA provides two main structures for making decisions and carrying out altemative processing, represented by the If and Select Case statements. If is the more flexible one, but Select Case is better when you are testing a single variable. If Statements MF comes in tree forms: the Uf function, the one-ine If stalement, and the block If structure, Tax = If(¢ProfitBeforeTax > 0, 0.3 * dProfit itBeforeTax, 4) ‘End Function ‘3 If is similar to the Excel worksheet JF function. It has thes input arguritents: the first is a logical test, the second is an expression that is evaluated if the test is true, and the third is an expression that is evaluated ifthe testis false, ’ In this example, the If function tests that the dProjitBeforeTax value is greater than 0. If the” test is tre, Hf calculates 30% of dProfitBeforeTax. If the test is false, Uf calculates 0. The calculated If value is then assigned to the return value of the Tax function. The Tax function can be rewritten using the single-Jine If statement as follows: > . & ee Function dTax(dProfifReforeTax As Double) As Double If dProfitBeforeTax > D Then dTax = 0.3 * dProfitBeforeTax Else aTax = 0 End Function One difference between {ff tn 5 is thatthe Else section of the single-line Jfis, optional. The third parameter of the Jif function must be defined. In VBA, itis often useful to omit the Else: If dProfitBeforeTax < 0 Then MsgBox “A Loss has occurred”, , “Warning” Another difference is that, whereas |If can only retum a value to a single variable, the single- line If can assign values to differeaf variables: If iJohnsScore > iMarysScore Then.iJohn = iJohi+ ! Else iMary = iMary + 1 Block If If you want to carry out ior than one action when a test is trwe, you can use a block If structure, as follows: If iJohnsScore > iMarysScore Then iJobn =iJohn +1 iMary = iMary -1 EndIf ‘Using a block If, you must not include any code after the Then, on the same line. You can have 25 many lines after the test as requited, and you must terminate the scope of the block If with an End Jf statement. PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 46 Peers -VBA- Excel ee A block If can also have an Else section, as follows: IfiJohnsScore > iMarysScore Then iobn = iJohn + 1 iMary = iMary - 1 Else John = iTohn - 1 iMary = iMary + 1 EndIf ‘A block Ifean also have as many Ziself sections as requires If iTohnsScore > iMarysScore Then ohn= ‘ohn + 1 iMary = iMary - 1 ElselfifohnsScore John = iJohn - 1 iMary = iMary + 1 Else itobn= ifohn + 1 iMary = iMary + 1 EndIf When you have a block If followed by one or more Elself tests, VBA keeps testing until it finds a true section. It executes the code for that section and then proceeds directly to the statement following the End If. Ifno test is true, the Else section is executed. ‘A block If does nothing when all ests are false and the ise section is missing, Btock If tests can be nested, one inside the other. You shi f indenting to show the scope of each bluck. This is vital—you te with the nesting of If blocks within other If blocks, and if blocks within Etse btacks, and so on. If code is unindented, it isn’t easy, in a long series of nested IF tests, to match each End Jf with each If IfNot ThisWorkbook.Saved Then 1Answer = MsgBox("Do you want to save your changes”, vbQuestion +_ vbYesNo) If Answer = vbYes Then ‘ThisWorkbook.Save MsgBox This Workbaok.Name & “ has been sayed” End If EndIf This code uses the Saved property of the Workbook object containing the code to see if the ‘workbook has been saved since changes were last made to it. If changes have not been saved, the user is asked if they want to save changes. If the answer is yes, the inner block If saves the ‘workbook and informs the user. Select Case ‘The following block If is testing the same variable value in each section: Function vPrice(sProduct As String) As Variant i PEERS TECHNOLOGIES PVT LTD,, HYDERABAD Page 47 TT ee Peers -VBA- Excel : ES If sProduct= “Apples” Then vPrice = 12.5 Eiself sProduct = “Oranges” Then vPrice = 15 Elself sProduct = “Pears” Then vPrice = 18 Elself sProduct = “Mangoes” Then Price = 25 Bise vPrice = CVEn(xIEGNA) End If End Function If sProduet is not found, the vPrice function retums an Excel error value of #NA. Note that vPrice is declared as a Variant so it can handle the error value as well as numeric values. For 4 sifuation like this, Select Case is a more elegant construction. Jt looks like this: Function vPrice(sProduct As Stcing) As Variant Select Case sProduct Case “Apples” , vyPrice = 12.5 Case “Oranges” vPrice = 15 Case “Pears” End Seiect End Funetion. Tf you have only one statement per case, the following format works quite well. You can place multiple statements on a single line by placing a colon between statements: Function vPrice(sProduct As String) As Variant ° Select Case sProduct Cese “Apples”: vPrice ~ 12.5 Case “Oranges”: vPrice = 15 Case “Pears”: vPrice = 18 Case “Mangoes”; yPrice=25 Case Else: vBrivé = CVErs(xlEnNA) End Select End Function Select Case can also handle ranges of numbers or text, 2s well as comparisons using the keyword Is. The following example calculates a fare of O for infants up to 3 years old and anyone older than 65, with two ranges between. Negative ages generate an error: Function vFare(iAge As Integer) As Variant Select Case iAge ee PEERS TECHNOLOGIES PVT LTD, RYDERABAD Page 48 at Peers -VBA- Excel ES Case To 3, Is > 65 vPare=0 Case 4To 15 vFare=10 Case 16 To 65 vFare = 20 Case Else > vFare = CVEn(xlEnNA) End Select End Function. Looping ‘All computer languages provide a mechanism for repeating the séime, or similar, operations in an efficient way. VBA has two main structures that allow you to loop through the same code over and over again. They are the Do...Loop and the For...Noxt loop.” ‘The Do..Lodp is for those situations where the loop will be terminated when a logical condition applies, such as reaching the end of your data. The For...Nex! loop is for situations where you can predict in advance how many times you want to loop, such as when you want to enter expense for the 10 people in your department. VBA also has an interesting variation on the Mor...Next loop that is used to process all the objects in a collection—the For Each...Vaxt loop. You can use it to process all the cells ina range or all the sheets in a workbook, for example, Do..Loop # To illustrate the yse"8F¥Do...Loop, edastruct a sub procedure to shade every second line of a worksheet, as sown in Figure 1-27, to make it more readable. You want to apply the macro ‘products, so the macro will need to test + determine when to stop. to different report sheets with different mus cach cell in the A column until The first macro will select every other row and apply the formating: rr PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 49 Peers -VBA- Excel eee Sub ShadeEverySecondRow() Range("A2”) EntireRow.Select Do While ActiveCell Value >“ Selection Interior ColorIndex = 15 ActiveCell.Offset(2, 0) EntireRow.Select Loop End Sub ShadeBverySecondRow begins by selecting row 2 in its entirety, When you select an entire tow, the leftmost cell (ia column A) becomes the active cell. ‘The’ ‘code between the Do and Loop statements is then repeated While the value property of the-detive cell is not a zero- Tength string, that is, the active cell is not empty. In the loop, macro sets the interior color index of the selected cells to 15, which is gray. Then the mlacrd Selects the entire row, two ‘rows under the active cell. When a row is selected that has an empty cell in column A, the hile condition is no longes true and the loop terminates, 5 You can make ShadeBverySecandRow run faster’ by avoiding selecting, It is seldom necessary to select cells in VBA, but you are led into this way of doing things because that’s the way you do it manually, and that’s what you get from the macro recorder. The following version of ShadeBveiySecondRow does not seiect Gels, and it runs considerably faster. It sets up an index IRow, which indicates the row of the worksheet and is. initially assigned a value of 2. The Celis ‘Property, ‘of the worksheet allows you to refer to cells by row number and coluitin number, go when the loop starts, Ceils(IRow,1) refers to cell AZ. Each time around the lodp, increased by Ho, ‘You can, therefore, change any reference to the active cell toa Celsf!Row, I) reference and ape. 10 CellsiRow.1} to refer to the complete sow: Sub ShadeverySecondRow)) © Dim Row As Long WRov= 2 Do Until IsEmpty(Cells(IRGiy, 1)) CellsiRow, 1)Entifeow Interior Colorindex = 15 IRow= IRowt 2 Loop End Sub e To illustrate some altermativés two more changes have been made on the Do statement line in the previous code. Hither While or Until can be used after the Do, so the test has been changed to an Until and you have used the VBA IsEmpty function to test for an emply cell. ‘The IsEmpty function is the best way to test that a cell is empty. If you use If Celis(IRow,1)=“", the test will be true for a formula that calculates a zero-length string. Its also possible to exit a loop using o test within the loop and the Exit Do statement, as follows, waich also shows another way to refer to entize rows: Sub ShadeEverySecondRow() eed PBERS TECHNOLOGIES PVT LTD, HYDERABAD Page 50 ire od FSERF Peers -VBA- Excel Dim Row as Long IRow= 0 Do TRow= [Row 2 1 IsEmpty(Celts(Row, 1)) Then Exit Do Rows(IRow) Interior Colorindex = 15 Loop End Sub ‘Yet another altemative isto place the While or Until on the Loop Siatement line. This ensures that the code in the loop is executed at least once. When the test is on the Do line, it is possible that the test will be false to start with, and the loop will be skipped, Sometimes, it makes more sense if the test is on the last line of the loop. In the following, example, it seems more sensible to test sPassHVord after getting input from the user, although the code woutd still work if the Until statement were placed on the Do line: Sub GetPassword() im sPassWord As String, i As Integer 0 Do akal 18> 3 Then ‘MsgBox “Sorry, Only three tries” Exit Sub End If sPassWord = Inpu!Bex(" Loop Uniii sravs = vee MsgBox “Welcome End Sub Assword") GetPassword loops unl the password XXX is supplied, or the number of times around the loop exceeds three. For...Next Loop ‘The For...Next loop differs from the Do...Leap in two ways. It has a built-in counter that is automatically incremented each time the loop is executed, and it is designed to execute until the counter exceeds a predefined value, rather thon depending on a user-specified logical test. ‘The following example places the full file path and name of the workbook into the center footer for cach worksheet in the active workbook: Sub FilePathinFooter() Dimi As Integer, sFilePath As String sFilePath = ActiveWorkbook FullName For i= 1-To Worksheets Count Step 1 ‘Worksheets(), PageSetup.CenterFooter = sFilePath ———_ ee PBERS TECHNOLOGIES PVT LTD, HYDERABAD Page ST —<—<—<—— ee rhO CT Peers -VBA- Exce) Next i End Sub Versions of Excel prior to Excel 2002 do not have an option to automatically include the full file path in a custom header or footer, so this macro inserts the information as text. It begins by assigning the FulName property of the active workbook to the variable sFilePath. The oop starts with the For statement and loops on the Next statement. i is used as a counter, starting at L and finishing when i exceeds Worksheets. Count, which uses the Count property of the Worksheets collection to determine how many worksheets there are inthe active workbook. - ‘The Step option defines the amount that i will be increased each time around the loop. Step 2 could be left out ofthis example, becavse a step of 1 is the defoult value. In the loop, iis used 8 an index to the Worksheets collection to specify each individual Worksheet object. The PageSetup property of the Worksheet object refers to the PageSetup object in that workshect, 0 that the CenterFooter property of the PageSetup object can be assigned the sFilePath text. The following exemple shows how you can step backwards. It takes a complete file path and sirips out the filename, excluding the file extension. The example uses the FullName property of the active workhook os input, but the same code could be used with any file path. It starts at the last character in the file path and steps backwards until it finds the period between the filename and its extension, and then the backslash character before the filename. It then extratis the characters between the two: Sub GetFileNameQ 5 Dima iBackSlash As integer, iPoint As inte Din sFilePath’As String, sFileName As String Dimi As Integer FriePath = Active Workbook FullName For i= LenfsFilePath) To 1 Step -1 IEMidS(sFilePath, i, 1) ="\" Then iPoint=i Exit For LengsFiteath) + 1 For i= (Point- 1 To 1 Step-I Tf MidS(GFilePath, i, 1) "V" Then sFileName = MidS(sFilePath, iBackSlash + 1, iPoint -iBackSlesh - 1) MsgBox sFileName End Seb ‘The first For... Next loop uses the Len function to determine how many characters are in the eed PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 52 Peers -VBA- Excel : ES sFilePath variable, and i is set up to step backwards, counting from the last character position, Working toward the first character position. The MidS function extracts the character ftom sFilePath at the position defined by i and tesis it to see if tis 2 period. ‘When a period is found, the position is recorded in iPoint and the first For...Next loop is exited, Ifthe filename has no extension, no period is found and #Poiné will have its default value of 0. In this case, the Jf test records an imaginary period position in éPoint that is one character beyond the end of the filename, The same technique is used in the second For..Next loop as the first, starting one character before the period, to find the position ofthe backslash character, and storing the position in BackSlash. The Mid function is then used to extract the characters between the backslash and the period. For Each...Next Loop When you want to process every member of a collection, you can use the For Eack...Next Joop. The following example is a rework of the FilePathinFooter procedure: Sub FilePathInFooter() Dim sFilePath As String, wks As Worksheet sFilePath ~ ActiveWorkbiok FullNome For Bach wks In Worksheets wks PageSetup CenterFooler = sFilePath wetuee e End Sub The loop next member of fhe 2nibers of the collection, During each pass, a reference to the js assigned to the object variable wis. The following example lists all the files in the root directory of the C: drive. Tt uses the Windows Scripting FileSystemObject to create a reference to the C drive root directory. The ‘example uses a For Each.«Next loop to display the names of ll he files inthe directory: ® Sub FileList “Listing files with a For..Bach loop Dim objFSO As Object = Dim objFolder As Object Dim objFile As Object “Create a reference to the FileSystemObject Set objFSO = CreateObject("Scripting FileSystemObject”) “Create a folder reference Set objFolder= objFSO.GetFolder( rere PEERS TECHNOLOGIES PVT LTD, HYDERABAD PageS3 Peers -VBA- Excel “List files in folder For Bach objFile In objFolder Files ‘MsgBox objFile Name Next objéile End Sub The code uses techniques thet are discussed in Chapter 19 to reference objecis outside the Excel cbject model. Ifyou test this procedure on a directory with lots of files, and get tired of clicking OK, don't forget that you can break out ofthe code Arrays Arrays are VBA variables that can hold more than one item of data. An array is declared by including parentheses after the array name. An integer is placed within the parentheses, efining the number of elements in the asray: ‘ : : Dim avData(2) ‘You assign values to the elements of the array by indicating the clement number as follows: 2 : avData(0) avData(I) = 10 avDala(2) = 100 The numberof eles ig-the aay, depends on the anay base, The defait base is 0, which means that the first data elment is item 0. Dim avData(2) declares a three-element array if the hase is 0. Altematively, you can place the following statement in the declarations section he top of your module to declare that arrays are 1-bosed: Option Base f ° ‘With a base of 1, Dim avData(2) declares a two-element array, Item 0 does not exist. You can use the following procedure to test the effect of the Option Base statement: Sub Aryl) Dim aiData(10) As Integer. Dim sMessage As Sting, As Integer Fori=LBound(aiDats) To UBound(aiData) aiData(i)=i Next sMessage = “Lower Bound ="* & LBound(aiData) & voCr sMessage = sMessage &: "Upper Bound =“ & UBound(aiData) & voCr sMessage = sMessage & “Num Blements ~ “ & WorksheetFunction,Count(aiData) & vbr sMessage = sMessage & “Sum Elements =" & WotksheetFunction Sum(aiData) ‘PEERS TECHNOLOGIES PVT ETD, HYDERABAD Page 54 Peers -VBA- Excel See ee MsgBox sMessage End Sub . Array! uses the LBound (lower bound) and UBound (upper bound) functions to determine the Jowest and highest index values for the array. It uses the Count worksheet function to determine the number of efemtents in the aay. If you run this code wilh Options Base 0, of n0 Options Base statement, in the declarations section of the module, it will show a lowest index aumber of Oand 1 elements in the aray, With Options Base 1, it shows a lowest index number of | and 10 elements in the array. [Note the use of th nrinsic constant VoCr, which contains carte return character. Cr 4s used to break the message text toa new line If you want to mske your aay size independent of the Option Base statement, you can > explicitly declare the lower bound as well as the upper bound as follows: Dien avData(1 To 2) Arrays are very usefil for processing lists or tables of tems. Ifyou want to cate a short ist, you can use the Array function as follows: Dim avDala As Variant avData = Array("North”, “Sout ' “East”, “West") You can then use the lisi’in a For..Neet loop. For example, you could open and process a series of workbooks called North.xls, South ly, Easxls, and Westxls: Sub Array20, Dim ayData As Variant, wkb AS Workbook + integer avData = Array(‘North”, “South”, "East", “West") For i= LBound(eyData) To UBound(avData) Set wiky = Workbooks Open(Fileaame:=avData(i) & xls") “Process data here swkb,Close SaveChaiiges:~True ‘So far you have only looked at arrays with a single dimension. You can actually define arrays -with up to 60 dimensions, although few people woutd use more than two or three dimensions. The following statements declare two-dimensional arrays: Dim avData(10,20) Dim avData(t To 10,1 to 20) a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 55 Peers -VBA- Excel ‘You can think of a tio-dimensional array as a table of data. The preceding example defines 2 table with 10 sows and 20, columns, Amtays axe very useful in Excel for processing the data in worksheet ranges. It cam be far ‘more efficient (o load the values in a range into an array, process the data, and write it back to the worksheet, than to access each ceil individuslly, The following procedure shows how you can assign the values in a range to a Variant. The code vses the LBound and UBound fanctions to find the number of dimensions in avData, Note that there is a second parameter in LBound and UBound ta indicate which index you are referring to. [f you leave this parameter out, the functions refer fo.the frst index: Sub Array3) $e DimayData As Variant, vUBound As Variant Dim Message As String, i As Integer = avData = Range(“A1:A20"). Value i=l De Message ~ “Lower Bound =“" & LBound(avData, i) & vbCr Message = Message & “Upper Bound =“ & UBound(avData, i) & voCr MsgBox Message, , “Index Number=" & i +1 vUBound: cubes i) IfErrNumber > 0 Then Exit Do OnEnerGoToo Loop ‘Message = "Number of Non Blank Elements =" ‘& WorksheetFunction. Count (avData) & vbCr MsgBox Message End Sub : ‘The fisst time around, the Do..Lodp, Array3 determines the upper and lowes bounds of the first dimension of avDara, as i bas a value of |. It then increases the value of i to look for the next dimersion.t exits the oop when an error occurs, indicating that no more dimensions exist. By substituting different ranges isto Array3, you can determine that the array created by > assigning a range of values to a Variant is two-dimensional, even if there is only one row or one column in the range, You cin also determine that the lower bound of each index is 1, regardless of the Option Base setting in the declarations section. Dynamic Arrays ‘When writing your code, it is sometimes not possible to determine the size of the array that will be required. For example, you might want to foad the names of all the xs files in the ‘eurtent directory foto an array. You won't know in advance how many files there will be, One altemative isto declare an array that is big enough to hold the largest possible amount of ate—but this would be inefficient. —————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 56 Peers -VBA- Excel Se aa cd Instead, you can define a dynamic array and set its size when the procedure runs. You declare 1 dynamic array by leaving out the dimensions: Dim ayDateQ You can declare the required size at run time with a ReDim statement, which can use ‘variables (0 define the bounds of the indexes: ReDim avDataGiRows, iColumns) ReDim avData(iminRow to imaxRow, iminCol to imaxCol) ReDim will e-initalize the array and destroy any data in it, unless you use the Preserve Keyword, Preserve js used in the following procedure that uses a Do...Leop to load the names of files into the dynamie array called asF'Names, increasing the upper bound of its index by ‘one each time to accommodate the new name, ‘The Dir function retums the first flename found that matches the wildcard specification in sFIppe. Subsequent usage of Dir, with no parometer, repeats the safne specification, getting the next file that matches, until it runs out of files and returns a zero-length string: Sub FiteNamesQ Dim sFName As String Dim asFNames() As Sting, Dim sFType As String. Dimi As Integer sFType=“#x1s?" sFName = Dir(sFTyps) Do Until sFNeme="” isiet ReDim Preserve asFNames(I To i) ° sFName Then, 4 ‘MsgBox “No files found” For i= | To UBound{askNames) MsgBox asf Names(i) Nexti ° Bnd If End Sub you intend ta work on the files in a directory and save the results, it is @ good Idea to get all the filenames first, as in the FileNames procedure, and use that list to process the files. Its rot a good idea to rely on the Dic function to give you an accurate file list while you are in the process of reading 2nd overwriting files. Run-Time Error-Handling a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 57 Peers -VBA- Excel ‘When you are designing an application, you should try to anticipate any problems that could ‘eccur when the application is used in the real world. You can remove all the bugs in your code and have flawless logic that works with all permutations of conditions, but a simple operational problem could still bring your code crashing down with a less then helpful message displayed to the user. For example, if you by to save a workbook file to the floppy disk in the A: drive, and there is no disk in the A: drive, your code will grind toa halt and display a message that will probably ‘not mean anything to the average user. you anticipate this panizuler problem, you can setup your eodé io gracefully deal with he sitoetion. fg ‘VBA allows you to trap error conditions using the fallowing statement: ‘On Enor GoTo LineLabel LineLabel is a marker that you insert at the end of your uormal code, as shown in the following code with the Tine Tabet err'Trap, Note that a colon follows the line label: The fine label marks the start of your error recovery code and should be preceded by an Exit statement to prevent execution of the error recovery code when tio error occurs: Sub Error TraplQ Dim lAnswer As Long, sMVFil As Sting Dim sMessage A Sting, SCutentPath As Sting On Enor Gotog sGmeyeah ae ChDrive “A” Chbrive sComentath a ChDir sCurrentPath sMyFile =" “ANDataxls” | Application. DisplayAlerts= False ActiveWorkbook.SaveAs. :FijenamesMyFile TidyUp: Ge ‘ChDrive sCarentPath (Chir sCurrentPath Exit Sub centTrap: sMessage = “Error No: Er. Number & vbCr sMessage = sMessage & ir Description & voCr & vbCr sMessage = sMessage& “Please place a disk jn the A: drive” & vbCr sMessage = sMessage & “and press OK" & vbCr & vbCr sMescage = sMessage & “Or press Cancel to abort File Save” Answer = MsgBox(sMessage, voQuestion + vbOKCancel, “Error’) ‘If lAnswer = veCancel Then Resume TidyUp Resume End Sub ‘Once the On Error statement is executed, erzor trapping is enabled. If an error occurs, no ‘message is displayed and the code following the line label is executed. You can use the Err cbject to obtain information about the error. The Number property of the Err object retums ne PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 58 Peers -VBA- Excel i ee the error number, and the Description property retums the error message associated with Ihe error, You can use Err.Number to determine’ the error when it is possible that any of a number of errors could occur. You can incorporate Brr.Description into your own error message, if appropriate. In Excel 5 and 95, Est was not an object, but a function that returned the error number. Because Number is she default property of the Ex object, using Ext by self is equivalent to using Err Number, and the code from the older versions of Excel still works in Excel 97 and Tater versions. The code in ErrorTrap!, after executing the On Error statement, saves the current directory drive and path into the variable sCurrendPath. It then executes the ChDrive statement to try to activate the A: drive. If there is no disk inthe A: drive, eror 68—(Device unavailable) occurs and the error recovery code executes. For illustration purposes, the eor number and description are displayed and the user is given the opportunity to either place a disk in the A: drive and continue, or abort the save. If the user wishes to stop, you branch back to TidyUp and restore the original drive and directory settings. Othorwise the Resume, statement is executed, This means that execution retums to the statement that caused the ertor. If there is still no disk in the A: drive, the error recovery code is executed again. Otherwise the code confinues normally. ‘The only reason for the ChDrive “A” statement is to fest the readiness of the A: drive, so the code restores the stoted drive and directory path. The code sets the DisplayATeris property of the Application object to Fase, before saving the active workbook. This prevents a waming if sn ol il aed Datel is being replaced bythe new Davai. (See Chap 3 for more on DisplayAleris) : ‘The Resume statement comes in three forms: © Resume causes execution of the statement that caused the error. D Resume Next returns execution to the statement following the statement that caused the ‘error, so the problem statement is skipped. 1 Resume LineLabel jumps back to any designated line label in the code, so you can decide to resume where you Want. The following code uses Resume Next to skip the Kil! statement, if necessary. The charmingly named Kill statement removes a file from disk. The following code removes any file with the same name as the one you are about to save, so there will be no need to answer the warming sessage about overwriting the existing file ‘The problem is that Xill will cause a fatal error if the file does not exist. If Kill does cause a problem, the error recovery code exeoutes and you use Resume Next to skip Kill and continue With Saveds. The MsgBox is thee for educational purposes only. You would not normally include it: Sub Error Trap20) ‘Dim sMyFile As String, sMessage As Sting Dim sAnswer As String On Eror GoTo entTrap ——————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 59 Peers -VBA- Excel eS Workbooks.Add sMyFile="C\Data.xls” Kill sMyFile ActiveWorkbook SaveAs Filename:~sMyFile ActiveWorkbook Close Exit Sub enrTrap: sMessage = “Error No: =“ & En-Number & voCr sMessage = sMessage & Ent Description & vbCr & vbCr ‘Message = sMessage & "File does not exist” ‘sAnswer = MsgBox(sMessage, vbInformation, “Error’ Resume Next End Sub On Error Resume Next : ‘As an altemative to On Error GoTo, you can use: On Error Resume Next This statcment causes errors to be ignored, soit should be used with caution. However, it has ‘manly uses. The following code is a rework of ErcorTrap2; Sub ErvorTrap3) Dim sMyFile As String Workbooks,Add sMyFile = *CAData.xls” On Error Resume Next Kill sMyFile OnEnor GoToo ActiveWorkbook SaveAss Filename:=sMyFile ActiveWorkbook.Close End Sub Use On Error Resume New just before the Xilf statement. If C:\Data.xls does not exist, the ‘error caused by Kill is ignored and execution continues on the next line. After all, you don’t care if the file does not exist. That’s the situation you are trying to achieve. (On Error GoTo 0 is used to tum on normal VBA error-handling again. Otherwise, any further errors would be ignored. It is best not to try to interpret this statement, which appears to be directing errorbandling to Jing 0. Just accept that it works. ‘You can use On Error Resume Next to write code that would otherwise be less efficient. The following sub procedure determines whether a name exists in the active workbook: ‘Sub TestPorName() If bNameExists(“SalesData") Then ‘MsgBox “Name Exists” Else ‘MsgBox “Name does not: ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 60 Peers -VBA- Excel ee End If End Sub a Function bNamcExists(sMyName As String) As Boolean j ‘Dim sName As String 4 (On Error Resume Next £ sName = Names(sMyName) RefersTo cc » fEm Number > 0 Then (| ‘bNameExists = False . Ere. Clear i Else bNameBxists = True Pgs EndIf oe Bnd Funetion Le TestForName calls the bNameBxists function, which uses On Error Resume Next to prevent a ° fatal erxor when it tries to assign the name's RefersTo property toa variable. There is no need for On Error GoTo 0 hese, because érror-handling in a procedure is disabled when a procedure exils, although ErrNumber is not cleared, If no error occurred, the Number property of the Emr object is 0. If Br-Number has 9 non-O value, an error occurred, presumably because the name did not exis, so bNameExists is assigned a value of False and the etzor is cleared. The alternative to this single pass procedure is to loop through all the names in the workbook, Woking for mate, IF there are lots of names, this can be a slow process, F Summary if Tn this chapter; you have seen those elements of the VBA language that enable you to write useful and efficient procedures. You have seen how to add interaction to macros with the MsgBox and InpurBox functions, how to use variables to store information, and how to get help with VBA keywords, ‘You have seen how to declare variables and define their type, and the effect on variable scope and lifetime of different declaration techniques. In addition, you used the block If and Select Case structures to perform tests and camry out alternative calculations, and Do...Loop and For.,.Next loops that allow you to efficiently repeat simnitar calculations. You have seen how arrays can be used, particularly with looping procedures. Moreover, you leamed how to use On Error stements to trap errors. ‘When writing VBA code for Excel, the easiest way to get started is to use the macro recorder. ‘You can then modify that code, using the VBE, to better suit your purposes and to operate efficiently. Using the Object Browser, Help screens, and the reference section of this book, ‘you can discover objects, methods, properties, and events that can’t be found with the macto B recorder. Using the coding structures provided by VBA, you can efficiently handle large amounts of data and automate tedious processes. You now haye the knowledge required fo . ‘move on to the next chapter, where you will ind a rich set of practical examples showing you how to work with key Excel objects. You will discover how to ereate your own user interface, setting up your own Ribbon buttons and dialog boxes, and embedding controls in ‘your worksheets to enable yourself and others to work more productively. et PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 61 Peers -VBA- Excel a Workbooks and Worksheets How to: Create a Workbook To create a workbook in Visual Basic, use the Add method. The following procedure creates a workbook. Microsoft Excel automatically names the workbook BookN, where Nis the next avaitabte number. The new workbook becomes the active workbook. Sub AddOneQ) ‘Workbooks,Add End Sub Pe A better way fo citate 2 workbook is to assign it to an object able. In the following example, the Workbook object retumed by the Add method is assigned to an ebject variable, newBook. Next, several properties of newBook are set. You can easily control the new ‘workbook by using the object variable. hi Sub AddNewO ‘Set NewBaok= Workbooks Add ‘With NewBook Title= "Al! Sales" me - “Subject = "Sates" : ‘Saveds Filename: End With Bnd Sub Opening a Workbook sales xis" ‘When you open sworkbopk using Egon ‘method, it becomes a member of the Workbooks collection, The followisk procedure? ppens a workbook named MyBook.xls located in the folder named MyFolder on dtiye.C, . Sub OpenU pO ae ‘Workbooks Open("C:\MyFolder\MyBookxs") End Sub , How to: Refer to More Than Onié Sheet Use the Amray function to ident ‘sheets in the active workbook. Sub Several) ~ Worksheets(Array("Sheetl", "Sheet?" ‘End Sub How ta: Referto Sheets by Index Number group of sheets. The following example selects three “"Sheet3")).Select ‘Am index number is a seqiiial number assigned toa sheet, based on the position ofits sheet tab (counting from the left) among sheets of the same type. The following procedure uses the ‘Worksheets propery fo activate worksheet one in the active workbook. Sub FirstOneQ, Worksheets) Activate End Sub Ifyou want fo work with all types of sheets (worksheets, charts, modules, and dialog sheets), use the Sheets property. The following procedure activates sheet four in the workbook. BEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 62 Peers -VBA- Excel es Sub FourthOneQ Sheeis(4).Activate End Sub Note: ‘The index order can change if you move, add, or delete sheets. How to: Refer to Sheets by Name You can identify sheels by name using the Worksheets and Charts properties. The following statements activate various shee inthe active workbook. Workshieets(’Sheet!").Activate Charts(*Chartl").Activate DialogSheets("Dialog!”). Activate You can use the Sheets property to return a worksheet, chart, module, or dialog sheet; the Sheets collection contains all of these. The following example activates the sheet named "Chart" in the active workbook. we Sub ActivateChart) Sheots(*Chartl"). Activate End Sub A Note: J s ‘Charts embedded in a worksheet are members of lhe ChartObjects collection, whereas charts that exist on their own sheets belong to thé Charts collection, : Cells and Ranges * ‘How to: Reference Cells and Ranges ‘A common task when using Visual Basic is to specify a cell o range of cells and then do something with it, such as enter a formula or change the format, You can usually do this in one slatement that identifies the range and also changes a property or applies a method. A Range object in Visual Basic can be either a single cell or a range of cells, The following > topics show the most common ways to identify and work with Range objects ‘Some ways to reference cells How to: Refer to All the Cells on the Worksheet How to: Refer to Celis and Ranges by Using Al Notation How to: Refer to Rows and Columis How to: Refer to Cells by Using Index Numbers How (o: Refer to Cells by Using Shortcut Notation How to: Refer to Cells Retative to Other Cells How lo: Refer to Cells by Using a Range Object, { How to: Refer to Named Ranges ° How to: Refer to Multiple Ranges How to: Refer to All the Cells on the Worksheet : ‘When you apply the Cells property to a worksheet without specifying an index number, the i method retums a Range object that represents all the cells on the worksheet. The following s ‘Sub procedure clears the contents from all the cells on Sheet! in the active workbook. i: oes PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 63 Peers -VBA- Excel aS Sub ClearSheetQ) Worksheots("Sheet”) Cells ClearContents End Sub How to: Refer to Cells and Ranges by Using Al. Notation ‘You cam refer to a cell or range of cells in the A. reference style by using the Range property. ‘The following subroutine changes the format of cells AL-DS to bold. Sub FormatRange() ‘Wotkbooks("BookI") Shects("Sheet!").Range("AL:DS")_ Font Bold = "True End Sub ‘The following fable illustrates some A-style references using the Range property. Reference ‘Meaning RangeC"Al") CeHAT Range("ALBS") Cells AT through BS Range("C5:9,G9.16") ‘A multiple area selection Ranget"A:A°) Column A Range) Row? Ree 7) Columns A through C % Rows I through 5 Rows T, 3, and 8 Colurans A, C, and F 9: Refer to Cells by Using a Range Object if'you set an object variable to a Range object, you can easily manipulate the « le name. ‘The following procedure crests the object variable myRange and then assigns the variable to sange ALDS gn Sheeti in the active workbook. Subsequent slatements modify properties of therange by substituting the variable mame for the Range object, Sub Random e Dim myRange As Range Set myRange = Worksheets(*Sheet!") Range("A.:DS") myRange Formula = "=RANDO" myRange Font Bold = True End Sub How to: Refer to Cells by Using Index Numbers You can use the Cells property to refer ‘0 a single cell by using row and column index ‘numbers. This property returns a Range object that represents 2 single cell In the following exanipte, Cells(6,1) retums cell A6 on Sheet. The Value property is then set ta 10, Sub EnterValueQ) Worksheets("Sheetl").Cells(6, 1).Value= 10 End Sub ne PEERS TECRNOLOGIES PVT LTD, HYDERABAD Page 6+ Peers -VBA- Excel , a The Cells property works well for looping through a range of cells, because you can substitute variables for the index numbers, as shown in the following example. Sub CycleThrough0 Dim Counter As Integer For Counter= 1 To 20 Worksheets("Sheet!"),Cells(Counter, 3)-Value = Counter Next Counter End Sub Note ¢ Ifyou want o change the properties of (or apply a method to) Arange’of cells all at once, use the Range property. For more information, see Refer to Cells and Ranges by Using Al Notation How to: Refer to Cells by Using Shortcut Notation ‘You can use either the Al reference style or a named range within brackéts as a shortcut for the Range property. You do not have to type the word "Range* or use quotation marks, as shown in the following examples. Sub ClearRangeQ) ‘Worksheets("Sheet1"} [A :B5} ClearContents End Sub Sub SetValueQ) [MyRange]. Value = 39. End Sub ye How ta: Refer fo Multiple Ranges Using the appropriate method, you can easily refer to multiple ranges. Use the Range and Union methods to refer to any group of ranges; use the Areas property to eter to the group of ranges selected on a worksheet. ‘Using the Range Property ‘You can refer to multiple ranges with the Range property by inserting commas between two or more references. The following example clears the conteas of three ranges on Sheet]. ‘Sub ClearRanges() ° Worksheets(""Sheet] 1) RonRCCSDD.GOHISDIADIE" 0 ClearContents End Sub ‘Named ranges make it easier'to use the Range property to work with multiple ranges. The following example works when all three named ranges arc on the same sheet. Sub CleaxNamedO Range("MyRange, YourRange, HisRange") ClearContents End Sub Using the Union Method ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 65 Peers -VBA- Exce} ‘You can combine multiple ranges into one Range object by using the Union method. The following example creates a Range object called myMultiplcRange, defines it as the ranges ALB2 and C3:D4, and then formats the combined ranges as bold. ‘Sub MoltipleRangeQ Dimi, 12, myMultipleRange As Range Setrl = Sheets("Shect|") Range("Al:B2") Sel 2 = Sheets("Sheet!") Range("C3:D4") Set myMultipleRange (cl, 72) myMultipteRange Font Bold = True End Sub fe Ushag the Areas Property You can use the Areas property to refer to the selected range’or io the collection of ranges in 4 multiple-area selection, The following procedure counts the areas inthe selection. Jf there is ‘more than one area, a warming message is displayed, = Sub FindMullipled) Uf Selection, Areas.Count > | Then ‘MsgBox "Cannot do this fo 2 mulpleselest EndIf End Sub Ranges ate easier to jdentify by name thal by Al notation, To same a selected range, click the mame box at thé 16 end of the formule Bar, type a name, and then press ENTER. Referring to a Named Range The following example refers fo the range named "MyRange” in the "MyBook." ‘Sub FormatRange() Range("MyBook.xis!MyRange") Font Jtalie= True End Sub The following example refers to ie worksheet-specific range named "Sheet! Safes" in the ‘workbook named "Report.xis." Sub FormatSalesQ) Range ‘Report xsSheetl Sales") BonderAround Weightman End Sub To select a named range, use the GoTo method, which activates the workbook and the ‘worksheet and then selects the range: Sub ClearRange() “Application Goto Reference:="MyBock.xlsfMyRange* Selection. ClearContents End Sub ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 66 Peers -VBA- Excel aS The following example shows how the same procedure would be written for the active ‘workbook, Sub ClearRangeQ) Application. Goto Reference:="MyRange” > Selection. ClearContents Bnd Sub » Looping Through Cells ia a Named Range The following example loops through each cell in a named range by using a For Each.. Next loop. Ifthe value of any cell in the range exceeds the value of fii, the cell color is changed. toyellow. ba ge Sub ApplyColor() ‘Const Limit As Integer = 25 7 For Each ¢ In Range("MyRange") . Ifc.Value > Limit Then Interior. Colorndex = 27 EndIf Next c End Sub How tor Refor to Rows and ¢ Cotumas: > : properties return a Range objets pte range of eel. In te faloing example, Rows(1) retums row ee ‘Sheetl, The Bold property of the Font object for the range is Sub RowBold) ° Worksheets("Sheetl"). Rows(1),Font.Bold = True End Sub ‘The following table illustrates some row and column references using the Rows and Columns properties, 2 Reference ‘Meaning Rows(!) Row one Rows ‘All the rows on the Worksheet Columns(1) ‘Column one. Columns("A") ‘Column one. ‘Columns “All the columns on the worksheet ‘To work with several rows or columas at the same time, create an object variable and use the Union method, combining multiple calls to the Rews or Columns property, The following example changes the format of rows one, three, and five on worksheet one in the active ‘workbook to bold. Sub SeveralRows() ‘Worksheets("Sheeti") Activate Dim myUnion As Range ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 67 # ts Peers -VBA- Excel Sot myUsion = Union(Raws(1), Rows(3), Rows(5)) smyUnion Font Bold = True Bad Sub Looping’ Through a Range of Cells: ‘When using Visual Basic, you often need to run the same block of statements om each cell in ‘range of cells. To do this, you combine a looping statement and one or more methods to identify each cell, one at atime, and run the operation. One way to loop through a range is to use the For...Next loop with the Cells property. Using the Celis property, you can substitute the loop counter (or other variables or expressions) for the cell index mumbers. In the following example, the variable counter is substituted for the ow index. The procedure loops through the range C1:C20, setting to 0 (zeto} any number whose absotute valve is less than 0.01. . Sub RoundToZerot() oe For Counter> 1 To 20 Set eurCell = Worksheets("Sheetl").Cells(Counter, 3) Af Abs(curCel. Value) < 0.01 Then cwCell, Value = 0 Next Counter : End Sub > ‘Another easy way to loop thrpugh a range is to use a For Each..Next loop with the collection of cells specified in th¢ Range property. Visual Basic automatically sels an object variable for the next cell each time the loop rans. The following procedure loops through the range ‘ALDIO.seing to 2) any —" ‘whoge absolute value is Tess than 0.01. ‘Sub RoundToZero2(Q) ‘ For Each ¢ In Worksheets{"Shect]' | Range("Al ‘D10").Cells If Abs(c. Value) < 0.01 Then c Value = 0 Next ‘End Sub If you do not know the boundaries of the sange you want to loop though, you can use the CurrentRegion property to return the range that surrounds the active cell. For example, the following procedure, when run from a worksheet, loops through the range that surrounds the active cell, setting to 0 (zero) any nuinber whose absolute value is less than 0.01. Sub RoundToZero30) For Each c In ActiveCell. CurrentRegion. Cells WAbs(¢ Value) <0.01 Then. Value =0 Next Bnd Sub Selecting and Activating Cells. ‘When you work with Microsoft Exeel, you usually select a cell or eells and then perform an action, such as formatting the celts or entering values ia them. In Visual Basic, i is usually not necessary to select cells before modifying them. ed PEERS TECHNOLOGIES PVT LID, HYDERABAD Page 68 Peers -VBA- Excel ee For example, if you want to enter a formula in cell D6 using Visual Basic, you do not need to select the range D6. You just need to retum the Range object and then set the Formula property to the formula you want, as shown in the following example, Sub EnterFormula() Worksheets(*Sheetl") Range('‘D6")-Formula = "=SUM(D2:D5)" ‘End Sub For examples of using other methods o control cells without selecting them, see How fo: Reference Cells and Ranges. ~ Using the Select Method and the Selection Property = The Sclect method activates sheets and objects on sheets; the Selection property retums an object that represents the current selection on the aclive sheet in the active workbook. Before ‘you can use the Selection property successfully, you must activate a workbook, activate oF select a sheet, and them select a range (or other object) using the Select method. ‘The macro recorder will often create a macto that uses the Select method and the Selection property. The following Sub procedure was ereated using the macro recorder, and it illustrates how Select and Selection work together. Sub Macrol0. wr AY Sheets('Sheet!") Select Range(“A1").Select As > ActiveCell FormulaRICl = *Natie” Range("BI") Select ActiveCell FormulaR Range("A1:B1") Setect Selection FontBold = True End Sub The following example sccomplishes the same task without activating or selecung the worksheet or cells. > Sub Labels. With Worksheets("Sheet!") Range("Al")= "Name" -Range("BI")= "Address" Range(“AL-B1")Font Bold = Truc End With End Sub Selecting Cells on the Active Worksheet If you use the Select melbod to select cells, be aware thet Select works only on the active ‘worksheet. Ifyou run your Sub procedure from the module, the Select method willful unless ‘your procedure activates the worksheet before using the Select method on a range of cells, For example, the following procedure copies a row fiom Sheetl to Sheet? in the active ‘workbook, Sub CopyRow0 ‘Worksheets("Sheetl”) Rows(1).Copy —— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 69 Worksheels("Sheet2") Select ‘Worksheets("Sheet2").Rows(1).Select, ‘Worksheets("Sheet2") Paste End Sub Activating a Cell Within a Selection ‘You can use the Activate method to activate a cell within a selection. There can be only one active cell, ven when 2 range of cells is selected. The following procedure selects a range and then activates a cell within the range without changing the selection, ‘Sub MakeActive() ge Worksbeets("SheetI*) Activate fer Range(“ALD4") Select f Range('B2") Activate End Sub Working with the Active Cell ‘The ActiveCell property returns a Range object that represents the cell that is active. You can apply any of the properties or methods of a Range object to the active cell, as in the following ‘oxample. Sub SetValueg) « Workshects("Shect!"). Activate, ActiveCell, Value = 35. ja? End Sub Note ” ‘You can work with the actiye'cell only when the worksheet that itis on is the active sheet, Moving the Active Cel You can use the Activate method fo designate which velt is the active cell. For example, the {following procedure makes BS the active cell and taen formas it as bold Sub SetActived) ‘Worksheets(*SheetI") Activate Worksheets("Sheet!") Range("BS"), Activate, ActiveCell Font Bold= Tre End Sub Note : To select a range of cells, use the:Select method. To make a single cel the active cell, use the Activate method. feo ‘You can use the Offset property to move the active cell. The following procedure inserts text into the active cell in the selected range and then moves the active cell one cell to the right ‘without changing the selection. Sub MoveActiveQ) ‘Worksheets("Sheetl") Activate Range("AL:D10"} Select ‘ActiveCell. Value = "Monthly Totals" a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 70, Peers -VBA- Excel ActiveCelLOffsel(0, 1).Activate End Sub Selecting the Cells Surrounding the Active Cell ‘The CurtentRegion property rcturns a range of cells bounded by blank rows and columns. In the following example, the selection is expanded to include the cells adjoining the active cell that contain data, This range is then formatted with the Currency style. SubRegionO Worksheets("Sheetl") Activate ActiveCell.CurentRegion.Select Be Os. ‘Working with 3-D Ranges If you are working wih the same range on more than one shee, use the Aray function to specify two or moze sheets to select. The following example formats the border of a 3-D range of cells. Sub FormatSheets() Sheets(Array("Sheet2", "Sheet", "SheetS")) Select Range("AI:HI") Select Selection Borders(xiBotton) LineStyle = xlDouble End Sub ‘The following example-applies the TillactbsiSheets method to transfer the formats and any data from the range on Slieet? to the torresponding ranges on all the worksheets in the active ‘workbook. Sub FiMLAIIQ Worksheets*Sheeta") Range(’ALEIN)_ Borders(xiBottom) LineStyle ~ xiDoubie Workshess FilAcrossShets (Workshet("Shee2")_ : Range(“Al-HI")) End Sub i 8 Cell Error Values % ‘You can insert a cell exor value into a cell or test the value of a cell for an errot value by using the CVErr function. The cell error values can be one of the following XICVEnor constants. f Constant ‘Error number Cell error value xlEnDiv0 2007 #DIVIOL xtEnNA 2042 EXZN ‘xlBnName 2029 #NAME? MEnNull 2000 ‘@NULL! xiEnNum 2036 #NUM! xEnRet 2023 REE! xiEmValue 2015, ‘#VALUE! ‘PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 72 Peers -VBA- Excel Example This example inserts the seven cel error values into cells AI:A7 on Sheetl. myAmay = Anrey(sIEnDiv0, xiEMNA, xIEtName, xiEriNull,_ alBrNum, xiEnRef, xlrValue) Fori= 1 To? : Worksheets("Sheetl").Celts(i, )- Value = CVEm(myAcay(i- 1)) Next i ‘This example displays a message if the active cell on Sheet! contains a celt error value. You ‘can use this example asa framework for a cel-errar-value error handler, ‘Worksheets("Sheetl"). Activate If sEcror(AetiveCell. Value) Then enrval = ActiveCell-Vahue Select Case errval Case CVEn(xlEnDiv0) MspBox "#DIV/0! error" Case CVEn(xIEGNA) Msofiox "ANVA esror" Case CVEn(xlEnName) ‘MsgBox "NAME? error" Case CVEm(ERNutl) Case CVEm(xtEnValue) MsgBox "#VALUE! error” Case Else MsgBox "This should never happeni!” End Select EndIf Range Object Members Represents a cell, a row, a column, 2 selection of cells containing one or more contiguous blocks of eels, or 93-D ronge. Metods -_ Name [Description vance ‘Activates a single ell which must be inside he eurent selection, To select arange ofclls, use the Select method. AdiComment "Adds a comment to the range. ' lle of copies data from a Tist based on effeda range. IF he AdvancedPitter intl selection se singe cel that cells cure region i 368, | RppiiNames Aaplies names tothe cells in the specified ange. | ApplyOullineSiyies | Applies ouilining styles tothe specified range. ‘AutoComplete Returns a0 AvtoComplete match from the Ist Wf there's no ET PEERS TECRNOLOGIES PVT LTD, HYDERABAD Page 72 Peers ~VBA- Excel ‘AuloComplete match or if more than one entry in the list matches the string to complete, this method returns an empty string, AutoFill Performs an autofill on the cells in the specified range. ‘AvtoFilter Filters a list using the AutoFiler. “Autorit ‘Changes the width of the columns in the range or the height of the rows inthe range 1 achive the best fi. ‘Automatically creates an outline for the specified range. Ifthe range ‘AutoOutline is a single cell, Microsoft Excel creates an outline for the entire sheet. The new outline replaces any exiting outline, ‘Adds a border to a range and sels the Color, LineStyle, and Weight BorderAround properties forthe new border. Variant. Calculates all open workbooks, a specific worksheet in a workbook, Calculate cor a specified range of eels on a worksheet, as shown in the following table. Checkpaling ‘Cheeks the speling of an objec. Clear Clears the entize object. ClearCommenis {Clears al cel comments om tbe specified range: learContents ‘Clears the formulas Som the range, ClearFormats Clears the formatting ofthe obec CleanNotes tas notes end seed ne Eo a ee a Ue oad ClearOutline Gens the outline for the cited Tange. ColumnDifveencey | REMES @ Range object that represents all the cells whose contents are different from the comparison ecll in each column. ‘Consolidates data from multiple ranges on multiple worksheets into | 4 single range on a single worksheet. Variant. ‘Copies the range to the specified range or to the Clipboard. Copies the contents oF > SFY ~- NWA B-—nAset object onto & worksheet, beginning at ine upps: ous. wvsine vt the specified range, CopyFromRecordset Tir he Recordset object contains fietas with OLE objects in them, 2 this method fails CopyPienure Copies the sefected object fo the Clipboard asa picture, Varin CreateNames reales names in the specified range, based on text labels in the on Guts the'‘oject to the Clipboard or pastes 1 into a opeeed destination. Dairies ‘Creates data series in the specified ange, Variant Delete Deletes ihe object Displays'a dialog box defined by a dialog box definition table ona DisiogBox Microsoft Excel 4.0 macro shee. Retums the number of the chosen control, or etums False ifthe user clicks the Cancel button. Diny Designafes a range to be recalculated when the next recalelalion occurs. “You have requested Help for a Visual Basic Keyword used only on the Macintosh. For information about this keyword, consult the EditionOptions language reference Help included with Microsoft Office Macintosh Eiition, TapowAcFixedFormar | Ie €ssepon fortis Rem Wil oppear in We Thal lease of Office 2007. a PEERS TECHNOLOGIES PVT LD, HYDERABAD . Page 73 Peers -VBA- Excel FillDown Fills down fom the top cell or cells in the specified range te the bottom of the range. The contents and formatting of the cell or cells in the top row of a range afe copied into the rest of the rows in the range. Fillet Fills left from the vightmast cell or cells inthe specified range. The ‘contents and formatting of the cell or cells in the rightmost column of a range are copied info the rest of the columns jn the range. FillRight Fills night from the leftmost cell or cells in the specified range. The contents and formatting of the cell or cells in the leftmost column of a range are copied into the rest of the columns in the range. ilUp Fills up ffom the bottom cell or cels in the specified range fo the top of the range. The contents and formatting of the cell or eels in the bottom row of a range are copied into the rest ofthe rows in the range. : Find Finds specific information in arange. FindNext ‘Continues a search that was begun with the Find method, Finds the next cell that matches those same conditions and returns a Range object that represents that cell. Docsn’t affect the selection or the active cell. FindPrevious ‘Continues a search that was begua with the Find method, Finds the previous cell that matches those same conditions and retums a ange objec tht represents that coll Doesn't fect the selection or the active cell. cn FuncfioaWizard ‘Starts the Function ‘Wizard for the upper-left cell of the range. a Gaeta "it Values necessary fo achieve a specific goal. If the | goal is an ammount ‘returned by a formula, this calculates a value that, ‘iin supple to your fommula, causes the formula to ream the ber you want Retums Tie ithe goal sek rcs vbject represents @ single cell in a PivotTeble Group { tic s usus range, the Group method performs numeric or date- | based grouping in that field. en “Inserts a cel or a range of cells into the worksheet or macro sheet and shifts other cells away 19 make space. Trsertindeat ‘Adds on indent to the specified sange. Tasty ‘Rearranges the text in a range go that i fills the range evenly. LisNames Pastes a list ofall nonhidden names onto the worksheet, beginning with the first cell in the range, Merge ‘Creates a merged cell from the specified Range Object. ‘Navigates a tracer arrow fer the specified range to the precedent, dependent, or etror-causing cell or cells. Selects the precedent, NovigateArow dependent, or error cells and retums a Range object tht represents the now selection, This method causes an error if it's applied to a cell without visible tracer arrows. ‘Retums or ses the cell note associated with the cell In We upper tet NoteText comer of the range. ReaWwrite String. Cell notes have been replaced by range comments. For more information, see the Comment object. Pane arses a range of data and breaks it into multiple cells, Distibutes the contents of the fange to fill several adjacent columns; the range er PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 74 Peers -VBA- Excel ES ‘can be no more then one column wide. PasteSpactal ‘asles 6 Range from the Clipboard into he specified range, PrintOut ‘Prints the object PrintPreview ‘Shows a preview of the object as it would look when printed. . ‘The description for this item will appear in the final release of RemoveDuplicates Office 2007, RemoveSubtotal Removes subtotals from a list. Retums a Boolean indicating characters in cells within the specified Replace range. Using this method doesn’t change cither the sclection or the active cell. 4 ‘Retums a Range object that represents all the cells whose contents RowDifferences are different fiom those ofthe compafigon cell in each row. Ron ‘Rubs the MicrosoR Exeel macro a this locaton. The range must ba on a macro sheet. Select Selects the object. ‘SetPhonetic Creates Phonetic objects forall the cells in the specified range. ‘Scrails through the contents of the active window to move the range Show >| into view. The range must consist of a single cell in the active document. ‘ShowDependents ‘Draws tracer arrows (o the direct dependents of the range: Show! ‘Draws tracer arrows through the precedents tree to the cell that’s the Errors source of the error, and returns the range that contains that ccll ShowPrecedents ‘Draws tracer arrows to the direct precedents of the range. ‘Sort The deseipfion fo dis Tem will appear in the final lease oF Office 2007. ** =" Uses East Aslan sonag Hittods To som Ua Tage, « POTTS SontSpocal report, or uses the method for the active region if the range contains only one cell Ear avamnte Iononece sorts in the order of the Kana syllabicy. Speak Causes the ces of tne singe to be spoken In Tow order or column order. Returns‘ Range object that represents all the cells that match the SpecialCells specified ypeand value. ‘You have requested Help for a Visual Basie keyword used only on subseribeTo the Macintosh. For information about this keyword, consult the language jeference Help included with Microsoft Office Macintosh Edition. Subtotal Creates subtotals for the range (or the current region, ifthe range is asinglecell). Table Creates a data table based on input values and formulas that you define on a worksheet, TextToCohumns ‘Parses 4 column of cells tht contain ext into several COhmns. Promotes a range in an outline (that is, decreases its outline level) Ungeon ‘The specified range must be a row or column, or a range of rows or rou ‘columns. If the range is in a PivotTable teport, this method ungroups the items contained in the range. Unierge ‘Separates a merged area into individual cells Properties —_—————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 75 i 3 Peers -VBA- Excel a ‘Name ‘Deseription AddIndent Retums or sets a Variant Value that indicates if text is automatically indented when the text alignment in a cell is set to equal distribution (either horizontally or vertically.) { Address Retums a String value that represents the range reference in the Tenguage of the macro. | AdaressLocal Returns the range reference for the specified range in the language ofthe user. Read-only String. | AllowEdit ‘Returns a Boolean value that Indicais ifthe range can be edited on a protected worksheet, Application ‘When used without an object qualifier, this property retums an Application object that represents the Microsoft Excel application, ‘When used with an object qualifier, this property retums an Application object that represents the creator of the specified ‘object (you can use this property with an OLE Automation object torepurn the applicstion of that abject). Read-only. Areas Retums an Areas collection that represents all the ranges in @ multiple-area selection, Read-only. Borders ‘Retums a Borders collection that represents the borders of a style or a range of cells (including a range defined as part of a conditional forma), . Colle Returns a Range object that represents the cells ja the specified range. Characters ‘Returns a Characters object that represents a range of characters ‘within the object text. You can use the Characters object to format ~ | characters within a tent string. Column iC: ee specified range. Rezd-only Lon; ‘Retums the number of the first column in the first area in the “sums a Range object that represents the columans ia the specified foe TRetums oF sels the width of alt columns in the specified range. Column Wid Read/write Variant, Comment ‘Returns a Comment object that represents the comment associated swith the cel in the upper-left corner of the range. Com ‘Retums a Long value that represents the number of objects in the | Co collection. ‘CountLarge Read-only Tf the speoified cell is part of an array, returns a Range object that Curenthay represen the entire array. Read-only. ‘Retums 2 Range object that represenis the current region. The CurentRegion cent region is a range bounded by any combination of blank rows and blank columns. Read-only. ‘Retums a Range object that represents the range containing all the Dependents dependents of a ceil. This can be a multiple selection (@ union of Range objects) if there's more than one dependent. Read-only Renge object. Returns a Range object that represents the range containing al he DiseotDependents _| direct dependents of a cell. This can be a multiple selection (a union of Range objects) if there's more than one depenident. Read- a RS PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 76 Peers -VBA- Excel only Range object. ‘Retums @ Range object that represents the range containing all the direct precedents ofa cell. This can bc a multiple selection (a union DirectPrecedents of Range objects) if there's more than one precedent. Read-only Range object, ‘Retums a Range object that represents the cell at the end of the End region that contains the souree range, Equivalent to pressing END+UP ARROW, END+DOWN ARROW, END+LEFT ARROW, or END+RIGHT ARROW. Read-only Range object. - ‘Retums a Range object that represenls the entire column (or EnfreColumn columas) that contains the specified range. Read-only, 5 ‘Returns a Rango objet that represen's the entze row (or rows) Ibat EnfrRow contains the specified range. Read-onl Enors Allows the user (oto aceess error checking opis. F Retoms a Font object that represents the font of the specified ont object. " ‘Retuins @ FormalCondiions colletion that vepreseats all the FormatConcitions | conditional formats forthe specified range. Read-only. Formula ‘Retums or sets a Variant value that represents the object's formula in Al-stle notation and inthe language of the macro. ‘Retums or sets the array formula of a range. Retums (or can be set to) a single formula or a Visual Basic array. If the specified range FormulaArray doesn't-confain an array formule, this property returns null Read/write Variant ‘Returns or sets a Variant value that indicates if the formula will be FormutaHfidden 55] pidden when the worksheet is protected, , ‘Returns or seis the formula for the object, using Al-style FormutaLocal | references in the fancuage of the user. Read/write Variant be t tee awa fe Uae FormulaR1C1 FormulaR1C Local notation in the language of the user. Read/write Variant, ‘True if the specified cell is part of an array formula, Read-oaly HasAmaye Variant, ‘True if all cells in the range contain formulas; False if none of the HasFormula cells'in the range contains 2 formula; wull otherwise. Read-only Variant. Retums or sels a Variant value that represenis (The height, in points, of the range. ‘Refuns or sets a Variant value that indicates if the xows or columns are hidden. HorizontalAlignment Retums or sels a Varint value that represenls the horizontal alignment forthe specified object. Hyperlinks ‘Returns a Hyperlinks collection that represents the hyperlinks for the range. ID Retums or sets a String value that represents the identifying label forthe specified cell when the page is saved as a Web page. IndentLevel Retums or sets a Variant value that represents the indent level for the cell or range, Can be an integer from 0 to 15. a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 77 Peers -VBA- Excel aS Ibterior Returns an Inferior object that represents the interior of the specified object ‘Retums a Range object that represenis a range at an offset to the Tem x specified range. uk Retums a Variant value (iat represents the distance in points, fom the let edge of column A to the left edge of the range. ListHeaderRows ee umber of header rows for the specified range. Read- ListObject Retums a ListObject object for the Range object. Read-only ListObject object. Refums a constant that describes the part of the Pivotfable report , that contains the upperlet comer of the specified range. Can be Tacationln able one of the following XWLocationlnTable. consianls, Read-only Los. Locked Retums or sets a Variant value that indicates if the object is locked. MDX Read-only TRetums a Range object that represents the merged range conlaining MergeArea the specified cell. Ifthe specified cell sn't in 8 merged range, this |, property returns the specified cell, Read-only Variant. | MerseCete “Tye ifthe ange contains merged cells, Read/urite Variant, Refums or suis a Variant vaiue tbat xepresents the name of the Nome object. Naw Rehims a Rage objeat thal represents the nox all ‘NumberFormat ‘Retums oF sets. g°Variht value that represents the format code for ci the ob 7 Gf Retums oes a Variant value that represents the format code for NonbesFormattecl | ie bier esting nthe language of heuer, Dike ‘Retums a Range object that represents a range that's offset Grom ‘the specified range. |.Ynentauon [Returns or sets a Variant value that represents the text orientation, ‘Returns or sets ihe current outline level of the specified row «| ‘OutlineLevel ‘column, Re: rite Variant. ‘Renums or sets the location of a page break. Can be one of the PageBreak following XiPageBreak constants: xlPageBreakAutoma xlPageBreak Manus}, or xiPageBreakNone, Read/ write Long. Parent contains information about @ Phonetic | specific phonetic text string in a cell. Phonetics ‘Retums the Phonetics collection of the range. Read only, PivotCell Rens 2 PivolCell object that represents a cell in a PivotTable PivolField Retums @ PivotField object that represents the PivotTable field containing the upper-left comer of the specified range. Pivotliem Retums a Pivotltem object that represents the PivotTable item ‘containing the upper-left comer of the specified range. PivotTable Retums a PivorTable object that represents the PivotTable report containing the upper-left comes of the specified range. ?. ‘Returns a Range object that represents all the precedents of cell This can be a multiple selection (a union of Range objects) if ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 78 Peers -VBA- Excel 7 tiere's more than one presedent Read-only. PrelixCharacler Returns the prefix character for the eel. Read-only Variant. Provious ‘Returns a Range object that represents the nent cell Retums a QueryTable object that represents the query table that QueryTable intersects the specified Range object. Pe 9 Range Returns a Range object hat represents a cell Ora range af calls, ‘Returns or sets th reading order for the specified object. Can be ReadingOrder one of the following constants: xIRTL (ight-o-le), xILTR (left- tocright), of IContext. Read/rite Long Rube esas tie pci ge Roki Rang ajea a ess the resized range. z Returns the number of he Hist ow of fhe Tit area In The Tange. ow Read-only Lon; ead-only Long, ‘Returns the height oF all the rows In he range specified, meanured Rowlleight in points, Retums null if the cows in the specified range aren't al the same beight, Readtwrte Variant. toms Retums a Range object that represents Th rows ia Whe specTied range. Read-only Range object SenerA ction Read-only “True if the oulline s expanded for the specified range Go that the etal ofthe column or row is visible). The specified range must be ShowDeta a single summaty column or row in an ovine. Read/write Variant. For the Fvolltem object or the Range object ifthe range isin PivotTable repon), (his property is set to True if the item «= bshowing detail Shrink TOF 7 ___| Retums ot sets a Variant value iat indicates. SmarTap3 [Reus ¢ Smuctaps object eewesning te Haier er Te om “* - s-wpsty should bat be used. Sound noles have been removed | SoundNote { trom Microsoft Excel soe Retuins or sels u Variant value, containing @ Style object, Wat ropreseats the style ofthe specified range. 3 “True if the range is an oullining summary Yow or colonia. The summary range should be a row or a column. Read-only Variant. Text ‘Retums or sets the ext forthe specified object. Read-only Sting. T Refunga Variant value that represents the distance, n points, from op the top edge of row J to the top edge of the range. Tine if the row height of the Range object equals the standard Aight of the sheet Retams Nall ifthe range contains more than ‘UseStandardtlcight | gre sowy and the rows aren't all the same height. Read/urite Vasant “True ifthe column width of the Range object equals he sandard , width ofthe sheet. Retums null ifthe range contains more than one UseStandardWidth —fcofumn and the columus aren't all the same width. Read/wnite Variant > Retums the Validation object that represents data validation forthe Validation specified range. Read-only. vane Relumns of sels @ Varian! value What represeats the value of the spovifiedrange. ooo PRERS TECHNOLOGIES PVT LTD, HYDERABAD Page 79 Peers -VBA- Excel EES Vatue2 Returns or sets the cell value. Read/write Variant. a Returns or sets a Variant value that represents the vertical Vericalalignment | slignment ofthe specified object = Width Returns a Variant value that represents the width, in points, of the rae. Worksheet ‘Retums a Worksheet object that represents the worksheet ‘containing the specified range. Read-only. ‘WeapText Retums or sets a Variant value that indicates if Microsoft Excel ‘wraps the text in the object. Returns an XPath object that represents the Xpath of the element XPath mapped to the specified Range object. ‘The context of the range determines whether or not the action suoceéds or returns an empty - object. Read-only. Controts, Dialog Boxes, and Forms How to: Add Controls toa Dacument a To add controls to a document, display the Control Toolbox, click the control you want to add, and then click on the document. Drag an adjustment handle of the control until the control's culline is the size and shape you want, Note Dragging a conttal, or a muraber of "grouped" cdntrols from the form back to the Contkol Toolbox creates a template of the controls, which can be reused. This is a useful feature for implementing a standard interface for your applications. ‘How to: Add Controls to'a User Form To add controls to a'user form, find the control you want to add in the Toolbox, drag the control onio the form, and then drag-an adjustment handle on the control until the control's outline isthe size and shape you want. Noe _Sregging a control, or a number of "grouped" controls from the form back to the Toolbox creates a template of the controls, which can be reused. This is a useful feature for ~ implementing a standard interface for your applications. ‘After you have added controls to the form, use the commands on the Format menu in the ‘Visual Basic Editor to adjust the control alignment and spacing. How to: Create a Custom Dislog Box ‘Use the following procedure to create a custom dialog box: 1. Create a User Form (On the Insert menu in the Visual Basic Editor, click UserForm. 2. Add Controls to User Form Find the control you want to add in the Toolbox and drag the control onto the form. 3. Setting Control Properties Right-click a contiat in design mode and click Properties to display the Properties window. 4. Initializing Control Properties ‘You can initialize controls in a procedure before you show a fort, or You can add code to the Initialize event ofthe form. 5. Control and Dialog Box Events PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 80 Peers -VBA- Excel All controls have a predefined set of events. For example, a command button has a Click ‘event that occurs when the user clicks the command button, You can write event procedures that ron when the events occur, 6, Displaying a Custom Dialog Box Use the Show methed to display a UserForm, 7, Using Control Values While Code Is Running Some properties can be set at run time. Changes made to the dialog box by the user are lost ‘when the dialog box is closed. ‘How to: Create a User Form To create a custom dialog box, you must create a UserForm. To create a UserForm, click UserForm on the Insert menu in the Visual Basic Editor. 3? see Use the Properties window to change the name, behavior, aiid appearance of the form. For example, to change the caption ona form, set the Caption property. Displaying a Custom Dialog Box To test your dialog box in the Visual Basic Editor, click Run Sub/UserForm on the Run menu in the Visual Basic Editor. To display a dialog box ffom Visual Basic, use the Show method, The following example displays the dialog box named UserForm|_ Private Sub GetUserNameQ + ‘UserForm|.Show End Sub ‘How to: Add. cares ver Form To add controls to a use? form, find the control you want 10 edd in the Toolbox, drag the . and then drag an adjustment handle on the contro! until the control's ovclme 5 we size and shape you wast. Note Dragging a control, or a number of “grouped” controls fiom the form back to the Toolbox creates a template of the conttols, which can be seused, This is a useful feature for implementing a standard interface for your applications. ‘After you have added controls to the form, use the commands on the Format menu in the Visual Basic Editor to adjust the control clignment and spacing. Initializing Control Properties You can initialize controls at runtime by using Visual Basic code in a macro, For example, ‘you could fila list box, sebtext values, or set option buttons. ‘The following example uses the Additem method to add data to a list box. Then it sets the value of a text box and displays the form, Private Sub GetUsetName() With UserFornt -AstRegions.Addltem "North" ‘AstRegions.A déltem "South -IstRegions Addltem "East" PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 81 Peers -VBA- Excel {otRegions.Adéltem "West" .fxtSalesPersonID. Text = "00000" Show End With Bnd Sub ‘You can also use code in the Initialize event ofa form to set inital values for controls on the form. An advantage to setting initial control values in the Initialize event is that the initialization code stays with the form. You can copy the form to another project, and when you run the Show method to display the dialog box, the controls will be initialized. Private Sub UserForm Initiatize) UserForml JstNames,Addlters "Test One" ‘UsecForml JstNames.Addltem "Test Two" UserForm] txtUserName.Text = "Default Name" End Sub Setting Control Properties ‘You can set some control properties at design time (before any macro is running). In design ‘mode, right-click a control and click Properties to display the Properties window. Property names are shovn in tbe left column in the window, and property values are shown in the right column. You set a property value by entering the new value to the right of the property name. ape Using ActiveX Controtg on Sheets ‘This topic covers specific-information abut usitig ActiveX controls on worksheets and chart sheets, For general-informiation on adding and working with controls, see Using ActiveX ‘Controls on a Dacument ang Creating a Costom Dialog Box. Keep the following points in mind wien you are working with controls on sheets: » In addition to the ‘standard properties available for ActiveX controls, the following properties can be used with Activex controle in Microsoft Excel: BottomRighiCell, LinkedCell, ListFillRange, Placement, PrintObject, TopLeRCell, and ZOrder. ‘These properties can be set and Teturned using the ActiveX control name. The following, example serolls the workbook window so CommandBution! js in the upper-eft conser. Sett= Sheet CommandButton}-Taph.etCell With ActiveWindow x ScrollRow = Row : ‘ScroliColumn=tColuma End With * Some Microsoft Excel Visual Basic methods and properties are disabled when an ActiveX control is activated. For example, the Sort method cannot be used when a control is active, so the following code fails in a button click event procedure (because the contol is sil active after the user licks it). Private Sub CommandButtonl Click Range(“al:a10") Son Keyl=Range(‘aI") End Sub —————————— ‘PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 82 Peers -VBA- Excel i © You can work around this problem by activating some other element on the sheet before you use the property or method that failed. For example, the following code sorts the range: Private Sub CommandButton] Click Renge("al").Activate ‘Range(“al:al0"),Sort Keyl:=Range("al") CommandButtonl Activate End Sub + Controls on a Microsoft Excel workbook embeddéd in a document in another application will not work if the user double-clicks the Workbook to edit it. The controls will work if the user right-clicks the workbook and selects the Open command from the shorteut menu, te + When a Microsoft Excel workbook is saved uising the Microsoft Exeel 5,0/95 ‘Workbook file format, ActiveX control information is lost, : + The Me keyword in an event procedure for an ActiveX control on a shect ‘refers to the sheet, not to the control, ‘Adding Controls with Visual Basic In Microsoft Excel, ActiveX controls ‘arc represented by OLEObject objects in the OLEObjects collection (all OLEObject objects are also in the Shapes collection). To programmatically add an ActiveX control to a shect, use the Add method of the OLEObjects collection, The following example adds 2 command button to worksheet I. Worksheets(1). OLBObjects. Add "Forms.CommanéButton.1", Lefi=10, Top=10, Height:o20, Width:=100 Using Control Properties with Visual Basic sions ves en, your Visual Basic code will refer to ActiveX controls by name. The following ‘example changes the caption on the control named "CommandButton!. Sheei| CommandButton! Caption = "Run" Note that when you use a control name outside the class module for the sheet containing the control, you niust qualify the control name with the sheet name. ‘To change the control name you use in Visual Basic code, select the control and set the (Name) property in the Properties window. Because ActiveX controls arc also represented by OLEObject objects in the OLEObjects collection, you can set control properties using the objects in the collection. The following example seis the left postion of the control named "CommandButton1." Worksheets(1),OLEObjects("CommandButton!*) Left= 10 Control properties that are not shown as properties of the OLEObject object ean be set by returning the actval control object using the Object property. The following example sels the caption for CommandButton!. ‘Worksheets(1) OLEObjects("CommandButton!" Object.Caption = "run me" a PEERS TECHNOLOGIES FVT LTD, HYDERABAD Page 63 Peers -VBA- Excel Because all OLE objects are also members of the Shapes collection, you can use the collection to set propenties for several controls. The foltowing example aligns the left edge of all controls on workshect 1. For Each s In Worksheets(1).Shapes Ifs:Type = msoOLEControlObject Thea sLeR = 10 Next Using Control Names with the Shapes and OLEObjects Collections ‘An ActiveX control on a sheet has two names: the name of the shape that contsins the ‘control, which you can see in the Name box when you view the sheet, and the code mame for the control, which you can see in the cell to the right of (Name) in the Propertics window. ‘When you first add a control to a sheet, the shape name and code name match, However, if you change either the shape name or code name, the other is not automatically changed to match. : “You use the code name ofa contol in the names of its event procedures. However, when you retum a control from the Shapes or OLEObjects colfection for a sheet, you must use the shape name, not the code name, to reler to the conttol by same, For example, assume that you add a check box 1o a sheet and that Both the default shape name and the default code ame are CheckBoxt. If you then change the control code mame by typing chkFinished next to (Name) in the Properties window, you must use chkFinished in event procedure names, butsyau still have to use CheckBoxi to return the control from the Shapes or OLEObject allegtion ‘as shown in the following example. Be “egies ea Private Sub chiinisited Chick“: ActiveSheet. OLEObjects(*CheckBaxl"). Object. Value = | End Sub . Using Control Values While Code Is Running Some cantzol properties can be set and retumed while Visual Basic code is running. The following example sets the Text property ofa text box to "Hello." ‘TextBoxl.Text= "Hello" ‘The data entered on a form by a uset is lost whea the form is closed. If you retum the values of controls on a form after the form has been unloaded, you get the iniisl values for the controls rather than the values the user entered. If you want t6 save the data entered on a form, you can save the information to module-level variables while the form is stillronning, The following example displays a form and saves the form data. "Code in module to declare public variables. Public strRegion As String Public intSolesPersonID As Integer Public blaCancelled As Boolean * Code in form, Private Sub cmdCancel_Click() Module] binCancelled = True CD PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 84 Peers -VBA- Excel EE Unload Me > End Sub Private Sub omdOK_Click() * Save data, {ntSalesPersonID = txiSalesPersonID. Text stiRegion = tstRegions.List(Is(Regions ListIndex) ‘Modufel binCancelled = False Unload Me End Sub Private Sub UsetForm_jnitialize() Module! .binCancelled = True End Sub " Code in module te display form. Sub LaunchSalesPersonForm( : fimSalesPeople Show hes, IfbInCancelled = True Then ‘MsgBox “Operation Cancelled!", vbExclamation Else MsgBox "The Salesperson's Dis: "8 2.) ’ intSalesPersonID & - "The Region is: " & ane EndIf In Microsoft Excel, yoti'can saves workbook, worksheet, chart, range, query (able, PivorTable report, print aréa, or AvloFilter range to a Web page. You can also edit HTML file directly in Excel, Saving a Document as a Web Page Saving a documeat as a Web page isthe proces of creating and saving an HTML file and any supporting files. To do this, use the SaveAs method, as shown inthe following example, ‘which saves the active workbook as C:\Reports\myfile.htm. 4 ‘ActiveWorkbookSaveas © 1s Filerame:="C\Reports\nle hn’ FileFormat=x]HTML Customizing the Web Page ‘You can customize the appearance, content, browser support, editing support, graphios formas, screen resolution, file organization, and encoding of the HTML document by setting ‘properties of the DefaultWebOptions object and the WebOptions cbject. The DefaultWebOptions object contains application-level properties. ‘These seltings are overridden by any workbook-level property seitings that have the same names (these are contained in the WebOptions abject). ‘After setting the attributes, you can use the Publish method to save the workbook, worksheet, char, range, query table, PivotTable report, print area, or AutoFiller range to a Web page. ‘The following example sets various application-level propertics and then sels the AllowPNG "TECHNOLOGIES PVT LTD, HYDERABAD Page 8S Peers -VBA- Excel property of the active workbook, overriding the application-level default setting. Finally, the ‘example saves the range as "CAReports\1998_QUhtim." With Application Default WebOptions RelyonVML= Tre -AllowPNG = True -PixelsPerlnch =96 ‘End With ‘With ActiveWorkbook WebOptions.Allow?NG = False ‘With PublishObjects(1) FileName = "C:\Reports\1998_Qi.htm" Publish End With End With You can also save the files directly to a Wob server. The following example saves a range to a Web server, giving the Web” page the URL address ‘ttp:example homepage.com/annualreport him. : . With ActiveWorkbook . f With WebOptions = ‘RelyonVML= Te” -PixelsPerloch = 96 End With mack With PublishQbjects( I) FileName = _ we “hitpsvexample-homepags 5 Publish 2 ‘End With End With Opening an HTML Docum To edit an HTML document in Excel, fist open the document by using the Open method, The following example opens the file "C:\Reports\1997_Q4 htm’ for editing, Workbooks Open Filename="C\Reports\1997_Q4.himn" ° ‘After opening the file, you can.ctistomize the appearance, content, browser support, editing ‘support, graphics formatsy-screen resolution, fite argenizetion, and encoding of the HTML document by seiting properties of the DefaultWebOptions and WebOptione objects, ‘Visual Basie Concoptual Topics Using Arrays ‘You can declare an array to work with a set of values of the same data typo. An uray is a single variable with many compartments to store values, while atypical variable has only one storage compartment in which it can store only one value, Refer tothe array as a whole when you Want to refer to all the values it holds, or you can refer to its individual elements. aed PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 86 Peers -VBA- Excel eee For example, to store daily expenses for each day of the year, you can declare one array variable with 365 olements, rather than declaring 365 variables. Each element in an array contains one value. The following statement declares the array variable ‘cuExpense with 365 elements, By default, an array is indexed beginning with zero, so the upper bound of the array is 364 rather than 365. Dim curExpense(364) As Currency Re To sct the value of an individual element, you specify the element's index. The following example assigns an initial value of 20 o each element in the aay. Sub FillAcrayO Dim curExpense(364) As Currency Dim intl As Integer . Forintl = 0 to 364 ‘curExpense(int) = 20 Next End Sub mk Changing the Lower Bound = ‘You can use the Option Bas¢ siatément at tfc top of a module to change the default index of the ficst clement from. 0 1. In ng lowing. example, the Option Base sgment changes the index for the frst el im statement declares the array variable ‘eurBxpense with 365 elements. Option Base t Dim curBxpense(365) As Currency ‘You can also explicitly st the lower bound of an anay by using a To clause, as shown inthe ‘following example. es ‘Dim curExpense(1 To 365) As Currency > Dim str Weekday(7 To 13) As String Storing Variant Values in Arfays There are two ways to create arrays of Variant values. One way is to declare on array of ‘Variant data type, as shown in the following example, Dim varData(3) As Variant vvarData(0) = "Claudia Bendel" varData(1) = "4242 Maple Blvd” varData(2) = 38 varData(3) = Format("06-09-1952", "General Date") SS ee PEERS TECHNOLOGIES PVT LTD, 11YDERABAD ‘Page 87 xcel Peers VB: ‘The other way is fo assign the array returned by the Array function to a Variant variable, as shown in the folowing example. Dim varData As Variant varData = Array("Ron Bendel", "4242 Maple Blvd", 38, __ Fosmat("06-09-1952", "General Date")) ‘You identify the elements in an array of Variant values by index, no matter which technique ‘you use to ereate the array. For example, the following statement can be added to either of the preceding examples. (& MsgBox "Data for” & varData(0) & "has been recorded.” 2 Using Multidimensional Airays In Visual Basic, you can declare arrays with up to 60 dimensions. For‘example, the following statement declares a 2-dimensional, 5-by-10 array. . Dim sngMulti(1 To 5, i To 10) As Single Tf yoo think of the array as a matrix, the frst argument represents the rows and the second ‘argument represents the columns, - Use nested For.-Next stglements to, process multidimensional arays. The following’ Poel ils r-cinnal apy Wi Sige vale Sub FillArrayMtultifs Dinn intl As Inter, int"As Integer Dim sngMulli(I To 5, 1 To, 10) As Single Fill array with values. For intl=1To5 For ind = i To 10 sogMliint, int) = int * itd Debug Print sagMliind, int) Nest int} Next inti End Sub ‘Writing Visual Basie Statements A statement in Visual Basic is a complete instruction. I can contain keywords, operators, variables, constants, and expressiins. Each statement belongs to one of the following three categories: eo + Declaration statements, which name a variable, constant, or procedure ‘and can also specify a data type. Writing Declaration Statements * Assignment statements, which assign a value or expression to a variable oF constant. ‘Writing Assignment Statements ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 88 Peers -VBA- Excel eee + Executable statements, which initiate actions. These statements can execute a method or function, and they can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators. ‘Writing Executable Statements Continuing a Statement over Multiple Lines A statement usually Sts on one line, but you can continue a stalement onto the next line using a line-continvation character, In the following example, the MsgBox executable statement is continued over three lines. Sub DemoBox() "This procedure declares a string variable, * assigns it the value Claudia, and then displays * a concatenated message, Dim myVar As Sting myVer= "John! MsgBox Prompt="Hello " & myVar, _ - Tille:="Greeting Box", ‘Buttons:=vbExclam: End Sub Adding Comments Comments can explain a ae ora pata instruction to anyone reading your code, ‘Visual Basic ignores ‘congnent iy fen it runs } ‘your procedures. Comuncnt lines begin with an. apostrophe () or with Retp followed by a\$pacé, and canbe-added anywhere in.a procedure. To add a comment to, Tine asa an, insert an apostrophe after the statement, followed by the‘commeal® Ey ett eomments are displayed as green text. Checking Syntax a: Ifyou press ENTER aller typing a line of code and the line is displayed in red (an error message may display as well), you must find out what's wrong with your statement, and then comect it ee Writing Executable Statements ‘An executable statement initiates detion. It can execute 2 method or function, and it can loop or branch through blocks of code.!Executable statements often contain mathematical or conditional operators. The following example uses a For Bach,.Net statement to iterate through each callin a range named. ‘MyRange sone on Sheet! of an active Microsoft Excel workbook. The variable c isa cell in the collection of cells contained in MyRange ‘Sub ApplyFormatQ) re PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 89 Peers -VBA- Excel Const limit As Integer = 33 For Each c In Worksheets("Sheet]"),Range("MyRange").Celis WeValue> limit Then With Font Bold= True Attic = Trae End With End if Nexto MsgBox "AN done!* End Sub Bes The If..Theo..Bise statement in the example checks the value Of the cell. If the value is ipeater than 3, the With statement sts the Bold and Talc fropertes ofthe Font object for hat cel. If...Then...se statements end with End If. “The With statement can save typing because the statements it contains se avtomatically ‘executed on the object following the With keyword, ‘The Next statement calls the next cell in the colle ‘MyRange A Sub procedure is a series'of Visi slalements that performs actions but doesn't retura a value, A Sub procedure can take arguments, such 2s constants, Vasiables, or expressions that are passed by a calling procedure. If a Sub procedure has no oe ents, the Sub statment must include an empty set of pareatheses. The following Sub procedure has comments explaining each line, "Declares a procedure named Gethifo “This Sub procedare takes no arguments Sub Gelato) "Declares sting variable names! answer Dim answer As Sting " Assigns the zetum value of the TopulBox function to answer answer = laputBox(Prompts="What is your name") * Conditional I. Then.-Else statement Afanswer = Empty Then * Calls he MsgBox function MsgBox Prompt="You did not enter a name.” Else * MsgBox function concatenated with the variable answer MsgBox Prompt="Your name is" & answer nr PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 50 Peers -VBA- Excel SS eee " Ends the If. Then...Else statement EndIf "Ends the Sub procedure End Sub Writing a Funetion Procedyre A Function procedure is a series of Visual Basic statements enclosed by the Function and End Funetion statements, A Function procedure is similar to a Sub procedure, but a function can also retum @ value. A Fonction procedure can take arguments, such as constants, variables, or expressions that are passed to it by a calling procedure. If a Function procedure has no arguments, its Function statement must include an empty set of pareatheses. A. function returns a value by assigning a value to its name in,bne or inore statements of the procedure. s In the following example, the Celsius function calculates ‘degrees Celsis from degrees Fahrenheit, When the function is called from the Main procedure, a variable conlaining the argument value is passed to the function, The result of the calculation is retumed to the calling procedure and displayed in a message box. ‘Sub Maing, temp = Application InputBox(Prompt= _ "Please enter the temperature in degrees F.", Type:=1) MsgBox "The tempers * & Celsius teip)& " depres .* End Sub ‘ Function CeleuatDeptdl Celsius = (Degrees -32) 25/9 Understanding Visual Basie Syntax The syntax in a Visual Basic Help topic for a method, statement, or function sizows all the elements necessary fo use the niethod, statement, or function correctly. The examples in this topic explain how to interpret the most common syatax elements, Activate Method Syntax : object Activate In the Activate method syntax, the italic word “object is a placeholder for information you supply — in this case, code that returns an object. Words that are bold should be typed exactly as they appear. For example, the following procedure activates the second window in the active document. Sub Makeactived) Windows(2) Activate End Sub MsgBox Function Syntax MsgBox(promp{f buttons], itl} [,helpfile, context) In the MsgBox function syntax, the bold italic words are named arguments of the function. Arguments enclosed in brackets are optional, (Do not type the brackets in your Visual Basic code.) For the MsgBox function, the only argument you must provide is the text for the prompt. ne PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 91 Peers ~VBA- Excel a Arguments for functions and methods can be specified in code either by position or by name. To specify arguments by position, follow the order presented in the syntax, separating cach argument with a comma, for example: ‘MsgBox "Your answer is comrect!",0,""Answer Box" an argument by name, use the argument name followed by a colon and an equal To speci ‘nd the argumesi's value, You can specify named arguments in any order, for sign example: ‘MsgBox Title=" Answer Box, Prompt~"Your answer is comet! ss “The syntax for fonctions and some methods shows she argomenis enclosed in parentheses. ‘These functions and methods return values, so you must enclose the arguments in parentheses to assiga the vatue to a variable. If you ignore the return value or if you don't pass arguments at all, don’t include the parentheses. Methods that don't return values do not need their arguments enclosed in parentheses, These guidelines apply whether you're using positional arguments or named arguments. In the following example, the return value ftom the MsgBox function is a number indicating the selected button that is siored in the variable mnyVar wend enjoy tay job.", _ Title;="Answer Box", Buttons="4") MsgBox myVar End Sud “ Option Statement Syntax Option Compare {Binary | Text | Database | 1 the Option Compare statement syntax, the braces and vertical bar indicate a mandatory choice between three items. (Do fit type the braces ia the Visual Basic statemen!). For example, the following statement specifies that within the module, strings will be compared ‘ina sort orderthat is not case-sensitjye. ‘Option Compare Text ‘Dim Statement Syntax + Dim vamame(({subseripts)] [As type] [, varamef(fsubscripts)] [As typel] ... In the Dim statement syntax, the word Dim is a required keyword. The only required element is varname (the variable name). For exansple, the following statement creates three variables: myVar nexiVar sand ee ey ‘PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 92 Peers -VBA- Excel ————————— thirdVar ‘These are automatically declared as Variant variables. Dim myVor, nextVar, thirdVar The following example declares a variable as a String, Including a data type saves memory and can help you find errors in your code. Dim myAnswer As Sting, To declare several variables in one statement, include the data! type for each variable. ‘Variables declared without a datatype are automatically declared a¢:Variant. Dimx As Integer, y As Integer, 2 As Integer Inthe following statement, is assigned the Integey dl S type.” Dim, y,z As InfseR If you are declaring an’ “atta variable, you must include parentheses. The subscripts are optional. The following statement dimensions a dynamic array, Assignment statements assign a value or expression to a variable or constant Assignment statements always include an equal sign (=). The following example assign the retum value of the InpotBox function to the variable ‘yourName 2 Sub Question) # ‘Dim yourName As String == ‘yourName = InputBox(”What is your name?") ‘MogBox "Your name is" & yourName End Sub ‘The Let statement is optional and is usually omitted. For example, the preceding assignment statement can be written: Let yourName = InputBox("What is your name?"). ———— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 93 Peers -VBA- Excel ‘The Set statement is used to assign an object to a variable that has been declared as an object. ‘The Set Keyword is required. In the following example, the Set statement assigns a range on Sheet! to the object variable ‘myCell Sub ApplyFormatQ) Dim myCell As Range Set myCell = Worksheets(’Sheet!") Range("AL") With myCell Font Bold = True Malic = True End With End Sub E Statements thot set property values are also assignment statements. The following example sets the Bold property of the Font object forthe active cell AstiveCell.Font.Bold = True Font Object, Bold, Halic, Size, StrkeThcugh, Usderline, Weight Properties Example The following example demonstrates 4 Font dbject and the Bold, Italic, Size, StrikeThrough, ‘Underline, and Weight properties related to fonts. You can manipulate font properties of an object directly or by wsing an afias, as this example also shows, To use this example, copy this sample code to the Declarations patie doo Make sure that the form contains: + A Label named Labell. © Four ToggleButton controls named “ToggleBution! through ‘ToggleButtond, * Asecond Label and a TextBox named Label2 and TextBox!. Dim MyFont As StdFoat S Private Sub TogeleButton!_Click() If TogeleButtoni. Value = True Then MyFontBold=Tiue 7” "Using MyFont alias to control font ‘ToggleButton! Caption = "Bold On” ‘MyFont Size = 22 “Increase the font size Else MyFont Bold = False ‘ToggleButton! Caption = “Bold Off MyFout Size = ‘Retum font size to initial size ———— PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 94 Peers -VBA- Excel End If Ton Box!-Toat= Str(MyFont Weigh) "Bold and Weight are related End Sub Private Sub ToggleButton2_Click() If ToggleButton2, Value ~ True Then Label{.FontIalic = True ‘Using Labell Font directly ‘ToggleButton2.Caption = "Italie On" Else Label! Font.Italic = False Private Sub ToggleButton3_Click() If ToggleButton3, Value = True Then ‘Label! Font.Strikethrough = True “Using Labeil Font directly ‘ToggleButton3. Caption = "StrikeThrough On” Else = ook Labell Font Stikeihrough= False | ToggleButton3.Caption = StrikeThrough Off "Using MyFont alias for Labell. Font ‘ToggleButton4.Caption = "Underline On" Ebe Labell Font Underline = False ‘ToggleButton4.Caption = "Under Endlf End Sub je OFF" Private Sub UsesForm Initialize) ‘Set MyFont = Labell Font TogeleButton|.Caption ="Bold On” Labe!l AutoSize = True 'Set size of Labell Labell.AutoSize = False ToggleButton2, Value = False ToggleButton2.Ception = "alie Off" ‘ToggleButton3. Value = False ‘ToggleButton3.Caption = "StrikeThrough Off" — PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 95 Peers -VBA- Excel RN ToggleBiutton4. Vatue = False ‘TopgleButton4.Caption = "Underline Of" Label2.Caption = "Font Weight" ‘TextBoxl.Text = Str(Labell Font, Weight) ‘TextBox! Enabled = False End Sub PormatConditions Object ‘Represents the collection of conditional formats for a single range ‘Remarks ‘The FormatConditions collection can contain multiple conditional formats. Bach format is represented by a FormatCondition object. : For more information about conditional formats, see the FormatCondition object. ‘Use the FormatConditions property to retum a FormatConditions object. Use the Add method to create ¢ new condional fommat, sad wie the Modity method 19 change an existing ‘Visual Basie for Applications "2." ‘With Worksheets(1)-Range("el: Add(xICell Value, xIGreater, "=$a81") With Borders .LineStyle = x!Continuous Weight = xIThin Colorindex = 6 End With . ‘With Font : Bold = Tine Cooriader = 3 End With ‘End With ‘LBound Fanction 2 ‘Retums a Long containing the smallest available subscript for the indicated dimension of an array. Syntax ‘LBound(arrayname(, dimension)) ‘The LBound finction syntax has these pats [Part [Description [evan Required. Name of the array variable, follows standard variable naming conventions. PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 96 Peers -VBA- Excel ‘Gimension | Optional; Variant (Long). Whole number indicating which dimension’s lower ‘bound is retumed. Use | for the first dimension, 2 for the second, and so on. If dimensioa is omitted, 1 is assumed. Remarks ‘The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension, ‘LBound retums the values in the following table for an array with the following dimensions: Dim A( To 100, 0 To 3, -3 To 4) ‘Statement ‘LBound(A, 1 TBound(A, 2) LBound(A, 3) 3 . ‘The default lower tound for any dimension is either 0 or 1, depending’ on the setting of the Option Base statement, The base of an array created with the Array function is zero; it is unaffected by Option Base Arrays for which dimensions are sot using the To clause in a Dim, Private, Public, ReDim, or Static statement can have, as.a lowet bound. Example : UB ed ‘This example uses the LBound function to determine the smallest available subscript for the indicated dimension of an array. Use the Option Base statement to override the default base array subscript value of 0. Dim Lower Dim MyArray(I To 10, 5 To 15, 10 To 20) Declare array variables. Dim AnyArray(10) Lower = Lbound(MyArray, 1) "Returns 1. ‘Lower = Lbound(MyArmay, 3)'Refims 10. Lower Lbound(AnyArray)' Retuns 0 or 1, depending on " setting of Option Base. UBound Function Retums a Long containing the largest available subscript for the indicated dimension of an amy. ee Syntax ‘UBound(arraynamef, dimension]) ‘The UBound function syntax has these parts: Fart ‘Description amayzame (Required. Name of the array variable; follows standard variable naming conventions. ‘Gimension | Oplionat; Variant (Cong). Whole number indicating which dimension’s ——————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page9? Peers -VBA- Excel ‘upper Bound is refurned. Use | for the first dimension, 2 for the second, and 50 on. If dimension is omitted, 1 is assumed. Remarks ‘The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension. ‘UBound returns the following values for an aray with these dimensions: Dim A(I To 100, 0 To 3, -3 To) ‘Statement > Retorn Value” ‘UBound(a, 1 109) 3 (A, 2) 3) 4 Example This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array, Dim Upper Dim MyArray(t To 10, 5 To | Dim AnyAsray(10)_ PivotTableSourceData Property Returns the data source for the Pavr# Variant, ar ihe following table, Read-write Syntax expression SovreeData expression A variable that represeils a PivotTable object. Remarks Sal Data source {Reta value. “Microsoft Excel fistor database | The cell reference, a text External data source ‘An array. Each row consists of an SQL connection st if with the rematning elements asthe query string, broken _£" | down into 255-characier segments, ‘Multiple consolidation anges | A two-dimensional array. Each row eonsisis of @ reference and its associated page field items. ‘Another PivotTable report ‘One of the above three kinds of information. ‘This property is not available for OLE DB data sources. Example Assume that you used an extemal data source to create a PivotTable report on Sheet!. This example inseits the SQH. connection string and query string into a new worksheet. tT PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 98 Peers -VBA- Excel a Visual Baste for Applications Set newSheet = AcliveWorkbook Worksheets Add sdArray = Worksheets("Shectl").UsedRange.PivotTable,SourceData For i= LBound(sdArray) To UBound(sdArray) newSheet.Cells(i, 1) = sdArray() Nexti ‘Len Function Relums a Long contsining the mumber of characters in a string or the number of bytes required to store a variable, Syntax Len(string | varname) ‘The Len function syntax has these pans: Part Deseription string ‘Any valid sting expression, Irstting containg Null, Null returned ‘Vamamne ‘Any valid variable name, if varname contains Null, Noll is returned. IF ‘varname is a Variant, Len treas it the same as a Sting and always retums the number of characters it contains. Remarks One (aad only one) of th, tivo possible argurients must be specified. With user-defined types, Len retoms the size as “e" be written (pte file. “eka! Note PE Use the Len fnction ih byte dla contained ina string, asin double byte charter st number of bytes used to represent that string. With use memory size, including any padding between elements. For so the second example in the example topic. Note Len may not be able to determine fe actual number of storage bytes required when used with variable-length strings in er digg data types. Example ‘The frst example uses Lento rohit the umber of characters in a sting or the amber of bytes required to store a variable. The Type. .End Type block defining CostomerRecord J rust be preceded by the:Kefivord Private if it appéars in a class module. In a standard module, « Type statement can be Public. ‘Type CustomerRecord" Define user-defined type. ID As integer Place this definition in a Name As String * 10" standard module, ‘Address As String * 30 End Type Dim Customer As CustomerRecord Declare variables. ‘Dim Mylat As Integer, MyCur As Currency re te PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 99 Peers -VBA- Excel ‘Dim MyString, MyLen ‘MyString ~ "Tiello World" 'Intinlize variable. ‘MyLen=Len(Myini)' Returns 2. ‘MyLen = Len(Customer) ' Retums 42 MyLen = Len(MyString) ‘Returns 11. MyLen = Len(MyCu) "Retums 8. ‘The second example uses LenB and a user-defined function (LenMbes) to return the number of byte characters in a string if ANSI is used to represent the string. Function LenMbes (ByVal str as String) ‘LenMbes = LenB(StConv(str, vbFromUnicode)) End Function Dim MyString, MyLen MyString = "ABo" ' Where "A" and "B" are DBCS and MyLen=Len(MyString) * Retums 3 ~ 3 characters in the string, MyLen = LenB(MyString) * Retums 6 - 6 bytes used for Unicode, MyLen = LenMbes(MyString) " Retiims 5 - 5 bytes used for ANSI. AutoBiter Object FF : ‘Represents autofiltering for the spe ified workshiéet. Example 7 Use the AuloFilter property fo return the AvtFilter objec. Use the Filters property to return 3 collection of ind Range property to return the Range object thet represents the entire suites . site following example stores the address and filtering criteria for the current shea applies new filters. Visual Basic for Applications Dimw As Worksheet - Dim filterAmayQ, Dim curreatFiltRange As String ‘Sub ChangeFilters() Set w= Worksheets("Crew") ‘With w.AutoFilter . cunentfiltRange = Range Addreis With Filters ReDim fiterAroy(I To Coun, | To 3) Forf=1 To Count With em(f) if.On Thea, AiterArray(f, 1) = Criteria! If Operator Then filterArmay(£, 2) = Operator filterArray(E, 3) = Criteria2 Endif ey PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 100 SS See End if End With Next End With End With ‘wAutoFilterMode = False wRonge(“Al").AutoFilter field:-1, Criterial="S* End Sub To create an AutoFilter object for a worksheet, you must furn autofiltering on for a range on the worksheet either manually or using the AvlcFilter method: of the Range object. The {following example uses the values stored in module-level variables in the previous example. torestore the original autofiltering to the Crew worksheet. * ‘Visual Basic for Applications ‘Sub RestoreFiltersQ Set w= Worksheets("Crew") Ww AutoFilterMode = False For col = 1 To UBound(filterArtay0, 1) TENot IsEmpty(GilterArray(col, 1)} Then ffilterArray( col, 2) Thea ‘w Range(currentFiltRange). aut ite figld:-co}, Criteria =filterAsray(colj:1), pertain iiteriad-=fiterArray(¢ Ese ‘wRange(currentFiltRange) AutoFilterfield-=co!, _ Criteria} fiterArray eo. 1) End lf End if Next End Sub Range-AutoFilter Method Fillers a list using the AutoFilter. Syntax nt expression. AutoFilter(Field, Crterial, Operator, Crteria2, VisibleDropDown) ‘expression An expression that returns a Range object. Parameters Name Required! [Data Type | Description Optional Field ‘Optional | Variant “The integer offset of the field on which you ‘want to base the filter (Gom the left of the list; the leftmost field is field one), Criterial Optional | Variant The criteria (a string; for exemple, "I0I"). Use "=" to find blank fields, or use "S" to find nonblank fields. If this argument is omitted, the criteria is All. If Operator is ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 101 Peers -VBA- Excel aifoploltems, Criterial specifies the number ‘of items (For example, 10"), ‘Operator Optional} XtAutoFilter | One of the constants of XIAuiofiiterOperator Operator __{ specifying the type of filter. Criteria2 ‘Optional — | Variant The second criteria (a string). Used with : Criterial and’ Operator to construct, compound criteria. ‘Optional ) Variant “True to display the AutoFilter dropdown arrow for the fillered field, False to hide the AvioFiller drop-down arrow for the filtered Return Value Variant Set hr= ActiveSheet Hyperlinks(1) Range Active Window. ScrollRow = hr Row ActiveWindow SerollColuma = br.Columa Hyperlink.Range Property Rune a Range objet at reprise singe the specie hyperlink is attached to. Syntax expression Range expression A. variable ren givin object. one Example The i’ ack us sain Variable the address for the AutoFilter applied to the Crew worksheet. vs ‘Visual Basic for Applications Address = Workshects(* Crew") AutoFilte Range.Address This example scrolls through the workbook window until the hypestink range is in the upper- left comer ofthe active window. Visual Basie for Applications Workbooks(!) Activate | Set hr = ActiveSheet Hypertinks(1).Range ActiveWindow.ScrollRow-= br Row ActiveWindow Scroll Column = hr.Coturnn PivolCell Range Property Returns a Range object that represents the range the specified PivotCell applies to, Syntex expression Range expression A variable that represents a PivolCell object. a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 107 Peers -VBA- Excel aS Example > ‘The following example stores in a variable the address forthe AuloFilter applied to the Crew worksheet. ‘Visual Basie for Applications Address = Worksheets("Crew").AutoFilter Range Address This example scrolls through the workbook window unlil the hyperlink range is in the upper= eft comer of ihe active window, Visual Basic for Applications Workbooks(1).Activate ‘Set hr= ActiveSheet Hypestinks(1).Range ActiveWindow.SerollRow = hr Row ActiveWindow.SeroliColuma = hr.Column Filter.On Property ‘True ifthe specified filter is on. Read-only Boles Syntax expression. On a - expression A variable tnet $3 died. Example att The following exainpla'seis a vari ‘3 jo tie value of the Criterial property of the filter for ‘he first column the filiered range jhe Crew worksheet Visaal Basie for Applications: ‘With Worksheets("Crew") If. AutoPilterMode Then With AutoFilter Filters(1) Jf.On Then el = Criterial End With End If End With ListObject.Uinlist Method | Removes the list functionality frorf a ListObject object. After you use this method, the range of cells that made up the the list Will be a regular range of dato. Syntax F expression Unlist expression A variable that represents a ListObject object, Remarks Running this method leaves the cell data, formatting, and formulas in the worksheet. The ‘Total row is also left intact. This method removes any link ta a Microsoft Windows. SharePoint Services site. AutoFiller is also removed from the fist. Example —_———— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 108 Peers -VBA- Excel ‘The following example removes the list features from a list on a worksheet. ‘Visual Basic for Applications Sub DeListQ Dim weksht As Worksheet Dim obj istObj As ListObject Set wrksht ~ ActiveWorkbook. Workshects("Sheet!") Set objListObj = wrksht ListObjects(1) objListObj.Unlist End Sub ef f ‘Range.AdvancedFilter Method : Filless or copies data fom a list based on a criteria range. Ifthe inital slestion is single cell, that cel’s current region is used. Syntax ? Parameters oy BAS ‘Name Required! | Description Optional. ‘Action Requi One of the constants of XIPierAction Lape specifying whether to make a copy or _4 ae filter the list in place. CaiteraRange “| Optisnal “The criteria range. If this argument is Phe omitted, here are no criteria, Tame Optional | Variant “The destination range for the copied rows | i if Action is xIFiesCopy. Otherwise, this argument is ignored. Tnique Optional | Variant “Tme to filter unique records only. False : to filter all records that meet the criteria, The default value is False. Retur Vaiue Variant w Example This example filters a database (named “Database") based on a criteria range named "Criteria." . ‘Visual Basic for Applications’ ‘Range("Database"), AdvancedFilter _ Action:=xlFilterInPlace, _ GiiteriaRangeRange(* Criteria’) Sort Object, Represents a sort ofa range of daa. ‘Version Information ‘Version Added: Excel 2007 —— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 109 Peers -VBA- Excel Exsmple ‘The following procedure builds and sorts data in a range in the active worksheet, Visuat Basic for Applications Sub SortData() "Building data to corton the active sheet, Range(“AI"), Value = "Name" Range("A2") Value = "Bill™ Range("A3") Value = "Rod Range("“A4").Value = "John" Range("“AS") Value = "Paddy* Range("“A6").Value = "Kelly* Range(’A7").Value = "Wiliam" Range(“A8").Valu Range("A9"). Valu Range("Ato" Range(*AI1"): Value = "Mary" MsgBox "The list is out of order. Hit Ok to coatizue. : vbInformation "Selecting a cell within the range. Range(*A2") Select “Asplying sort. ‘With ActiveWorkbook Worksheets(Acth \SorFields.Clear se ‘SortFields.Add Key:=I BCAA | ag SoriOn=xiSortOaVa! 3, es ging, DataOption:=xlSortNormal i : “Header=: nee SetRange Rang. -MatchCase = False “a Orientation = xITopTo SortMethod = xIPinYin Apply End With a MagBox "Sort complete." vblnfefzpation End Sub % Worksheet.ActivateEvent 3 Oceurs when awarkbook, vworksbe, chart sheet, or enibedded chart is activated. ‘Syntax ¥ expression. Activate & “expression A Vasile that epesis a Worksheet object. Return Value nothing Remarks This event doesnt occur when you create a new window. ‘When you switch betvreen two windows showing the same workbook, the WindowActivate event occurs, but the Activate event for the workbook doesn't occur. Example This example sorts the range AI:A10 when the worksheet is activated. nT PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 110 Peers -VBA- Excel eee ‘Visual Basic for Applications Private Sub Worksheet _ActivateQ Range("al:a10") Sort Key1:-Range("al’ End Sub ‘Workbook SheetCalculate Event ), Order:=xLAscending Occurs after any worksheet is recaleulated or after any changed data i plotted on a chart. Syntax expression SheetCalculate(Sh, ) expression An expression that retams a Workbook object. Parameters (Name [Required/Optional [Data Type | Description Sh Required Object Can be a Chart or Worksheet object Example This example sorts the range AI:A100 on worksheet dae when any sheet inthe workbook is calculated. Visual Basic for Applications Frivate Sub Workbook Sag With Worksheets(1) Range(“al:0100") Sort ky Bnd With a End Sub scouge- Range Property’ Retumsa Range object that represents a cell or a range of cells, Syntax expression Range(Cell, Cll2) expressién A variable that represtl a Range object. Parameters Name | Reauited Toysta type | Description Optional The name of the range. This must be an Al-aiyle reference in the language of the macro. It ean include the range operator (a colon), the intersection operator . (a space), or the union operator (a comma). It can also. Celt [Required | Variont |e dolar signs, but they're ignored. You can use a local defined name in any part of the range, if you use a name, the name is assumed to be in the language of the macro. ‘The cell in the upper-left and lower-right comer of the range. Can be a Range object that contains a single Cell2 | Optional | Variant | cell, an entire column, or entire row, or it can be & ° string that names a single cell in the language of the L ‘macro, —————————— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 111 Peers -VBA- Excel Remarks When used without an object qualifier, this property is a shorteut for ActiveSheet Range (it returns a range from the active sheet; ifthe active shect isn’t a worksheet, the property fails) ‘When applied to a Range object, the property is relative fo the Range object. For example, if the selection is cell C3, then Selection. Range("B1") returns cell D3 beceuse it’s relative to the Range object ronumed by the Selection property. On the other hand, the code ActiveSheet Range("B1") always returns cell BI. Example ‘This example sets the vafue of cell Al on Sheet! to 3.14159. ‘Visuab Basic for Applications Workshects("Sheeti")Range("At").Value = 3.14159 ‘This example creates a formula in cell Al on Sheet. ‘Visual Basic for Applications Worksheets("Sheet!").Range(*Al")Formula = “=10'RAND" ‘This example loops on cells AI:D10 on Sheet) [oie ofthe cells has a valueless than 0.001, the cad replaces that value yi O (2a). . Visual Basic for Applicators For Fach cin Worksheetsshoet!") Ifc.Value <.001, : «Value =0 Endit Nexto ‘This example loops on the range named "TestRange" and displays the number of empty cells. in the range. Visual Basic for Applications ‘numBlanks = 0 For Each c In Range("TestRange" ME Ife.Value pumBlanks = numBlanks +1 EndIf Next Fa MsgBox “There are "& numBlasis &" empty cells his ange” ‘This example sets the font style in cells Al:CS on Sheet to italic, The example uses Syntax 2 of the Range property, ‘Visual Basic for Applications Worksheets("Sheeit") Range(Cells(1, 1), Cells(5, 3). _ Fontltalic= True Range Object ———— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 112 Peers -VBA- Excel Represents a cell, a row, a column, or a selection of cells that contains one or more contiguous blocks of cells. Using the Range Object ‘The following propertis for retuming a Range object are describe + Range property + Cells property Range Property ‘Use Range(arg), where arg is the name of the range, to retum a Range object that represents a single cell or a range of eels. The following example places the value of cell Al in cell AS. myChart Application DataShectRange("AS")Value=_ 9 smyChart Appliestion DataSheet Range(*Al".Value i ‘The following example fills the range A1:H8 with the value 20, * ‘myChart Application DataSheet Range("A L:H8") Value =20. Cells Property : ‘Use Cells(cow, column), where row is the row’s index number and column is the column's index number, to return a single cell. The following example sets the value of cell Al to 24 (columa A is the second eoluma on the datasheet, and row 1 is the second row on the datasheet). ayChart Application DataSheet Clls2; Although you can:als0 use Range("Al") . : to return cedi AL, there may be times when the Cells property is more convenient because you ‘can use a variable for the row or column. The following example creates column and row headings on the datasheet. Sub SefUpTable With myChart Application DataSheet FortheYear=1To 5 ee Cells, the¥ear + 1).Value= 1990+ theYear ‘Next theYear For theQuarter = 1 To 4 ‘Colls(theQuarter + 1, 1).Value="Q" & theQuarter ‘Next theQuarter End With en End Sub Although you can use Visual Basic string functions to alter Al-style references, i's much ‘easier (and much better programming practice) to use the 2 Cells, 1) notation. Use expression Cells(ow, column), where expression is an expression that retums a Range object, and row and column are relative to the upper-left comer of the ange, to return part of a range. The following exomple sets the value for cell C5. myChart Application Range("C5:C10"),Cells(1, [).Value =35 nd PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 113, Peers -VBA- Excel Range.Columns Property Returns a Range object that represents the columns in the specified range, Syntax expression.Colunns expression A variable that represents a Range object. Remarks ‘Using this property without an object qualifier is equivatent fo using ActiveSheetCotumns. ‘When applied to.a Range object that's a multiple-area selection, this propeity sefums columns from only the first area of the range. For example, if the Range abject has two areas —— ‘Al:B2 and C3:D4 — Selection.Columns.Count returns 2, not'4. To use this property on a xrange that may contain a multiple-area selection, test Areas.Count to determine whether the ‘ange contains more than one area. If it does, loop aver each area in the range. ‘Example ‘This example sets the value of every cell in column one in the renge named "myRange” 10 0 (zero). ‘Visual Basie for Applications . Range("myRange") Columnns(1).Value=0 » ‘This example displays the’aumber of columns in the selection on Shectl. If more than one area is selected, the ex: oe on ggch atca, ‘Vinual Basie for,Applications 7 Worksheets("SheetI")Activate © areaCount = Selection Areas.Count IareaCount <= 1 Then ‘MsgBox "The selection contains" & _ Selection.Columns.Count &" golumns.* Else Fori= 1] To areaCoupt ‘MsgBox "Area " & i &" of the selection contains" & _ ‘Selection Areas(i).Columns,Count & " columns." Nexti EndIf > Range Froperty ; Retums a Range object that represents the specified cell or range of cells. Read-only Range object. ‘expression Range(Rangel, Range2) ‘expression Required, ‘An expression that returns a DataSheet object.Range 1 Required for a single cell. The name of the specified range. This must be an Ai-style reference in the language the macro is ‘waitien in. It can inchude the range operator (a colon}, the intersection operator (a space}, or the union operator (a comma). Itean also inchude dollar signs, but they'se ignored ORRange! ee PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 114 Peers -VBA- Excel —— + Range? Required for a range of cells. The cells in the upper-left and lower-tight comers oF the specified range. Each argument can be a Range object that contains a single cell (or an antire column or entre row), or the argument can be a string that names a single cell in the Janguage the macro is written in. Remarks (On the datashect, the frst column heading (starting on the left) is A, followed by B, C, D, and so on. The first row heading (starting at the top) is 1, followed by 2, 3, 4, and so on. Neither the leftmost column nor the top row has a beading. In other words, colomn A is actually the second column from the left; likewise, row 1 is the second row fom the top. The leftmost column and the top row, which are commonly used for legend text or axis labelé, are referred to as column 0 (zer0) and row 0 (zero). Thus, the following example inserts the text "Annual Sales" in the top cell in column A (the second column), * ‘myChart Application DataSheet.Range("'A0"). Value = "Annual Sales" in the leftmost cell in row 2 (the third ‘And the following exomple inserts the text "District 1 row). "District 1” a ‘myChart.Application DataShect Range(*02") Value Example ‘This example sets the wget Al gn he rin 10 3.14159. a ‘This example Ioops on tells A1:C3 ae datasheet. [Fone of the cells has a value less than 0.001, the example replacés that vatue with 0 (zer0). With myChart.Application.DataSheet For Each c in Range("A1:C3") Ife.Value <.00] Then eValue=0 EndIf Nexte End With 4 snyChartDatSbeet Bande pay aie Sig Range.MergeArea Property Retums a Range object that represents the merged range containing the specified cell If the Specified cell tin a merged ang, this property renms the spovied cl, Rra-cly Variant. Syntax ‘expression MergeArea expression A vatible that represents a Range object. Remarks The MergeAsea property only works on.a single-cell range. ‘Example This example sets the value of the merged range that contains cell A3. eee PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 115 Peers -VBA- Excel Visual Basic for Applications Set ma = Range("a3") MergeArea Ifma.Address = "$AS3" Then Range.Rows Property . Retums a Range object that represents the rows in the specified range. Read-only Range object. Syntax expression. Rows expression A variable that represents a Range object. Remarks Using this property without an object qualifier is equivalent to using ActiveSheet Rows. ‘When applied ta a Range object that’s a multiple selection, this property returns rows from only the frst area of the range. For example, if the Range object has two areas — A1:B2 and CR:D4 — Selection Rows.Count retums 2, not 4.:To use this property on a sange that may contain multiple selection, test Areas.Cotnt to determine whether the range is a multiple selection. If iti, loop ove paehares ‘in the range, As shown in the third example. PNSEeD es Fy Example cepa 3 “This example dele ree on ‘Visual Basic for Applications ‘Workshecis("! Sheet ROVE Dielete . ‘This example deletes rows in the | current region on worksheet one where the valué of cell one in the row is the same as the vaine in cell one i the previous row. ‘Visual Basic for Applications “|” ; For Each nw In Worksheets). Cells, 1) CurrentRegion Rows this = nw.Cells(1, {).Value , Tf this = last Then rw.Delete last this Next ‘This example displays the: umbeé of roves in the selection on Shectl. If more then one area is selected, the example loops through tach area. ‘Visual Basic for Applications Workshcets("Sheet!") Activate sareaCount = Selection Areas,Count WateaCount <= 1 Then MsgBox "The selection contains " & _ Selection Rows.Count & " row: Else isl re PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 116 Peers -VBA- Excel For Each a In Selcction.Areas ‘MsgBox "Area " & i 8" of the selection contains " 8 _ aRows.Count & "rows." +1 Nexta EndIf ‘Range-PasteSpecial Method Pastes a Range from the Clipboard into the specified range. Syntax a expression PasteSpecial(Paste, Operation, SkipDlanks, Transpose) > expression A variable that represents a Range object. Parameters > £% Name ‘Required’ [Data Type | Description : Optional ‘Optional | XiPasteType |. The part of the range to be pasted. ‘Optional | xiPasteSpecial |. The paste operation, Operation = Variant "Fine to have Blank cells in the range on the Clipboard not be pasted into the destination range. The defoult value is False, _| "True to transpose rows and columns when the range is pasied The default value is False. ‘Optional Example “This example replaces the data in cells DI:DS on Sheet! with the sum of the existing contents and cells ‘5 on Sheet]. © Visual Basic for Applications © ‘With Worksheets("Sheet!") Range(*CL:C5").Copy ® ‘Range("DI-DS") PasteSpecial_ (Operation:=xPasteSpecialOperationAdd End With Range.Copy Method : Copies the range to the spétified range orto the Clipboard. Syntax expression. Copy(Destination) ‘expression A variable that represents a Range object. Parameters Wane Requized | Data] Desription Optional [Type _ PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 117 Peers -VBA- Excel Destination | Optional | Variant | Specifies the new range to which the specified range will be copied. If this argument is omitted, Microsoft Excel copies the range to the Clipboard. ‘Retum Value Variant Example ‘This example copies the formulas in cells AI:D4 on Sheet| into cells ES:H8 on Sheet2. ‘Visual Basie for Applications ‘Worksheots("Sheet!") Range("Al:D4").Copy _ destination:=Worksheets("Sheot2") Range("ES") Range.AutoFil Method Performs an aufofill on the cells in the specified range. Syntax expression AvtoFill(Destination, Type) expression A variable that represents a Range object, Parameters » Name “[Required/Optional [Data Type ‘Desorption Destination (Required Tae cells to be filed. The destination must include the source range. Specifies the Hill type. Example This example performs an autofill on cells A1:A20 on Sheetl. based on tne sewn < ‘AJ:A2 on Sheatt, Before running this exemple, type | in cell Al and type 2 in cell A2. Visual Basie for Applications Set sourceRange = Worksheets(’SheetI") Range("AL:A2) Set fillRange = Worksheets("Sheeti”) Range(" AU:A26") sourceRange. AutoFill Destination:=fillRange RangeHasFormula Property” ‘Trve if all cells in the range contain formulas; False if none of the cells in the range contains 4 formula; mul otherwise. Read-only Variant Syntax expression HasFormula °°" expression A variable that represents a Range object. Example : “This example prompts the user fo select a range on Sheeil. I every cel in the selected range contains a formula, the example displays a message. ‘Visual Basic for Applications ‘Worksheets("Sheett") Activate Setrr= Application InputBox(_ Se rr cememememenne ee aeeeed ‘PEERS TECHNOLOGIES PVT LID, HYDERABAD Page 18 Peers -VBA- Excel Seen eS See "Select a range on this worksheet’, _ prompt Type=8) fre HasFormala= True Then MsgBox “Every cell inthe selection contains a formula" EndIf Range.Table Method (Creates a data table based on input values and formulas that you define on a worksheet. Syntax expression Table(Rowlnput, Columalnput) expression A variable that represents a Range object. Parameters Name Required/Optional_| Data Type _| Description Rowinpat | Optional Variant | A single cell to use as the row input for your able, Columminput | Optional Variant | A single cell to use a5 the cohimn [input for your table. Retun Value Variant re a Remarks ‘worksheet to sce how. sale mao = ‘This example creates afozatted multiplication fable in cells AL-KI on Sheath. Visual Basie for Applications Set dataTableRauge = Worksheets(*Sheet!") Range("AL:K1I") ‘Sct rowlnpatCell = Workshects("Sheet!")Range("A12") Set columninputCell = Worksheets("Sheetl") Renge("A13") Worksheets(*Sheet!") Range("AI") Formula ="=AI2*A13" Fori=2To1l dataTobleRange-ToblerowlnputCel, columalnputCell With Worksbects(‘Shect!") Range(*AL") CurentRegion Rows()-FontBold = True -Columns(1) Font Bold = eve’ -Columns. AuloFit End With Range-BorderAround Method ‘Example ‘This example adds a thick red border around the range A1:D4 on Sheetl. Visual Basic for Applications Worksheeis*Sheetl") Range(“A1:D4") BorderAround a eee ‘PEERS TECHNOLOGIES PYT LTD, HYDERABAD Page 119 Peers -VBA- Excel Colorindex:=3, Weight=xIThick Range.Olfset Property Retums a Range object that represents a ange that's offtet from the specified range, Syntax expression. Offset(RowOfset, ColumnOfiset) expression A variable that represents a Range object. Parameters ‘Name Requized/O | Data Type | Description ptional fg RowOffset [Optional | Variant | The number of rows (positive, negative, or (zero) by which: the range is to be offset. Positive values ace. bffset downward, and negative values are offset ipward, The default value is 0. ColuimnOttset [Optional — | Varian | The number of columns (positive, negative, or 0 (@ero)) by.which the range is to be offset, Positive values are offset to the right, and 2005} negative values ate_offbet to the Jett. The 2 . “| default value is 0. Worksheeis("Sheet]")Actvete ActiveCel OffelGowOGet=3, colummOset:-3) Activate ‘This exampte assumes thet Sheet] contains a table that has a header row, The example selects ‘the table, without selecting the header row. The active cell must be somewhere in he table before the example is mun. ‘Viswal Basie for Applications Sot tl = ActiveCell. CurentRegion. (bLOMfsei(1, 0) Resize(thl Rows. Count th].Columns.Count).Select Range.RemoveDuplicates Method Removes duplicate values from a ange of values. Version Information . “Version Added: Excel 2007° Syntax expression RemoveDuplicates(Columns, Headet) expression A variable that represents a Range object. Parameters ‘Name — | Required/O | Data Type ‘Description tional Columns "| Optional | Variant “Auay of indexes of the columns that contain ——————— eee PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 120 Peers -VBA- Excel eS the duplicate information. If nothing is passed then it assumes all columns contain duplicate information. Header [Optional | Xi¥esNoGuess | Specifies whether the first row contains header information, xINo is the default value; specify xiGuess if you want Excel to attempt to determine the header. Example ‘The following code sample moves duplicates with all eolumos Sam arange, ‘Visual Basic for Applications ActiveSheet Range(”A1:C100").ReméveDuplicates ‘The following code sample removes duplicates with the first 2 eolumns ‘Visual Basic for Applications ActiveSheet Ran ge("A I:C100") RemoveDuplicates Columns:=Array(1,2), Header:=xIYes Abs Function Retums a value of the sae: type that is passed to it specifying the absolute value of a number. Syntax ocpeeth Abs(number) f° 7: ‘The required number argument can be any valid swmeric expression. If number condains ‘Noll, Null is retuned: ifit is an eninitialized variable, zero is returned. Remarks ‘The absolute valuc of a number is its unsigned magnitide. For example, ‘ABS(-1) and ABS(1) both return 1 ‘Example ‘This example uses the Abs function fo compute the absolute value of a number. ‘Dim MyNumber ‘MyNumber= Abs(50.3) " Retums 50,3. ‘MyNumber = Abs(-50.3)' Retums $0.3. Int, Fix Functions ‘Retums the integer portion of « number. Syntax ——— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 121. Peers -VBA- Excel Int(aumber) Fix(oumber) ‘The required number argument is a Double or any valid numeric expression. If number contains Null, Null is retumed, Remarks Both Int and Fix remove the fractional part of number and retum the resulting integer value, ‘The difference between Int and Fix is that if number is negative, Int returns the frst negative integer less than or equal to number, whereas Fix retums the first negative integer greater than ot equal to number. For exemple, Int converts -8.4 to -9, and Fix converts -8.4 to 8. Fix(nuniber) is equivalent to: ‘Sgn(wumbes) * fnt(Abs(aumber)) Esample ‘This example illustrates how the Int and Fix functions return integer portions of numbers. In (he case of a negative number argument, he Int fonction retuons the frst negative integer less than or equal to the number; the Fix function returns the first negative integer greater than o equal tothe number. Dim MyNumber *ix(99.2) 4 yi 7 > ‘MyNumber= Int99.8)/.Remms -100;2"" 2 MyNumber = Bix(-99.8)'\Retums -99." > ‘MyNumber = Int(-99.2) "Returns “100. MyNumber = Fin(-99.2)' Returns 99. ‘MURR Function & Refunts a Double specifying the fibdified internal rate of return for a series of periodic cash flows (payments and receipts). \. Syntax . # ‘MIRR(valuesO, finance_rat, seinvedh rate) ‘The MIRR function has these named arguments: Past Description values) Required:-Ariay of Double specifying cash flow values. The aray must contain at least one negative value (a payment) and one positive value (a receipt). finance rate | Required. Double specifying interest rate paid as the cost of financing. reinvest rate | Required. Double specifying interest rale received on gains from cash reinvestment, Remarks ‘The modified internal rate of retur is the internal rate of return when payments and receipts are fioanced at different rates. The MIRR function takes into account both the cost of the ns PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 122 Peers -VBA- Excel Eee investment (finance_rate) and the interest rate received on reinvestment of cash (teinvest_rate). ‘The finance rate and reinvest rate arguments are percentages expressed as decimal values. For example, 12 percent is expressed as 0.12, “The MIRR function uses the order of values within the array to interpret the order of payments and receipts, Be sure to enter your payment and receipt values in the correct sequence, Example ‘This example uses the MIRR function to return the modified ii series of cash flows contained in the array Values) LoanAPR sepresents the financing interest, and InvAPR = represents the interest rate received on reinvestment. Dim LoanAPR, InvAPR, Fmt, Re‘Rate, Msg. Satie Values(5) As Double ' Set up aray. ‘LoanAPR = 1 "Loan rat 5 InvAPR = .12 Reinvest Fmt="#0.00" "Define pjoney foraiat ‘Vahues(0) = -709903 start-up costs: * Positive cash flows xeflegting in income for four successive years. ‘Values(1) =: ‘Values(3) = 28009 : Values) =31000 RetRate = MIRR (Values), LoanAPR, InvAPR) * Calculate intemal rate, Msg = “The modified internal rate of return for these five cash flows is ‘Msg = Msg & Format(Abs(RetRate) * 100, Fmt) & "%." ‘MsgBox Msg ' Display internal run “rate. PPmt Function % Returns a Double specifying the priticipal payment for a given period of an annuity based on periodic, fixed payments and a fined ‘interest rate. Syntax - PPant(rate, per, nper, py, fl; type] ‘The PPmt function has these named arguments: Part] Description rate | Required. Double specifying interest rate per period. For example, if you get @ car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate por period is 0.1/12, of 0.0083. per__| Required. Integer specifying payment period in the range 1 through nper. nper | Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car Joan, your Joan has a. a PEERS TECHNOLOGIES PVT I.1D, HYDERABAD Page 123 total of 4 * 12 (or 48) payment periods. py | Required. Double specifying present value, or value today, of a series of Future payments or receipts. For exemple, when you borrow money to buy a car, the loan amount isthe present value to the lender of the monthly car payments you will make. fv ‘Optional. Variant specifying future yalue or cash batance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if yon want to save $50,000 over 18 years ‘for your child's education, then $50,000 is the future value. If omifed, 0 is assumed, ‘ype | Optional. Variant specifying when payments are due, Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the L period. Ifomitted, 0 is assumed. a Poe Remarks ‘An annuity isa series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan). The rate and nper arguraents mst be calculated using payment periods expressed in the same units, For example, if rate is calculated using months, pper must also be calculated using months. For all arguments, cash paid out (such 2s deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers. ‘Example ‘This example vses the $Pmt fundlioa to Galeuiate how mach of a payment for a specific pesiod is principal when ll the payments are of equal value. Given are the interest percentage rate per period ( ee APR/ 12, ? ), the payment period for which the principal narina ie dacived + Period }, the total number of payments ( TotPmts ), the present value or principal of the loan ( PVal )sthe future value of the loan ( val }, and a number thot indicates whether the payment is due at the beginning or end of the payment period ( PayType: 2 > ! Dim NL, 1, Fmt, FVal, PVal, APR, TotPmts, PayType, Payment, Msg, MakeChart, Period, BI ‘Const ENDPERIOD = 0, BEGINPERIOD ~ 1 ' When payments are made. ‘NL=Chy(13) & Cha(10) "Define newline, ‘TB=Chr(9)' Define tb. Fmt = "#8 ##0.00" ' Define money format. F¥al= 0" Usually 0 fora loan. PVal~ InputBox("How much do you want to borrow?) APR= InputBox("What is he annual percentage rate of your loan?”) rr PEERS TECHNOLOGIES PVILTD, HYDERABAD Page 124 Peers -VBA- Excel Sea ee IfAPR> | Then APR = APR / 100 Ensure proper form. ‘TotPmts = InputBox("How many monthly payments do you have to make?") PayType = MsgBox("Do you make payments at the end of month?", vbYesNo) UfPayType = vbNo Then PayType = BEGINPERIOD Else PayType - ENDPERIOD Payment = Abs(-Pm((APR / 12, TotPmts, PVai, FVal, PayType)) Msg = "Your monthly payment is" & Format(Payment, Frat) & "." ‘Msg = Msg & "Would you like a breakdown of your principal and" Msg = Msg & “interest per period?" ‘MakeChart = MsgBox(Msg, vbYesNo)' See if chart is desired, IfMakeChart > vbNo Then . If ToPaits > 12 Then MsgBox "Only frst year will be shown.” _ ‘Msg = "Month Paymeat Prioeipal Interest” & NL For Period = { To TotPmnts IfPeriod> 12 Then Exit For' Show only first 12, P=PPmi(APR / 12, Period, TotPmts, -PVal, FVal, PayType) P= (int(P + 005) * 100)/ 100) ' Round principal. _I=Payment -P 1= (Inl((+.008) * 100)/ 100)" Round interest. Msg = Msg & Period & TB & Format(Payment, Frnt) Mag = Msg & TB & Format(, Fmt) & TB & Formal(J, Fmt) & NL Next Period het MspBox Msg' Display amortization ible. = End If SS Using For Kach..Next Statements. j ‘For Each, .Next statements repeat a block of stalements for cach object in a collection or each clement in an array. Visual Basic automatically sets a variable each time the loop runs. For example, the following procedure closes all forms except the form containing the procedure, Ghat’s running. . Sub CloseForms() For Each fim In Application Forms If fim.Caption © Screen, ActiveForm Caption Then frm Close Next End Sub, - . ‘The following code loops through’cach clement in an array and sets the value of each to the value ofthe index variable Dim TestArray(10) As nteger, LAs Vasiant ForEach [Jn TestArray ‘Testarray(1)=1 Next > Looping Through a Range of Cells Use a For Esch...Next lovp to loop through the cells in a range. The following procedure oops through the range A1:D10 on Sheetl and sels any number whose absolute value is less than 0.01 to 0 (zet0). Sub RoundToZero0) For Bach niyObject in myCollection If Abs(myObject. Value) < 0.01 Then myObject. Valu rr PEERS TECHNOLOGIES PVT LTD,, HYDERABAD Page 125 Peers —VBA- Excel Nexto End Sub Exiting a For Each..Next Loop Before itis Finished ‘You can cxit a For Eaok...Next loop using the Exit For statement. For example, when an error cocurs, use the Exit For statement ia the Truc statement block of cither an If..Then. Else statement of a Select Case statement that specifically checks for the error. If the error does sot occur, then the If...Then..,Else statement is False and the loop continues to run as expected. The following example tests for the first cell in the range AI-BS that does not contain a umber, If such a cel is found, a message i displayed and Exit For ets the loop. Sub TestFotNumbers() For Fach myObject In MyColleetion : [If IsNurperie(mayObject: Value) = False Then ‘MsgBox “Object contains @ non-numeric value.” Exit For End If Nexto, ; End Sub wa Appiteation.StatusBar Prépc ‘Syntax ‘expression. sinf txprosion A variable that epresets ‘an Apolication object. Remarks. ‘This property retums False if Microsoft Ess! has control of the status bar. To restore the default status bar text, set te property to False; this works even if the status bar is hidden, Example “This example sets the status bar text to "Please be patient.." before it opens the workbook Lasge.als, and then it restores the default text. Visual Basic for Applications oldStatasBar = Application DisplajStatusBar Application DisplayStatusBar~ True Application. StatusBar = "Please be patient.. Werkbooks.Open filoname:~"LARGE XLS" Application, StatusBar = False ‘Application DispleyStatusBer = oldStamsBar SharedWorkspaceTasks.Add Method ‘Adds a task to the list of tasks in a shored workspace. Returns a SharedWorkspaceTask object. Syntax ————————————————————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 126 Peers -VBA- Excel a expression. Add(Title, Status, Priority, Assignee, Description, Due Date) expression Required. A variable that represents a SharedWorkspaceTasks object. Parameters Nome | Required” | Data Type Description Optional Tite Required _| Sting “The title ofthe new task. Status Optional | msoSharedWork |The status of the new task, Default is spactT ask msoSharedWorkspaceTaskNotStarted. Paority "| Optional | msoSharedWork | The priority of the new task. Default 15 spaceTask mmsoSharedWorkspaceTaskNoral, Assignee Optional | SharedWorkspace |The member fo whom the new task is Member assigned: * ‘Description { Opfional | String ‘The description of the new task. DueDate « [Optional | Date “The due date of the new task. Remarks ‘The schema thot defines shared workspace tasks and their properties for a SharePoint site can be modified on the server in such a way that the Add method of the SharedWorkspaceTasks collection may raise an eror, or may istegard the Values of certain argumeais. In perticular, the task status and priority emumerations can be customized. Some examples of the problems that can result are mentioged below: j< i, ied, and the status field has been semoved from + Ifa Stats prevents Suppl the gusttized itayihe argument will be ignored and no error will raised Rf Status value is supplied that lies outside the status values recognized by the customized tasks Schema, the arenment wii he iomared the default value Will be used, and no erzor wil! Be s3iou. + Ifa new requifed field has been added to the cusivinized tasks schema, then the Add method. yell fail with an error, and it will no longer be possible to use the Add method tage new tasks. anh Example a The following example adds a nei task to the tasks collection of the shared workspace, spovifes a due date, and assigns thé fask lo the first member ofthe shared workspace, Visual Basic for Applications Dim swsTask As Office. SharedW¢ Dim swsMember ‘As Office, Shared WorkspaceMember ‘Set swsMember = ActiveWorkbook SharedWorkspace Members(1) Set swsTask = ActiveWorkbook Shared Workspace.‘Tasks.Add{_ "Complete document by year-end”, _ smsoSharedWorkspaceTaskStatusNotStarted, _ ‘msoSharedWorkspaceTaskPriorityNormal, _ swsMember, _ "My first shared workspace task", #12/31/20054) ‘MsgBox "New task: " & swsTask-Title,_ ‘vbInformation + veOK Only, _ ee PEERS TECHNOLOGIES PVTLTD, HYDERABAD i Page 127 Peers -VBA- Excel SS "New Task in Shared Workspace" Sct swsMember= Nothing ‘Set swsTask =Nothing ‘CommandBar Object Represents 2 command bar in the container application. The CommandBar object is a ‘member of the CommandBars collection. Note ‘The vse of CommandBars in some Microsoft Office applications has been superseded by the new Ribbon user interface. For more information, search help for the keyword "Ribbon." Example fo Use CommandBars(index), where index is the name or index number of s command bar, to return 2 single CommandBar object, The following example’ steps through the ctllection of command bars to find the command bar named "Forms." Ifit finds this command bar, the example makes it visible and protects its docking state Jn this examiple, the variable cb represents a CommandBar object, a Visual Basic for Applications . foundFlag = False For Each cb In CommandBars Ifcb.Name = "Forms" Then - cbProtection = msoBarNoChangeDock cbVisible= Tue pO Se foundFlag=Tne : EndIf : s - ‘Next cb - ‘Af Not foundFlag Then MsgBox "The collection dies na enotain a Forts command bar.” EndIf ‘You can use a name of index number to specify a menu bar or toolbar in the list of available” mem bars and toolbars in the container application. However, you must use a name to specify a menu, shortcut menu, or submenu (all of which are represented by CommandBar ‘bjects). This example adds a new menu ftem fo the bottom of the Tools menu. When clicked, the new menu item runs the procedure named "gbReport.” ‘Visual Basic for Applications Set newltem = CommendBars(" Tools"), Controls, Add(Type:-msoControlButton) With newltem BeginGroup = True Caption = "Make Report" FacelD = 9 OnAction = "qtReport" End With If two or more custom menus or submenus have the same name, CommandBars(index) setumns the first one. To ensure that you return the correct menu or submenu, locate the pop- up control that displays that menu. Then apply the CommandBar property to the pop-up ‘control fo zeturm the command bar that represents that menu. Assuming thatthe third control ————— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 128 Peers -VBA- Excel on the toolbar named "Custom Tools" is a pop-up control, this example adds the Save command to the bottom of that menu. Visual Basic for Applications ‘Set viewMenu = CommandBars("Custom Tools"). Controls(3) ‘viewMenu.Controls.Add ID:=3 ID of Save command is 3 ‘Mow to: Add and Modify Toolbars ‘The use of CommandBars in some Microsoft Office applications hes been supirseded by the new Ribbon user interface. For more information, search help for the keyword "Ribbon." All host applications have an extensive interface for adding and-designing custom toolbars (adding built-in butions, adding macros as buttons, even adding pop-p controls to toolbars). ‘The design-time changes you'll usually make from Visual Basic code are ones that add or modify combo box controls. Otherwise, working with toolbars in code is almost completely limited to making run-time changes (such as changing the button state, changing the bution appearance, changing the button action). Making run-time modifications to toolbars: There are several modifications you can make to a toolbar at run time, One of these modifications is to change the state of 2 command bar button on the toolbar. Each button control has two active states: pressed (True) and not pressed (False). To change the state of a button control, use the appropriate constant for the Stale property, as explained inthe table later in this topic. Another modification yo can make at‘rin time is to change the appearance or action of a button. To change the Sppearance of a Button but not its action, use the CopyFace and PasteFace method: “These. methods are useful if you want to copy the face of a particular ‘button to the Clipboard! or import it into another application to change some of its features, Use the PasteFace method to transfer the button image fem the Clipboard onto a specific button. To change a button's action to a function you've deveioped, assign the custom procedure name to the button's OnAction property. ‘The following table lists the most common properties and methods for changing the state, appearance, or action of a button” « Property or [Description | method a CopyFace _, | Copies or pastes the image on the face of a button, Use the CopyFace method PasteFace to copy the face of the specified bulton to the Clipboard. Use the PasteFace ‘method to paste the contents of the Clipboard onto the face of the specified bution. The PasteFace method will fal ifthe Clipboard is empty. If the image ‘on the Clipboard is too large for the button face, the image won't be scaled down, Generally, its more convenient to copy and paste a button face at design time, bot you can also make changes to a button face at runtime. You can also use the Faceld property to assign a different built-in button face to a button. 1d Specifies the value that represents the button’s built-in functionality. For example, a button that copies highlighted text o the Clipboard has an Id value of 19. State ‘Specifies the appearance, or state, of the button. Can be one of the following. ‘MsoButionState__ constants: msoButtonDown, _msoButtonMixed, or rr PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 129 Peers -VBA- Excel > msoButtonUp. Sie Specifies whether the button face diaplays its icon of is caption. Can be one of the following MsoButtonStyle constants: msoButtonAutomalic, msoButtontcon, misoButtonCaption, msoButtoniconAndCaption, msoButtonIconAndCaptionBelow, msoButtoniconAndW rapCaption, masoButtonIconAndWrapCaptionBelow, or msoButtonWrapCaption. OnAction | Specifies the procedure to be.run when the user clicks a button, displays @ ‘menu, or changes the contenis of a combo box control. ‘Visibie | Specifies whether the control is tobe displayed or hidden from the user, ‘Enabled | Enables or disables a command bar; the name of a disabled commend bar won't appear in the list of available command bars.’ ° ‘The following example creates a new command bar containing a single command bar button. By using the OnAction property of the CommandBaButton object, you can use the CopyFace method to copy the button face of the built-in Open button to the Clipboard, and hen you can use the PasteFace method to paste the foes onto the existing button. This ‘changes the appearance of the command bar button at run time. Sub testAddModifyToolbars1Q Set myBar = CommandBars _ -Add(Name:="ChangingBution*, Position:=msoBarTop, _ léControl, Ong End Sub Sub ciseaei me Set uewControl = CommandBars FindControl _ ClypermsoConiwwiduiton, _ 3D:-CommandBars("Standard").Controls("Paste") 1d) ‘newControl.CopyFace: Set oldContro] = __ ‘CommandBars("ChangingButton"),Controls(1) oldControl.PasteFace End Sub X ‘Adding and modifying combo bok controls Bait boxes, drop-down list boxes’ and combo boxes are powerful new controls you can add fo toolbars in your Visusl Basie application. However, most container applications require that ‘you use Visual Basic code to design these contols, To design 2 combo box control, you use the and methods descrived in the following table Pi ormethot | De ytion ‘Adds a combo box coatrol to @ command bar by specifying one of Add the following MsoContro!Type constants for the Type argument: msoConlrolEdit, msoControlDropdown, or msoControlComboBox. ‘Adds an item to the drop-down list portion of a drop-down list box Addltem cor combo box. You ean specify the index number of the ne item in the existing list, but if this number is larger than the number of | OO PEERS TECHNOLOGIES PVT LID, HYDERABAD Page 130 Peers -VBA- Excel items in the list, the Addliem method fails. ‘Specifies the label for the combo box control. This is the label that's Caption displayed next to the control if you set the Style property to msoComboLabel, Specifies whether the caption for the specified control will be syle displayed next fo the control. Can be elther of the following MsoComboSiyle constants: msoComboLabel (the label is displayed) of msoComboNormal (the label isn't displayed). ‘Specifies the procedure to be run when the user changes the contents ofthe combo box control. OnAction ‘The following example adds a combo box to a custom toolbat’and aSsigns the macro named "ScrollToQuarter" to the combo box. Set myBar = CommandBars_ -Add(Name:="Custom", Position:=msoBarTop, _ ‘Temporary:=True) smyBar.Visible= True Set newCombo = myBar.Controls _ -Add(Type:=msoContro!ComboBax) ‘With newCombo * AddItem "QI ‘Adaltem QQ” -Additem "Q3" ‘Adaltem "Q4" dure assigned (0 the OnAction property of the combo bor. control is called eacs time the user changes the control. [In the procedure, you can use the ActionControl property éf the ‘CommandBar object to find out which control was’ changed and to return the changed value, The ListIndex property will return the item typed or selected inthe combo box. ‘SendKeys Statement ‘Sends one or more keystrokes to thé active window as if typed at the keyboard. Syntax ‘SendKeys stringf, wait] ‘The SendKeys statement syntax has these named arguments: Part _[ Destription string | Required. Sting expression specifying the keystrokes to send. ‘Wait | Optional. Boolean value specifying the wait mode. IF False (defaul), control is retuned to the procedure immediately after the keys are sent. If True, keystrokes ‘must be processed before contol is returned tothe procedure. Remarks Each key is represcnted by one or more characters. To specify a single keyboard character, ‘use the character itself. For example, o represent the letter A, use PEERS TECHNOLOGIES PVT LTD, HYDERABAD ge 131 Peers ~VBA- Excel a “ar {or string. To represent more than one character, append each additional character to the one preceding it, To represent the letters A, B, and C, use vABC for string. “The plus sign (4), catet (%), percent sign (6), tilde (), and parentheses ( ) have special meanings to SendKeys. To specify one of these characters, enclose it within braces ( a ). For example, to specify the plus sign, use ed . Brackets ({ ]) have no special meaning to SendKeys, but you must énclose them in braces. In other applications, brackels do have a special meaning that may be significant when dynamic data exchange (DDE) occurs. To specify brace characters, use (0 and ay To specify characters that aren't displayed when you press a key, such as ENTER or TAB, and keys that represent actions rather than characters, use the cades shown below: Fey Code. » BACKSPACE {BACKSPACE}, {BS} , or (BKSP} BREAK fe {BREAK} ‘CAPS LOCK {CAPSLOCK] DEL or DELETE {DELETE} or {DEL} DOWN ARROW {DOWN} PEND END - {ENTER] or be (ESC) HELE (HELP) ‘HOME {HOME} INS or INSERT, INSERT) or INS} LEFT ARROW, (LEFT) = NUMLOCK (NUMLOCK} PAGE DOWN, = [{eGDN} PAGE UP, {PGUP) PRINT SCREEN =| PRTSC} RIGHT ARROW (RIGHT) SCROLL LOCK . {SCROLLLOCK} TAB {TAB} UP ARROW, (UP) FL (FI) ¥2 §F2) #3 {FB} F4 ( (ray _| FS {FS F6 (F6) FZ (F7 ee ‘PEERS TECHNOLOGIES PVT LTD, RYDERABAD Page 132, Peers -VBA- Excel ooo ¥e (FB) BJ F9) FIO) (F10} Fil FL Fiz (F12) Fi3 13; FI4 FI4} FIs, FIS Fig, FI6 To specify keys combined with any combination of the sur, GIRL, and ALT keys, ‘precede the key code with one or more of the following codes: Code ‘SHIFT + ‘CTRL n “ALT %. “To specify that any combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, enclose the code for those keys in parentheses. For example, to specify to hold down SHIFT while E and C are pressed, use" +EC) "To specify to hold en hile Eis pressed, followed by C without SHIFT, use " " a. a ‘To specify sephing keys se the form «You must puta spac key and umber, Forcxample, (LEFT 42} ‘means press the LEFT ARROW key 42 times; (h 10} ° ‘means press H 10 times. Nate You can't use SendKeys to sond keysitokes to an application that is not designed to run in ‘Microsoft Windows or Macintosh, Sendkeys also can't send the PRINT SCREEN key { PRISC } to any application, Example This example uses the Shell function to run the Calculator application included with Microsoft Windows. It uses the SendKeys statement to send keystrokes to add some ‘members, and then quit the Calculator. (To see the example, paste it into a procedure, then run ——————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 133 Peers ~VBA- Excel OE ad the procedure, Because AppActivate changes the focus (0 the Calculator application, you can't single step through the code). On the Macintosh, use a Macintosh application that accepts keyboard input instead of the Windows Calculator. Ditn ReturnVatuo, 1 RetumValue = Shell("CALC-EXE’, 1)' Run Calculator. ‘AppActivate RetunValue ' Activate the Calculator. For 1= 1 To 100" Set up counting toop. SendKeys 1& "(+)", True" Send keystrokes to Calculator ‘Next "to add each value of ‘SendKeys "=", True ' Get grand total. SendKeys "*{F4)", Tove Seng ALTHFA to close Caleulater, f Application SendKeys Method Seuds keystrokes tothe active application, Syntax at expression SendKeys(Keys, Wait) expression A variable that represents an Application object. Parameters { ‘Name | Required? Optional Faye | Resid The Key or Rey combinatioa you want to send to the | spoliation as text. Wait) Optio Tee 1 bave Microsoft Excel walt for the Leys to be : $FSeessed before returning control to the macro. False ! (@ omitted) to continue running the macro without | siting for the keys to be processed, Remarks This method places keystrokes’ ita key buffer. In some cases, you must call this method before you call the method that will use the keystrokes. For example, to send a password to a * dialog box, you maust call the Sendieys method before you display the dialog box. ‘The Keys argument can specify any single key or any key combined with ALT, CTRL, or SHIFT (or any combination of tose keys). Bach key is represented by one of more characters, such as "a" for the characfer a, or “{ENTER}" for the ENTER key. To specify characters that aren't displayed when you press the corresponding key {for ‘example, ENTER or TAB), use thp codes listed in the following table, Each code in the table represents one key onthe Keyboafd. Key Code BACKSPACE {BACKSPACE} ot (BS) BREAK {BREAK} ‘CAPS LOCK {CAPSLOCK} CLEAR | (CLEAR) DELETE of DEL (DELETE) of (DEL) DOWN ARROW (DOWN) END. {END} — ENTER (iumeric keypad) (ENTER), nt PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 134 Peers -VBA- Excel ae ENTER = (ide) ESC {ESCAPE) or (ESC) HELP {HELP} HOME {HOMEY INS (INSERT) LEFT ARROW. (LEFT) ‘NUMLOCK {NUMLOCK] = PAGE DOWN, (PGDN} PAGE UP {PGUP} RETURN (RETURN) RIGAT ARROW {RIGHT} SCROLL LOCK. (SCROLLLOCK} ~ TAB (TAB} ‘UP ARROW {UP} Fl through FIS {FL} through (F15) ‘You can also specify keys combined with SHIFT and/or CTRL and/or ALT. To specify a key combined with another key or keys, use the following table. “To combine a key with recede the key code with ‘SHIFT zi “+ (plus sign) CIRL. = * (oazel) i ‘ALT % (percents : ‘Example me : ‘This example uses the SeadKeys method tg ‘Visual Basic for Applications |" Anplicstion SendKeys( Ex") Applicanon.iuinzaccute Method Runs a ci = performs some other action or actions in another application by way of the specified DDE channel. Syntax ~ expression. DDEExecute(Channél, String) expression A variable tbat represeals an Application object. Parameters ‘Nate [Required [Data] Desorption Optional _| Type Channel_| Required | Long { The channe! number returned by the DDETnitiate method. ‘Suing [Requiced [Sting |The message defined in the reveiving application, Remarks ‘The DDEExecute method js designed to send commands to another application. You can also. use it to send keystrokes to another application, allhough the SendKeys method is the preferred way to send keystrokes. The String argument ean specify any single key combined with ALT, CTRL, or SHIFT, or any combination of those keys. Bach key is représented by one or more eheracters such a5 "a" for the character a, or" ENTER)” for the ENTER key. et PEERS TECHNOLOGIES PVT \11D,, HYDERABAD Page 135 Peers -VBA- Excel RS the comesponding key (for To specify characters that aren‘t displayed when you example, ENTER ot TAB), use the codes listed in the follo table. Each code in the table represents one key on the keyboard. Key Code BACKSPACE {BACKSPACE} or (BS) BREAK (BREAK} ‘CAPS LOCK {CAPSLOCK) ‘CLEAR {CLEAR} DELETE or DEL {DELETE} or {DEL} DOWN ARROW. {DOWN} END {END} = ENTER (numeric keypad) ENTER] = ENTER, = (tilde) ESC {ESCAPE} o1 {ESC} HELP {HELP} HOME (HOME, INS (INSERT) LEFT ARROW {LEFT} NUMLOCK {NUMLOCK} PAGE DOWN, {PGDN} PAGE UP, {PGUP} RETURN (RETURN) RIGHT ARROW. L (RIGHT) SCROLL LOCK > 7 (SCROLELOCK} OT AUF} Fl through FS FL FS) —_ ‘You can also specify keys combined with SHIFT and/or CTRL and/or ALT. To specify a key ‘combined with one oF more of the Keys just mentioned, use the following table. ‘To combine a key with Precede the key code with ‘SHIFT “+ (pls sig) CTRL 2 (caxet) ALT - ‘%e {percent sign) 4 Example : ‘This example opens a channel to Word, opens the Word document Formle.dec, and then sends the FilePrint command to WordBasic, ie Visual Basie for Applications channelNumber = Application DDETnitiate(_ Application DDEExecute channelNumber, "{FILEPRINT]" ‘Application DDETerminate channelNumber DateDift Function Retums a Variant (Long) specifying the number of time intervals between two specified dates, eee PEERS TECHNOLOGIES PVT LTO, HYDERABAD. Page 136 Peers -VBA- Excel oo Syntax DateDifi(interval, datel, date2, firstdayofiweek{, Lirstweekofycer]]) ‘The DateDiff fimetion syntax has these named arguments: Pat Description * interval Required. String expression Ghat is the interval of lime you use to calculate the difference between datel and date2. datel, date2 | Required, Variant (Date), Two dates you want to use in the calculation, firstdayofiveek | Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed, . Tistweekolyear | Optional. A constant that specifies the first week of the year. If not specified, the fitst week is assumed to be the week in which January 1 occurs. Settings at - ‘The interval argument has these settings: Settin ‘Weekday ‘Week ‘Hour “Minute ‘Second _ mouse otWeek argunient has these settings: Constant Value Description ‘voUseSystem 0 ‘Use the NLS API setting. ‘voSunday 1 ‘Sunday (default) ‘voMonday 2 ‘Monday voTuestay 3 ‘Tuesday voWednesday 45 ‘Wednesday ‘voThursday 3 "Thursday vbFriday 6 Friday voSaturda; 72 Saturday Constant ‘Value [Deseription “wbUseSysiem 0 t= | Use the NLS APT setting. ‘woFirstJanl "| ‘Start with week in which January 1 occurs (Gefaull) ‘vFissiFourDays —}2 ‘Start with the fist week that has at least four days in the ‘pew year. ‘voristruliWeek [3 Start with frst full week of the year, Remarks ‘You can use the DateDiff fonction to determine how many specified time intervals exist between two dates, For example, you might use DateDiff to calculate the number of days —————— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 137, Peers -VBA- Exce} ES between tivo dates, or the number of wecks between today and the end of the year. To calculate the number of days between datel and date2, you can use either Day of year (’y") or Day ("a"). When interval is Weekday ("w"), DateDiff retums the number of weeks between the two dates. if date! falls on a Monday, DateDiff counts the number of Mondays ‘until date2. It counts date2 but not datel. If interval is Weck ("ww"), however, the DateDiff fonction returns the number of calendar weeks behween the two dates. It counis thesumber of Sundays between datel and date2.DateDiff counts date? if it falls on a Sunday; but it doesn't coint date, even if t does fll om a Sunday. [f datel refers to a later point in time than date2, the DateDi ‘lacionretums a negative number. “The firstdayofweek argument affects calculations thot use the. 'w" and *ww" interval symbols. If datel o date2 is a date literal, the specified year becomes a permanent part of that date. However, if date! or dated is enclosed in double quotation marks (""), and you omit the year, {he current year is inserted in your code each time the datel or date? expression is evaluated. This makes it possibte to write code that can be used in different years. When comparing December 3 to January 1 ofthe immediately succéediig yenr, DateDiff for ‘Year ('yyyy") retums 1 Pe onlya days lapsed. Note, . re dar property Setting is Gregorian, the supplied date must be i, the oled date must be Hijri. Example This cxample uses the DateDiff function to display the aumber of days between a given dite and toy. Dim TheDate As Date "Declare Yatiables. DimMsg ES ‘TheDate = InpuBox("Enter a date") Msg "Days from today: " & Datel pres Now, TheDate) MsgBox Msg ‘PageSetup.TopMargin Property |? ++Show All ‘Returns or sets the size of the tip margin, in points. Read/write Double. Syntax expression. TopMargin expression A variable that represents a PageSetup object. ‘Remarks Margins are set ot retumed in points. Use the InchesToPoints method or the CentimetersToPoints method to convert measurements from inches or centimeters. es PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 138 Peers -VBA- Excel Example ‘These two examples set the top margin of Sheet! to 0.5 inch (36 points). Visual Basic for Applications Worksheets("Sheet") PageSetup TopMargin = _ Application LnchesT oPoints(0.5) Worksheets( "Sheet ) PageSetup. TopMargin = 36 ‘This example displays the current top-margin setting. ‘Visual Basic for Applications marginlnches ~ ActiveSheetPageSetup.TopMargia /_ Application ZnchesToPoints(1) ‘MsgBox "The current top margin is " & marginlaches & " inches Understanding Named Arguments and Optional Arguments When you calla Sub or Function procedure, you can supply arguments positionlly, inthe order they appear in the procedure's definition, or you can supply the arguments by name ‘without regard to position. : For example, the following Sub procedure takes three arguments: Sub PassArgs(steName As String, intAge As Tneger, dteBinh As Date) ‘Debug Print strName, intAge, dteLiirth «! : End Sub 1S : . fo, ni ‘You can call this procedui€ by supplying its arguments in the correct position, each delimited ‘hy a comma, as shown in the following example: vassasgs "Mary", 29, #2-21-698 ‘You can also call this procedure by supplying named arguments, delimiting each with a comma. PassArgs intAge:29, dteBisth:-#2/21/694, suNames="Mary" ‘A named argument consists of an argument name followed by a colon and an equal sign (=), followed by the argument value, ‘Named arguments are especially iséful when you are calling a procedure that has optional arguments. If you use named arguments, you don't have to include commas to denote missing positional arguments. Using named arguments makes it easier to keep track of which ‘arguments you passed and which you omitted. Optional arguments arc preceded by the Optional keyword in the procedure definition, You can also specify a default value for the optional argument in the procedure definition, For example: Sub OptionalArgs(stState As String, Optional strCountry As String = "USA") End Sub When you call a procedure with an optional argument, you can choose whether or not to specify the optional argument. f you don't specify the optional argument, the defalt value, if PEERS TECHNOLOGIES PVT LTD, HYDERABAD Peers -VBA- Excel a any, is used. If no default value is specified, the argument is it would be for any variable of the specified type. ‘The following procedure includes two optional arguments, the varRegion and varCountry ‘variables, The IsMissing function determines whether an optional Variant argument hes been passed to the procedure. si - Sub OptionatArgs(strState As String, Optional vatRegion As. Yes, Optional varCountry As Variant= "USA") If IsMissing(varRegion) And IsMissing(varCountry) Theo, Debug Print strState ElseIf IsMissing(varCountry) Then Debug Print state, varRegion Ebself IeMissing(varkegion) Then Debug Print sisSiate, varCountry Else Debug, Prin stiState,varRegio, vaCountiy EndIf End Sub OptionalArgs varCount OptionalArgs st#State:= "MD", varRegion:=5 Workbook SendMail Method Sends the workbook by using the installed mail system, Syntax expression SendMail(Recipients, Subject, RetumReccipt) expression A variable that represents a Workbook object. Parameters ‘Name Required/ [Data <-| Description Optional_| Type Recipients [Required | Variant | Specifies the name of the recipient as text, or as an array of text strings if there are multiple recipients, At Jeast one recipient must be specified, and all recipients are added a5 To recipients. Subject [Optional | Variant | Specifies the subject of the message. IF this argument is omitted, the document name is used. Retwm (Optional [Variant ("True to request a return receipt. False to wot request @ Receipt return receipt. The default value is False, Example This example sends the active workbook to a single recipient. ‘Viswal Basic for Applications ————— ‘PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 140 Peers -VBA- Excel ‘Type Conversion Functions Bach fonction cocrees an expression to specific data type. ‘Syntax CBool(expression) ‘CByte(expression) ‘CCurfexpression) CDate(expression) ‘Dbi(expression) (CDecfexpression) Clat(expression) CLng(expression) ‘CSng(expression) ‘CSirfexpression) (CVar(expression) ‘The required expression argument is any string expression or numeric expression. Return Types ‘The function name determines the return type as shown in the following: Foncion_[Renum Type | Range for expresion argument CBool Boolean “Any Valid string or tumeric expression. CByty Byte Oto 255. Ray CCur Currency. 3.5] -922,337,203,685,477.5808 to 922,337 203,685,477.5807. Date Date. ==" Any valid date expression. “| -1.79769313485231E308 10 -4.94065645841247E-324 for CDbI Double negative values; 4,9406564584 124 7E-324 lo 1.79769313486232E308 for positive values. +1-79,228, 162,514,264,337,593,543,950,335 for zern-scaled numbers, tats, nambers with no decimal places, For numbers epee [Decimal [with 28 decimal places, the range is 41- 7.9298162514264337593543950335. The smallest_possble jon-zéro number is 0.0000000000000000000000000001., Cint Integer -32,768'to 32,76; actions are rounded. al Chang Long. -2,147,483,648 to 2,147,483,647; fractions are rounded. “B40RH23E3 10° -LADIQSGE-AS for negative values CSng__| Single 1.401298E-45 to 3402823838 for positive values, Con |Seing Reis for CSur depend onthe expression argument . “Same range as Double for numeries. Same range as Siring for cvar [Variant [Sam rane 3 Remarks Ifthe expression passed to the fonction i8 outside the range of the data type being converted to, en error occurs. In general, you can documeat your code using the dala-type conversion functions to show that the result of some operation should be expressed 2s a particular data type rather than the PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 141, Peers -VBA- Excel eel default data type. For example, use Cus to force currency arithmetic in cases where single- precision, double-precision, or integer arithmetic normally would occur. You should use the data-type conversion functions instead of Val to provide internationally aware conversions from one data lype‘o another. For example, when you use CCur, dierent decimal separators, different thousand separators, and various currency options are properly recognized depending on the locale setting of your computer. ‘When the fractional partis exactly 0,3, Cint and CLag always round it to the nearest even umber. For example, 0.5 rounds to 0, and 1.5 rounds to 2. Clnt and CLng differ from the Fix and Int functions, which truncate, rather than round, the fractional par ‘of a number. Also, Fix and Int always retun a value of the same type as is passed in. ¢ ‘Use the [sDate function to determine if date can be cqnverted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted toa date, Any fiactional part of the number is converted to a time of day, starting at midnight. (Date recognizes date formats according to the locale seuing of your system. The correct order of day, month, and year may not be determined if itis provided in a format other than one of the recognized date settings. in addition, a long date format is not recognized i it also ontins the day-of-he-week sng, ‘A.CWDate function i algh provided for Compatibility with previous versions of Visual Basic. ‘The syntax of the CVDate fimction is identical to the CDate function, however, CVDate refuns a Vari type. inslead of an actual Date type. Sinze there is now an intrinsic Date tye, theté!js no futher need for CVDate, The same effect can be achieved by ion :t0.4 Date, aid then assigning it to a Variant. This technique is Note ‘The CDec fumetion does not ret a diserele datatype; instead, it always rotirns « Variant whose value has been converted tg a Decimal subtype, ‘CBool Function Example This example uses the CBool fusetion to convert an expression to a Boolean, If the expression evaluates to ‘nonzero value, CBool returns True; otherwise, it returns False. Dim A, B, Check A= 5:B=5' laitialize vasiables Check = CBool(A =B) ' Cheek contains True, ‘A= 0" Define variable. (Check = CBool(A) ' Check contains False. Byte Funetion Example This example uses the CBytc function to coavert an expression to a Byte. Dim MyDouble, MyByte ‘MyDouble = 125.5678 ' MyDouble is a Double. ees PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 142 Peers -VBA- Excel ‘MyByte= CByte(MyDouble)" MyByte conlains 126. (CCur Function Example ‘This example uses the Cur function to convert an expression to a Currency. Dim MyDouble, MyCum MyDouble = 543.214588 ' MyDouble is a Double. ‘MyCurr = CCur(MyDouble * 2)' Convert result of MyDouble * 2 * 1086.429176) toa * Currency (1086.4292). (Date Function Example ‘This example uses the CDate fanetion to convert a string to a Dit. In general, hard-coding. ates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as #2/12/1969# and 14:45:23 PMA, instead, © Dim MyDate, MyShortDate, MyTime, MyShorfTime 57.) MyDate = "February 12, 1969" ' Define date, MyShortDate = CDate(MyDate) ' Convert to Date data type, MyTime = "4:35:47 PM” ' Define time, ‘MyShortTime = CDate(MyTime) ' Convert to Date data type. Cb) Funetion Example ‘This example uses the CBI Dim MyCur, MyDoibie, | MyCurr A aS6i8) MyCiars a Cumeney. MyDouble = CDbIMyCurr * 8.2 * 0.01)' Convert result toa Double, (CDec Function Example This example uses the CDec function to convert a numeric value to a Decimal. Dim MyDecimel, MyCur* MyCorr= 10000000.0587 ' MyCurr is a Currency. ° ‘MyDecimal = CDee(MyCurt) ' MyDecimal is a Decimal. Cint Function Example This example uses the Clint fmction to convert a value to an Integer. Dim MyDouble, Mylnt MyDouble = 2345.5678 ' MyDouble is a Double. “Mylnt = CIni(MyDouble) 'Mylnt contains 2346. ‘OLng Function Example ‘This example uses the CLng fonction to convert a value to a Long. ‘Dim MyVall, MyVal2, MyLong!, MyLong? ‘MyVall = 25427.45: MyVal2 = 25427.55 ' MyVall, MyVal2 are Doubles. ‘MyLongl = CLog(MyVall) ' MyLongt contains 25427. ‘MyLong2 = CLog(MyVal2) ' MyLong2 contains 25428. ed PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 143 Oe Peers -VBA- Excel CSng Funetion Example This example uses the CSng function to convert a value to a Single. Dim MyDouble1, MyDouble2, MySinglel, MySingle2 " MyDoubie], MyDouble2 are Doubles. MyDoublel = 75.3421 115: MyDouble2 = 75.2421555 MySinglel = CSng(MyDoublel) ' MySingle! contains 75.34211. ‘MiySingle2 CSng(MyDouble2) ‘ MySingle2 contains 75.34216. CStr Function Example This example uses the CStr fonction to convert a numeric: valves Sing Dim MyDouble, MyString ° MyDouble = 437.324 ' MyDouble is a Double. S MyString = CStr(MyDouble) ' MyStcing contains "437.324". “2,” CVar Function Example This example uses the CVar function to convert an expression to a Varin Dim Myint, MyVar : ‘Myint = 4534° Mylnt isan Integer. oS “MyVar = CYVar(Mylat &"000")’ MyVar contain he srng 4534000, Me GS isa ‘Using Microsoft Ex Worksbcel Functions tn Visuat Basie “You can use most MicrojaR Exel worksheet functions in yur Visual Basic statements. For a lst of the worksheet functions you can use, see List of Worksheet Functions Available to Visual Basic. Note Some worksheet functions are not useful in Visual Basic. For example, the Concatenate function is not needed because in Visual Basic you can use the & operator to join multiple text values. : Calting a Worksheet Function from Visnal Basic In Visval Basic, the Microsoft Excel worksheet functions are available through the ‘WorksheetFunction object The following Sub procedure yses the Min worksheet function to determine the smallest value in a range of cells. First, the variable myRange is declared as a Range object, and then it is set to range AI:C10 on Sheet. Another variable, answer, is assigned the result of applying the Min function to myRange. Finally, the value of answer is displayed in a message Dox. ‘Sub UseFunction() Dim myRange As Range Set myRange = Worksheets("Sheet]")Range("A1:C10") answer = Application, WorksheetFunction. Min(myRange) MsgBox answer oe PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 144 Peers -VBA- Excel ee End Sub If you use a worksheet function thet requires a range reference as an argument, you must specify a Range object. For example, you can use the Match worksheet function to search a range of calls. In a worksheet cell, you would tnfer a formula such as =MATCH@,AI:A10,0). However, in a Visual Basic procedure, you would specify a Range ‘object to gt the same result, ‘Sub FindFizsiQ) myVat = Application. WorksheetFunetion _ ‘Match, Worksheets(1)-Range("Al:A10°), 0) ‘MsgBox myVar End Sub Note 5 ‘Visual Basic functions do not use the WorksheetFunction qualifier. A function may have the same name a5 a Microsoft Excel function and yet work differently.. For example, ‘Application. WorksheetFunction.Log and Log will return different values. Inserting a Worksheet Funetion into a Cell To insert a worksheet function into a ed, you specify the function as the value of the Formula property of the corresponding Range object. In the following exampte, the RAND ‘worksheet function (which. generates a random nimber) is assigned to the Formtla property the ‘Sub InsertForzny Worksheets("Shtet] End Sub e(’A1.B3") Formula = “RANDQ" Example This example uses the workshet function Pmt to eaeulte a home morgage Ioan payment. Notice that this exampte uses the InputBox method instead of the InputBox function so that the method can perform type checking, The Static statements cause Visual Basic to relain the values of the three variables; these are displayed as default values the next time you run the Program. te Static loanAmt a Static losnint (Prompt:="Loan amount (100;000 for example)", _ Deftult=loanAmt, Type=l) oanlnt = Application JnputBox _ (Prompt=="Annual interest rate (8.75 for example)", _ DefaultloanInt, Tyne:=1) JoanTerm = Application InputBox _ (Prompti="Term in years (30 for example)", _ Defeult:=loanTerm, Typer=1) ‘payment = Application, WorksheetFunction -Pmnt(loantnt /1200, loanTeim ¢ 12, loanAmt) —————— ————————— PEERS TECHNOLOGIES PVT LTD., HYDERABAD Page 145, Peers -VBA- Excel MsgBox “Monthly payment is " & Formet(payment, "Currency") Lirim, RTrim, and Trim Functions Retums a Variant (String) containing » copy of a specified string without leading spaces (Litim), tiling spaces (RTsiml, or both leading and tailing spaces (Trim). Syntax LTrim(sting) Rrimn(string) ‘Trimtting) ‘The required string argument is any valid sting expression, If sting contains Null, Null is retomed, & Example F ‘This example uses the Trim function o strip leading spaces and thé RTtim function to strip wali spt oma bing wale Hues te Tim ition os both pes fac Dim MyString, ‘rimS: MyString=" " Initialize suing. ‘TrimString = LYrim(MyString)’ TrimString ="<"Trim> ", ‘TrimString = RTrim(MyString) ‘TrimSuing="", ‘TrimS ring = LTrim(RTrim(MyString))* TrimString = "<-Trim.>*, ‘Using the Trim fanction alane'achieves the same result. SmartTags Obj A collection of SmartTag bbjects: that resent he denies assigned to each ell Remarks Use the SmarfTags property of the Range collection or Worksheet opject, iv sewn @ SmartTag collection. The following example demonstrates the use of the SmariTags zrozer with the Add method. Example ‘This example adds a smart tag titled "MSFT" to cell Al, then adds extra metadata called "Market" with the value of “Nasdaq” to the smart tag and then returns the value of the ‘property to the user. This example assumes the hast system is connected tothe internet. Visual Basie for Applications Sub UseProperties() ot Dim sttLink As Sting == Dim styType As String "Define smart tog variables. strLink = “urn:schemas-microsoft-com:smarttagst/StockTickerSymbal” strType = "stockyiew" “Enable smart tags to be embedded and recognized. ActiveWorkbook SmartTagOptions EmbedSmartTags = True Application SmartTagRecognizers Recognize = True ——— ‘PEERS TECHNOLOGIES PVT LTD, HYDERABAD Poge | Peers -VBA- Excel Range(*AI", Formula = "MSFT" * Adda property for MSFT smart tag and define i's value, Range("Al") SmartTags. Add(sttLink) Properties. Add _ ‘Name:="Market’, Value:="Nasdaq" ‘Notify the user of the smart tag's value. “MsgBox Range(''A1"},SmartTags.Add(str1 ink) Properties("Market"). Value ‘End Sub ‘FileDialogFilters Object ‘A collection of FileDialogFilter objects that represent the types of files that can be selected in 2 fle dialog box that is displayed using the FileDialog object.” ‘Example Be Use the Filters property of the FileDialog object to return a FileDialogFilters collection. The following code returns the FileDielogFilters collection forthe File Open dialog box. ‘Visual Basic for Applications Application FileDialog(msoFileDialogOpen) Filters ‘Use the Add method to add FileDialogFilter objects to the FileDialogFilters collection. The following example uses the Clear method to clear the collection and then adds filters to the collection, The Clear melliod éompletely empties the collection; however, if you do not add any filters to the eal ater HAIL files (¢.")" fille is added automatically. Visual Basie fof Applic tions Sub Maing, jeclare a variable as a FileDialng object. Dim fi As FileDialog ‘Create a FileDialog object as a File Picker dialog box. Set fd = Application FileDislog(msoFileDialogFilePicker) ‘Declace a variable to contain the path ‘of cach selected item. Even though the path is aString, ‘the variable must be @ Variant because For Each...Next “routines only work with Variants and Objects. Dim veSelectedltem As Variant "Use a With...End With block to reference the File ‘With £4. ialog object. ‘Change the contents of the Files of Type list. ‘Empty the list by clearing the FileDialogFilters collection. Filters. Clear “Add a filter that inicludes al files. Fillers Add "All files’, "#2" a PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 147 Peers -VBA- Excel ar cea "Add a filler that includes GIF and JPEG images and make it the frst item in the Filters. Add "Images", "* gif, * pg; * pes", 1 "Use the Show method to display the File Picker dialog box and retum the user's action. "The wser pressed the button, If Show=-1 Then "Step through ezchString i the FileDialogSelecteditems collection. ‘For Each vriSelecteditem in SelectedItems ‘vrtSelectedItem ig aString that contains the path of each selected itefn, "You can use any file I/O functions that you want to work: with, this ath. “This example displays the path in a message box. } MspBox "Path name: * & vnSelectedltem ‘Next vniSelectedltem “The user pressed Cancel, Else he S End if End With *Set the object variable to Nothing, 3 Set fd = Nothing End Sub ‘When changing | is collection, zemember that each application can only create an instalice of & single FileDialog object. This means that the FileDialogFilters collection resets to its default filters whenever you call the FileDialog method with anew dislog box type. ‘The following example iterates through the default filters of the Suvests diuiog box and displays the description of cach filter that includes a Microsoft Exeet file, ‘Visual Basie for Applications ‘Sub Main) y ‘Declare a varisble asa FileDialogtiiess collection. ‘Dim fais As FitcDialogFilters ‘Declare a variable as a FilDitogiter object, Dim ff As FileDislogFilter = ‘Set the FileDialogFilters colleétion variable to ‘the FileDialogFilters cofleotion of the SaveAs dialog box. Set féf3 = Application FileDialog(msoFileDialogSaveAs) Filters ‘Iterate through the descripfion and extensions of each ‘defau{t filter in the SaveAs dialog box For Bach ff In fats ‘Display the description of filters that include “Microsoft Excel files ————————— PEERS TECHNOLOGIES PVT LTD,, HYDERABAD Page 148 Peers -VBA- Excel a If bnStr(1, f4F Extensions, "xls", vbTextCompare) > 0 Then MsgBox "Description of filter: " & fOEDescription . EndIf Next fof End Sub Note ‘A.runtime error will occur if the Filters property is used in conjunction with the Clear, Add, ‘or Defete methods when applied to a Save As FileDiaog object. For example, Applicaton FileDialog(msoFileDislogSaveAs} Filters Clear willzesult in a runtime errr. ie FileDislog-Filters Property Gets a FileDialogFilters collection. Read-only. ‘Syntax expression Filters expression A vaciable that represents a FileDialog object. Retum Value FileDialogFilters a . Example The following example di displays each selected fie: jaya File Pigker diolog box using the FileDialog object and ‘a me3gage box, The example also adds a new file filter called “mee NE 2 Visual Basie for Applications Sub Maing ‘Declare a variable as a FleDialog object. Dim fd As FiteDialog ‘Create a FileDialog object as a File Picker dialog, Set f= Application FileDialog(msoFileDialogFilePicker) "Declare a variable to contain the path ‘of each selected item. Even though the path is aString, ‘the vatiable must be a Variant because For Each..Next ‘routines only work with Variants and Objects. Dim vtSelectedltem As Variont "Use a With,..End With block-to reference the FileDialog object. With fa ‘Add a filter that includes GIF and JPEG images and make it the first item in the is Filters.Add "Images", "* gif; * jpg: *,jpee", | ‘Use the Show method to display the File Picker dialog box and return the user's action. ‘Ifthe user presses the button... If Show >-1 Then —————————— ‘PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 149, Peers -VBA- Excel "Step through each string in the FileDialogSelectedltems collection. For Bach vriSelectedliem In Selectedliems ‘ywtSelectedltem is aSiring that contains the path of each selected item. "You can use any file /O functions that you want to work with this path, "This exaraple displays the path in a message box. MsgBox "Selected item's path: " & vrtSelecteditem ‘Next viSelectedltem “Ifthe user presses Cancel. Bise Ed If End With 'Set the object variable to Nothing. Set f= Nothing End Sub NPV Function : an ‘Retoms 2 Double specifying the net present value of an investment based on a series of periodic cash flows (payments and receists) and.a discount sate. Syntax aa NPV¢rate, values() a “The NPY function has thes Patt Description ale | Required, Doijble specif asa decimal. ‘igeount rate over the length of the period, expressed | values) | Required. Array of Double specifying cash flow values, The array must contain at least one negative value (a payment) and one positive value (a receipt). Remarks - ‘The net present value of an investment is the current valve receipts. ‘The NPV function uses the order of values within the array to interpret the order of payments and receipts. Be sure o enter your payment and receipt values in the correct sequence, cries of payments and ‘The NPV investment begins one pétiod before the date ofthe frst cash flow value and ends with the last cash flow value in the array. The net present value calculation js'based on future cash flows. JF your first cash flow occurs at the beginning of the first period, the first value raust be added to the value returned by ‘NFVand must not be included'in the cash flow values of values( ). ‘The NPV function is similar to the PV function (present value) except that the PV function alloves cash flows to begin either at the end or the beginning of 2 period. Untike the variable NPV cash flow values, PV cash flows must be fixed throughout the investment. Exaniple This example uses the NPV function to retum the net present value for a seties of cash flows contained in the array Values() ee PEERS TECHNOLOGIES PVT LTD, HYDERABAD. Page 150 RetRate represents the fixed internal rate of return. Dim Fant, Guess, RetRate, NetPVal, Msg Static Values(S) As Double’ Set up array. *y###H0.00" * Define money format. Guess stats at 10 percent. RetRate = 0625" Set fixed internal rate, ‘Values(0) = -70000 ' Business start-up costs, * Positive cash flows reflecting income for four successive years. ‘Values(1) = 22000 : Values(2) = 25000 NetPVal = NPV(RetRate, VaiuesO) 'Catulate net present vali, ‘Msg="The net present value of these cash flows is" ‘Msg ~ Msg & Formal(NetPVal, Fmt) & "." ‘MsgBox Msg ' Display net present value. Names Object ‘A collection of all the Name objects in the application or workbook. Remarks Each Name object represents a defined name fora range of cells. Names canbe ether builtin names — such as Database, Print_Area, snd Auto_Open— or custom names. ‘The RefersTo argument iniist bg. specified in Al-style notation, including dollar signs (8) ‘where appropriate, For example, if cell A10 is selected on Shectl and you define a name by using the RefersTovargiment *=sheetI!AL:BI", the new ‘name actually refers to cells ALO:B1O (because you specified a relative reference). To specify an absolute reference, use “asheetlISASISBS]". Example {Use the Names property to zetum the Names collection. The following example crepes a ist of ll the names in the active workbook, plus the addvesses they refer to. ‘Visual Basic for Applications “F ‘Sct nms = ActiveWerkbook Names ‘Set wks = Worksheets(1) Forr= 1 Tonms.Count @ wks.Cells(r, 2). Value = nms(r),Name wks.Cells(r, 3). Velue = nms(x).RefefsToRonge Address. Next - Use the Add method to create a name and add it to the collection. The following example creates a new name that refers to cells A1:C20 on the worksheet named "Sheet1." Visual Basie for Applications ‘Names.Add Name:="test", RefersTo:="-sheet! 'Se81:Sc520" Use Names(index), where index is the name index number or defined name, to retum a single Name object. The following example deletes the name “mySortRange" from the active workbook. ‘Visual Basie for Applications pS PEERS TECHNOLOGIES PVT LTD. HYDERABAD Page 151 Peers -VBA- Excel ES ActiveWorkbook Names("mySortRange").Delete Worksheet,Names Property Retums « Names collection that represents all the worksheet-specific names (names defined with the "WorksheetName!" prefix}. Read-only Names abject. Syntax ‘expression Names expression A vatiable that represents a Worksheet object. Remarks Using, is propery wihont an object quale f ig quivalemt to using ActiveWorkbook Names. i & Example . ‘This example defines the name "myName" for cell Al on §| ‘Visual Basie for Applications ActiveWorkbook Names,Add Name:="myName", RefersToRIC! ‘SheetI'RICI" ——— PEERS TECHNOLOGIES PVT LTD, HYDERABAD Page 152

Vous aimerez peut-être aussi