Escolar Documentos
Profissional Documentos
Cultura Documentos
to develop workbooks, reports, analysis and database interfaces. Personally, I use Excel to develop reports even if the data are in an Access database. The time and cost of development are substantially reduced and maintenance of the applications are made easy. Most important, the users can modify these reports and applications by themselves or with the help of colleagues with whom they can share their expertise. It is the ultimate in Learning Enterprise. Here are the functions I use: AVERAGE, CELL, COUNT, CONCATENATE DATE, DAY, IF, INDEX, ISERROR, ISNA, INT, LEFT, LEN, MATCH, MID, MOD, MONTH, NOW, RIGHT, ROUND, SUBTOTAL, SUM, TODAY, TRUNC, TEXT, VALUE, YEAR, +, -, /, *, & As unbelievable as it may appear, the 13 principal functions and the secondary ones presented above allow me to solve almost every problem I can encounter as a Database Interface Developer. For example, the following ONE formula (developed with my colleague ric Charbonneau from Bell Helicopter /Textron) uses 8 functions and named ranges : =IF(D8<CurrentYear,0,IF(ISNA(INDEX(rangeHRS,MATCH("wip",rangeColHRS,0), MATCH(" "&TEXT(D8;0)&"G ",rangeRowHRS;0))),0,(INDEX(rangeHRS, MATCH("wip",rangeColHRS,0),MATCH(" "&TEXT(D8,0)&"G ",rangeRowHRS ,0))*D11/(1+D10)))+C72)+IF(D8=CurrentYear,IF(ESTNA(INDEX( rangeHRS,MATCH("wip",rangeColHRS,0),MATCH(" "&TEXT(D8,0)&"Y ",rangeRowHRS,0))),0,(INDEX(rangeHRS,MATCH("wip",rangeColHRS,0),MATCH(" "&TEXT(D8,0)&"Y ",rangeRowHRS,0))*D11/(1+D10)-C32)),0)
(adding or deleting rows or columns) so that the change if reflected in the formula. : It is sometimes painful to work long formulas in the Formula Window. Press F2 and a more convivial windows will be displayed. : When you copy/paste a complicated formula from one workbook to another, you take the risk of creating useless links between the workbooks. Before "Copy", add an apostrophe in front of the formula and remove it in the destination workbook after "Paste". To copy only part of a formula, follow the following steps: In the Formula Window, select the segment you want to copy, click Copy then CLICK RETURN then proceed to the Paste operation. To copy a formula in a large number of contiguous cells, you will use the Autofill handle located in the right lower corner of the selected cell. Hence, if you have numbers in cells A1 to A1000 and other numbers in cells B1 to B1000, write a formula in C1 (ex. =A1+B1), click Return, re-select cell C1 and double click on the Autofill handle. Automatically, the formula will be pasted in cells C2 to C1000. In the French or international version of Excel, the arguments in functions are separated by a ";" instead of a "," because the "," is used as a separator for the decimals.
INT, MOD, TRUNC TRUNC serves to specify the number of decimals after the period. INT and TRUNC will render the same result if you specify "0" as second argument for TRUNC. The function MOD returns the rest of a division. Hence, =INT(140/60) or =TRUNC(140/60,0) will return "2" as result and =MOD(140,60) will return "20". Concatenation of the results of both functions and a ":" will result in the number of hours and minutes. For example, if you have 140 minutes in cell A1, the formula =INT(A1/60)&":"&(MOD(A1,60)) will return 2:20. If you have 125 minutes, the previous formula will return 2:5. To correct this situation and get 2.05, use a more developed formula: =INT(A1/60) & ":" & IF(MOD(A1,60)<10, "0" & MOD(A1,60), MOD(A1,60)).This formula is very handy when you add time worked, using serial number being sometimes tricky. Note : Note that the arguments in the MOD function are separated by a"," and not a "/" =MOD(B1,45) LEFT, RIGHT, MID, & Here is an example of a formula using the 3 main text functions. Is cell A1 is "accounting", the formula =LEFT(A1,1)&MID(A1,4,1)&RIGHT(A1,1) will return "aog" LEN LEN is the number of characters in the string. If you'd want to remove the letters at the end of these two strings "987676AB" and "67SD", you can't use RIGHT or LEFT by themselves. You will use: =LEFT(A1,LEN(A1)-2) SUBTOTAL The function SUBTOTAL allows (among other operations) to count, to sum or to calculate the average of non-filtered elements of a database. The function requires two arguments, the second is the range covered by the function and the first is a number between "1" and "11" that specifies the operation to be performed (for ex. "1" is for average, "2" is for count and "9" is for sum). =SUBTOTAL(9,B2:B45) This formula will sum the values in range (B2:B45) for records that are not filtered when a filter is applied on the database including range B2:B45. VALUE, MID The VALUE function states that an argument is a number. I have used this function to generate a subtotal depending on conditions among a group of account numbers in the following format: "608A9", "703B2" et "629B1". I wanted a subtotal (A1:A20) if the first two number's value was less than 70 and if the letter in the account number (B1:B20) was a "B". (SUMPRODUCT formula) =SUMPRODUCT((VALUE(LEFT(B1:B20,2))<70)*(MID(B1:B20,4,1)="B")*(A1:A20))
whatever the date format specified in your regional parameters. DATE, DAY, MONTH, YEAR
With a date in cell A1 ; the formula to add a day : =DATE(YEAR(A1),MONTH(A1),DAY(A1)+1) the formula to add a week : =DATE(YEAR(A1),MONTH(A1)+1,DAY(A1)+7) the formula to add a month : =DATE(YEAR(A1),MONTH(A1)+1,DAY(A1)) the formula to add a year : =DATE(YEAR(A1)+1,MONTH(A1),DAY(A1)) the last day of the month preceding the date in A1 =DATE(YEAR(A1),MONTH(A1),DAY(A1)-DAY(A1)) the first day of the month following the date in A1 =DATE(YEAR(A1),MONTH(A1)+1,DAY(A1)-DAY(A1)+1) Hours and Minutes To sum hours over a total of 24, you must modify the format of the result cell. "Format"/"Cell"/"Personalized"/"[h]:mm" To transform minutes in hours and minutes (125 becoming 2:05), use this simple formula (the format of the destination cell must be hh:mm): (thanks to Dean BartonAncliffe) =A1/1440 When you create a "Line" or "XY (Scatter)" chart and one or more value is missing in a series, the line will be broken. To avoid such a situation, go to the menu "Tools/Options/Chart" and check "Interpolated". When you create a chart, always create it on the sheet where the data is then cut and paste on another sheet. Otherwise, you will not be able to access the chart sheet with an hyperlink. Hidden rows or columns of data are not shown within a chart. It is an interesting feature allowing you to chart filtered data. If you want all data to be shown, go to the menu "Tools/Options/Chart" and uncheck "Plot visible cells only".
Here is an example: You have data supplied to you as TXT or CSV files or your import data from a database with Microsoft Query in the following format:
Date/Month January February March January February March January February March January February March
Product Brooms Brooms Brushes Brushes Brooms Brushes Brooms Brushes Brooms Brushes Brushes Brooms
City New York New York New York New York Montreal Montreal Montreal New York New York Montreal Montreal Montreal
Qty 536 756 654 365 758 445 255 654 324 156 753 135
Amount 1072 1512 1308 730 1516 890 510 1308 648 312 1506 270
Imagine such a table with 50,000 lines of data and you want to create a table answering to the following questions: How many of each products were sold by city? Quantities Brooms Brushes Total Montreal 1148 1354 2502 New York 1616 1673 3289 Total 2764 3027 5791
How much of each products were sold by city? Amounts Brooms Brushes Total Montreal 2296 2708 5004 New York 3232 3346 6578 Total 5528 6054 11582
To complete such a task instantaneously, you will use the Pivot Table. To create the first Pivot Table (Products by City), copy the raw data in Excel. Select the table go to "Menu/Data/PivotTable and PivotChart Report". In the first dialog box, choose "Microsoft Excel list or database", click "Next". In the second dialog box, accept the "Range" by clicking "Next". In the third dialog box Click on "Layout..." and you will see the following dialog box:
Drag the small grey buttons on your right on to the white shape in the middle, "Qty" over "DATA", Product over "ROW" and "City" over "COLUMN". Click "OK" and then "Finish". You have just created your first Pivot Table. To create the second Pivot Table with the same data, right click anywhere on the first Pivot Table, select "Wizard/Layout". Drag the "QTY" button off "DATA" and replace it by "Amount". To create any other Pivot Table from the same data, right click anywhere on the first Pivot Table, select "Wizard/Layout" and move the grey buttons around. For example, "Product" over "ROW" and "Date/Month" over "COLUMN" will give you a pivot table about "Sales of products by month". Try this one: "Product" over "ROW" and, "City" and "Date/Month" over "COLUMN". You have now "Sales of products by city and by month". Pivot tables are a marvellous tool for Data Analysts, For Report Developers, PT present certain limits as far as presentation is concerned. For reports concerning variables (cities, products, periods, etc.) that do not vary much, I will prefer using SUMPRODUCT and INDEX/MATCH formulas. Mastering SUMPRODUCT formulas and INDEX/MATCH formulas is of the utmost importance if you want to become an expert in reporting, a Report Developer able to extract, organize, analyze and present data.
My clients call them my MAGIC FORMULAS. Most don't know about them before I introduce them but after my visit, they become part of almost all the workbooks in their enterprise. These two tools are so powerful, that you might not need to learn VBA to improve substantially the performance and the ease of maintenance of your Excel workbooks.
Print this page, keep it handy, make these formulas YOURS. If you interview a VBA programmer who doesn't know about these formulas, don't hire him or teach him theses formulas, he will develop less complicated VBA procedures. Just cut and paste the downloaded data (txt , csv, xls) files into your data sheet and the report is updated automatically thanks to SUMPRODUCT formulas. Bring data from two different sources in one workbook and create a virtual relational database within Excel with INDEX/MATCH formulas.
Definitions
(borrowed form http://perso.wanadoo.fr/bernard.lupin/english/index.htm)
OLAP (On Line Analytical Processing): An OLAP application allows a user to extract, organize and analyze data on line.
(Below, I express certain reservations as far as analyzing data with OLAP applications.)
Dimension: A collection of data of the same type, allowing the construction of a multidimensional database. Ex.: Time, Location and Product are the classic dimensions. Data Cube: A multidimensional construction formed by the conjunction of several dimensions. Each cell is defined by a single member of each dimension For example, in a cube with 4 dimensions (amounts, by product, by month and by city), an example of single member would be amount of sales for dresses in May in Montreal. Members: A member is an element of a dimension. ex.: the dresses are a member of the dimension product Hierarchy: In each dimension, members can be organized based on a hierarchy. For example, a subtotal for "Ladies Garments" can be created including figures for "Dresses". In this case, the member "Dresses" would be a child of "Ladies Garments" and hence "Ladies Garments" would be a parent of "Dresses". "Montreal" could be a child of a sub-total "Canada".
OLAPing
OLAP applications (EssBase, Cognos, Business Object, OLAP on SQL Server, etc.) thus organize data to make them more easily retrievable by analysts and reporters. Most of the work is done on the main server making the individual analysis and reports
less complex and computing time hungry on the desktop stations. The data sits in a data warehouse (centralized database like Oracle, Sybase, SQL server, Access). In larger corporations, a copy of the data can be stored in datamarts (by country, by city, by department, etc.). The data cubes extract data from the warehouse and/or the datamart and maintain the cubes on a server accessible to analysts and reporters. The data cubes can be immense or small, serve corporate or departmental needs. Before the CUBES, there were QUERIES created with a language called SQL. SQL is not necessarily accessible to everyone, so came the OLAP applications to bring the data organizing precess closer to the user. At the same time and with the same goal in mind, the database people were creating friendly querying tools in WYSIWYG (what you see is what you get) where you drag and drop fields and write filters and conditions in basic English to create a queries. So you can OLAP with cubes or you can OLAP with queries. Both approaches have advantages and disadvantages.
INTRODUCTION
Very, very, very important. A lot of users and report designers make a major mistake, they try to create the report on the sheet where they import the data. Essbase and SAP have made the same mistake. Their add-in serves to import data and create reports. Importing data and creating a report are two very different operations, don't import data and create reports on a single sheet. Whatever method you chose to import data in Excel for reporting purposes, adopt this approach:
- The imported data MUST be on one sheet and the report on another sheet. Link the two sheets with SUMPRODUCT Formulas and INDEX/MATCH Formulas. - One single data query per sheet. - Format your data sheet so that Excel recognizes a data unit making it
possible to use filters and all the other database functionalities of Excel.
Downstream from EssBase, I have created reporting templates and applications with VBA to automate the importation process. I have simplified the add-in to make it convivial for both users and report designers.
Essbase
EssBase is a great tool to extract and organize data but Excel is THE tool to do the analysis so it is important that I keep Excel on top. I require that the double click and the right click be ruled by Excel and not EssBase so I go to Essbase/Options/Global/Mouse Actions and I uncheck (yes uncheck) "Enable secondary button" and "Enable Double Clicking" (the enable is for EssBase). I met users who would deactivate the EssBase Add-in when they were not using EssBase. No need to do so if you set your options correctly. When somebody looks at your "Retrieve" they should find text boxes explaining your approach. Essbase doesn't see these TB so use them. Text boxes can be created from the "Drawing" tool bar. When you retrieve data from an EssBase cube, if you set the missing value at "0", the zero is a string (text) and cannot be used in a lot of formulas. To correct this situation, set the option #Missing Values at ## and after retrieving the data, select all cells and replace "##" by "0" and all missing values become numbers. "Essbase/Options/Display/Replacement/# Missing values" When entering the dimensions of your retrieval on a worksheet, skip the row before the two last dimensions, leave it empty. Then format the before last dimension's row (bold font and thin bottom border). When doing so, Excel will recognize the data table as an Excel database and the before last row as the title cells of this database. You will have access to the much interesting functionalities under the menu item "Data" (sort and filter). Ex: (for 6 dimensions) The blue row is empty, the corner cell holds a formula that becomes a title, in the row hosting "Dim 5" the font is bold and the lower border is also bold. The yellow cells become a data unit.
Empty Dim 5a
Empty Dim 5b
Empty Dim 5c
Empty Dim 5d
Empty Dim 5e
even copy paste the filtered data on a different sheet). The two best tools to organize and analyze data coming from Essbase are the INDEX/MATCH formulas and the SUMPRODUCT formulas. With INDEX/MATCH formulas and SUMPRODUCT formulas, data from two or more cubes from EssBase can be retrieved within a workbook and the set of retrievals becomes a RELATIONAL database.
Empty Car 5a
Empty Car 5b
Empty Car 5c
Empty Car 5d
Empty Car 5e
Filters
Discover the AUTOFILTER, you place the cursor within the data unit and go to the menu "Data/Filter/AutoFilter" and little arrows appear in the title cell of each field. You can select many different views using the autofilter (on top of all the data and the ten highest values), you can create custom filters (up to two criterias for each field). If you want these dropdown menus to appear only for certain fields, select the desired column or columns before you go to the menu bar to use "Data/Filter/AutoFilter". (Thanks Darrel
Steen)
Advanced Filters
When you need to use filters on many fields, or more than two criterias on aone or many fields or when you need to use complex filters, leave the Autofilter aside and use the Advanced Filters. Advanced filters are one of the most important tool to be used with databases. Here are a few tips on these filters. Let's say we have a database with the following fields: First Name Name Age City Sex Weight
The criteria range to filter members by the name of Thomas would be: Name Thomas
The criteria range to filter the women of Montreal would be: Sex City W Montreal
The criteria range to filter the women of Montreal and of Toronto would be: Sex City W W Montreal Toronto
The criteria range to filter men between ages of 50 and 59 would be: Sex Age Age M >=50 <60
The criteria range to filter men between ages of 50 and 59 and all women would be: Sex Age Age M W >=50 <60
The function SUBTOTAL allows (among other operations) to count, to sum or to calculate the average of non-filtered elements of a database. The function requires two arguments, the first is a number between "1" and "11" that specifies the operation to be performed (for ex. "1" is for average, "2" is for count and "9" is for sum) and, the second is the range covered by the function. =SUBTOTAL(9,B2:B45) This formula will sum the values in range (B2:B45) for records that are not filtered when a filter is applied on the database.
SUBTOTAL
Code of Ethics
ERP and others) are essential in today's enterprises and computer specialists like Programmers will always remain the most suited to insure the effectiveness of these systems. Programmers play three different roles in the information environment. A first group of Programmers (machine/machine) often work in a closed environment (C++, Java and other specialized languages), they develop procedures that talk to other procedures within the MACHINE. The user is not a real concern to them and it is normal. A second group of Programmers (user/machine) have to create modules that collect information from a human being and organize the input so that the machine understands it. These Programmers work for the machine and the machine is the top priority. Still, interfaces have to be designed to minimize human errors and render the human part of the transaction as friendly as possible because unhappy human beings make more mistakes, involuntarily or voluntarily. There used to be a third group of Programmers (machine/user) who had to create reports to extract data from the machine and organize them so that a human being could USE them. These Programmers worked for the USERS and the USERS had to be their top priority. To do this job, the Programmer had be a good listener, had to be service oriented and had to possess a good understanding of the data and of the intuitive patterns of the users. Nowadays this third group of Programmers is being replaced by Excel-VBA Developers downstream from all databases and ERP systems. The Excel-VBA Developers often acts as translator between the machine and the human user. He has to deal with the HUMAN factor. The Excel-VBA Developer may also have to empower the users so that they develop the expertise to maintain the reports, modify them and even create some other reports by themselves. Needless to say that an Excel-VBA Developer must have a Code of Ethics. But first and foremost, an Excel-VBA Developer MUST master Excel and its functions. Without the knowledge of SUMPRODUCT and INDEX/MATCH formulas, the Excel-VBA Developer will spend a lot of time and money programming in VBA trying to re-invent the wheel. Here is the Code of Ethics that I have developed over the years. Good luck. Article 1 : Article 2 : Article 3 : Article 4 : The well informed user is always right. If the user is not well informed, I haven't done my job. My applications answer to the needs of the users. I don't do "miracles" and I know when to say "no".
I haven't been hired to prove that I am smart but to be useful. My applications allow the user to master the computer, not the other way around. If the user feels stupid or thinks I am a "God" there is something very wrong going on. What I do, the user could do if he had the time and the training. My applications are public and I have no secrets. When I leave, the user who is interested can maintain or modify my applications, he is EMPOWERED.
etc.) - a person who knows your corporate culture (Boeing, AT&T, Chase, Joe's Car Wash). If the programmer that you need is expected to work in a closed room away from the users talking all day long with the machine and the machine only, look for a nerd or even for a genius with an attitude. On the contrary, if you are looking for a programmer who will develop the interfaces between humans an machines (the forms with which the users feed data to the program) or with which users extract data from your program, look for a more sociable individual. Look for a programmer that can listen to the users VB and VBA In the early '70, I had a programmable Texas Instrument calculator and, a little later a Commodore64. The computer language used with these machines was BASIC. BASIC has evolved since then and has become Visual Basic. Microsoft has decided that VB would be the computer language used in their environment. So, you can program almost anything in VB within the Microsoft environment. You can create a calculator or even reinvent Excel. In nature, the first ape eventually engendered the gorilla, the monkeys, the ourang-outang and YOU and ME, in the Microsoft environment VB has had a few descendants of its own. One offspring is VBScript that is the VB used on the Internet. It is a limited version of VB because you would not want somebody creating a web page that could erase your hard disk. For security reasons, VBScript is limited to controlling the web page. Six other descendants are called Visual Basic for Application (VBA), VBA for Access, VBA for Excel, VBA for MSProject, VBA for Office, VBA for Power Point and VBA for Word. There are also VBA for Oracle, VBA for Visio and most probably VBA for Others that I don't know about. There is a serious difference between colloquial English (the one you use with your friends) and English for Physicians, English for Engineers, English for Lawyers. The same difference exists between VB and the VBAs. So a VB Programmer is not the right person to work in VBA for Excel. As I was saying earlier, he might try to reinvent Excel rather than use the thousands of functions in Excel. Hiring an Access-VBA Specialist to work in Excel is like going to the Lawyer with your cancer, you might win a billion in court but you will die. VBA for Excel can only be used within Excel so it has to be used by somebody who knows Excel VERY WELL. You are not looking for a Programmer; you are
looking for an Excel-VBA Developer. Excel-VBA Developer The Excel-VBA Developer programs but he is not a Programmer, his focus is not the machine it is the USER. So, no nerds, no genius with an attitude, you want somebody who can listen and offer solutions not impose them. When hiring such a professional, you will look for: - a person who is service oriented, - a person who masters Excel, - a person who masters VBA for Excel (not VB or VBA for another application) - a person who knows your specialty (accounting, MRP, production, HR, etc.), - a person who knows you business (retail, aerospace, banking, manufacturing, etc.) - a person who knows your corporate culture (Boeing, AT&T, Chase, Joe's Car Wash). Ideally, choose the best analyst within your organization and if he is service oriented get him trained in Excel and VBA for Excel. Insist on having him learn about SUMPRODUCT and INDEX/MATCH formulas. Select you 5 best analysts and have them work with a coach for a month. You will be crating a knowledge pool within your enterprise. Even if these people don't have the time to develop applications in Excel-VBA, they will be able to plan good development project, to oversee their completion by outside consultants and to maintain and modify these applications when needed. You will never be enslaved by your outside consultants anymore. Whatever your database, your data warehouse, your data mart, whatever your ERP system or financial application, Excel is the best tool to analyze the data and create reports to feed the decision making processes. With Excel and VBA you can do better than with any other reporting application, you can do it for cheaper, you can do it faster and you get to develop in-house expertise. I call it EMPOWERMENT.
Excel or Access?
I receive many Emails asking me to compare Excel and Access. I always answer that it is like comparing a car with a big truck. Access is a database program and Excel is a program to work with data and to develop reports. Excel is a poor excuse for a database program, it has many limits (quantity of data, limited to one user at the time). Likewise, you can work with data and create reports with Access but it is much more complex and it can get very expensive. Developing a report in Access (or any database application) will cost 10 times more than creating the same report in Excel. You cannot develop complex analysis in Access and you will never be able to customize reports as you can do with Excel. Finally, a report in Excel can be used to generate other reports (links and formulas) something you cannot do with a report developed in any other application. Developing reports at the database level is creating a bottle neck and depriving the enterprise of the intelligence of the majority of its employees and analysts. Access (Oracle and other ERP systems) is a database specialists' environment, Excel is a data specialists' environment. There are car drivers and there are truck drivers. Let's get back to our vehicles. With a car or with a truck you can deliver stuff. The car is faster it can run in alleys, rough roads, no overpass is to low, it runs on a little gas AND you can drive it YOURSELF. If you are good, you can load the trunk, the seats, the top of the car and you can even hitch a trailer. And why not bring a few guys with you to help delivery. With a car you can get closer to your clients in quiet residential areas forbidden to trucks. With a truck, you can transport large quantities of stuff over long distances. Upon arrival, you will need assistance (cranes, lift truck) to unload the stuff that may then be delivered by car. To deliver the parcel in the hands of the user, the 300 pounds hairy truck driver is not necessarily the best suited person. Excel is a car (it can be a racing car). Access is a truck and Oracle, SQL Server, SAP are trains, boats, planes. If you don't need a truck, don't buy one and if you buy one, don't throw he car away. Even with Access or any other database, you will need Excel to develop analysis and reports. Discover SUMPRODUCT Formulas and INDEX/MATCH Formulas, discover the database functions within Excel before you buy Access. And if you really need a database (who doesn't) look at SQL Server, Sybase, Oracle.....
Application
Application is a VBA-object: IT IS EXCEL. Whenever you want Excel to do something or you want to change a property of Excel, you will use the object Application. The methods I use with this THING are: GoTo, OnTime, Quit. Calculation, CutCopyMode,
The properties I use with this THING are: AskToUpdateLinks, Dialogs(), DisplayAlerts, ScreenUpdating, StatusBar.
When you code the closing of a file, you don't want Excel to ask the user if he wants to save it first. You can deactivate this "alert" message and the others with: Application.DisplayAlerts = False don't forget to re-activate the functionality at the end of your procedure with: Application.DisplayAlerts = True
DisplayAlerts
After each Copy/Paste operation, you should empty the clipboard with the following line of code. I make this a suggestion just in case memory is overloaded and so that a user using the paste icon doesn't start pasting anything around. Also using this suggestion will not impose the "Broadway" effect around a range to the user after the procedure has been run. What I call the "Broadway effect, is what happen to the border of a cell when you decide to "copy" it. It looks like the flashing lights around a sign advertizing "Cats" on the Broadway in New-York. Application.CutCopyMode=False
CutCopyMode
ThisWorkbook
ThisWorbook is a VBA-object: it is THE workbook within which the procedure that calls ThisWorkbook runs. You will use ThisWorkbook.Activate instead of repeating Windows("SOandSO.xls").Activate. Using this THING, you are always sure that you are in the RIGHT workbook. The methods I use with this THING are: The properties I use with this THING are: Activate, Saved. Close, Save.
Events
The event is the trigger of the procedure. Most procedure are activated by clicking on (Click) on a command button, a control, or an image (within a form or a sheet) but procedures can also be triggered when the workbook is opened (Open), before it is closed (BeforeClose), when a form is activated (Activate), when a sheet is activated (SheetActivate), before you leave the sheet (Deactivate), clicking on a key (Ctrl A), when making a change on a sheet (Change), etc... Visit also the page on Forms and Controls Here are some examples and notes: Note: You access the events related to the sheets by right clicking on the sheet's tab and choosing "View code". Note: You access the events related to the workbook by double clicking on "ThisWorkbook" in the project window of the Visual Basic Editor (VBE). Activate If you only want certain sheets to open with cell "A1" selected, go to the sheet in the VBA project window of VBE and write the following code on event Activate. Range("A1").Select If you want to attach a list of values to a combo box or a list box, your code must be in the event Activate of the form or the sheet that contains the combo box or the list box. The code will look like this if the values you want to use are in cells A36:A96 of a sheet named "flEntree": Dim varService As String Dim varCompteur1 As Integer For varCompteur1 = 36 To 96 varService = "A" & varCompteur1 lstService.AddItem Sheets("flEntree").Range([varService]).Value Next varCompteur1 Click If the only event of a command button you want to program is the "Click", you can replace the "Command Button" by any image, a WordArt object or any element on the "Design" toolbar. Insert the object and right click to link to a procedure. Ctrl A If you have developed a procedure and you want it to be activated by a key, go to the menu
"Tools/Macro/Macro" and click on the "Options" button. Open If you want to create code that will run at the opening of a workbook double click on "ThisWorkbook" in the Project Window of VBE and select Workbook and Open in the two small windows within the Code Window. You can use the code: Sheets("Home").activate Range("A1").Select SheetActivate If you want all sheets in a workbook to open with cell "A1" selected, go to ThisWorkbook in the VBA Project window of VBE and on event "SheetActivate" write the following code: Range("A1").Select
ABC DEF
SV
Properties
The properties that I use while coding are: FormulaLocal, Hidden, Locked, Name, Value, Visible Count, CurrentRegion, End, Format, NumberFormat, Offset, Path, Saved,
AskToUpdateLinks
When you have a workbook with outside links and you want these links to be refreshed without having to do so through the dialog box, write the following code in the OPEN event of your workbook: Application.AskToUpdateLinks = False at the end of the procedure, reactivate the functionality. Application.AskToUpdateLinks = True
used with: Application
Calculation
To speed things up in a workbook with many formulas, you should deactivate calculation at the beginning of a procedure Application.Calculation=xlManual and reactivate it at the end of it Application.Calculation=xlAutomatic.
used with: Selection, Activecell, Range(), Cells()
CurrentRegion
The CurrentRegion is the set of cells that is surrounded by empty columns, empty rows or sheet's border. It is the most important THING to learn about when you work with SUMPRODUCT formulas and INDEX/MATCH formulas. A CurrentRegion is a DATA UNIT.
Selection.CurrentRegion.Select
Dialogs()
To have access to all the custom dialog boxes (200+) in Excel type Application.Dialogs(. After you key in the parenthesis, VBE will offer you in a contextual menu all the dialog boxes available. The complete code would then look like this (for the "Save as" dialog box) Application.Dialogs(xlSaveAs).Show. You will find a list of all the arguments you can use with the object Dialogs in the VBE help file.
see object: Application
DisplayAlerts
When you code the closing of a file you don't want Excel to ask the user if he wants to save it first. You can deactivate this "alert" message and the others with: Application.DisplayAlerts = False don't forget to re-activate the functionality at the end of your procedure with: Application.DisplayAlerts = True
used with: Range("A1"), ActiveCell, Selection.
Formula, FormulaLocal
Note : If you work with a version of Excel in a language other than English, you will use the property FromulaLocal instead of Formula to be able to write the formulas in the language of your Excel version. Range("A1").Formula = "=SUM(""A2:A18"")" Range("A1").FormulaLocal = "=SUM(""A2:A18"")" Note that the quotes between quotes must be doubled. Hence, Selection.Formula= "=Range ("A1").Value & "normal"" must be written Selection.Formula = "=Range(""A1"").Value & ""normal"""
used with: ThisWorkBook, WorkBooks("SoandSo.xls").
Path
When the user opens a workbook through Windows Explorer, the "File Open" procedure of Excel points to the default directory. So, if you want to open a second workbook residing in the same directory within this first workbook, Excel won't find it. To avoid this problem, I ALWAYS create a variable identifying the path of the first workbook at the beginning of the procedure within which I am calling the second workbook: varPath= Workbooks("Workbook1.xls").Path I then use this variable within the OPEN event: Workbooks.Open varPath & "\Workbook2.xls"
used with: Application
ScreenUpdating
Deactivate the screen updating property at the beginning of a procedure so that the user doesn't have to stare at a rapidly changing screen: Application.ScreenUpdating = False at the end of the procedure, reactivate the functionality.
Application.ScreenUpdating = True
used with: Application
StatusBar
If you develop a procedure that takes time to run you might want to tell the user what is going on. You can write a message in the status bar for him. Application.StatusBar = "Working on such and such" you give control back to Excel with: Application.StatusBar = False
used with: Activecell, ComboBox, ListBox, Range("A1"), Selection, TextBox.
Value
Remember that you must use quotes if you want to allocate a string as value to a cell. Range("A1").Value = "toto" but not if you want to allocate a numerical value, Range("A1").Value = 134
Methods
The methods that I use in my procedures are: Activate, Add, AddItem, AdvancedFilter, Autofilter, ClearContents, Close, Copy, Delete, Find, GoTo, Hide, Insert, Open, Paste, PasteSpecial, PrintOut, Protect, Replace, Save, SaveAs, Select, Show, ShowAllData, Unprotect Note : Use hyperlinks instead of procedures to circulate within a sheet, between sheets and even between workbooks. You can attach these links to words, cells or objects (controls, drawings, images). Select the object, word or cell and click on the "Globe and Link" icon on the toolbar.
used with: ActiveCell, Cells, Range("A1"), Selection
ClearContents
When you want to erase the content of a cell, use the method ClearContents rather than Delete so that the formulas that refer to these cells do not collapse. Selection.ClearContents, Cells.ClearContents, Range("A2").CurrentRegion.ClearContents
Delete
When you want to erase the content of a cell, use the method ClearContents rather than Delete so that the formulas that refer to these cells do not collapse. Selection.ClearContents, Cells.ClearContents, Range("A2").CurrentRegion.ClearContents
used with: Application
GoTo
To avoid the problem of the hyperlinks (position of the selected cell in the screen), use the following code to select cell B32 and have the cell in the upper left corner of the screen: (thanks
to Yann Fernandez)
OnTime
If you want one of your procedure to be executed repeatedly (each 10 minutes here), place this line of code at the end of it. Application.OnTime Now + TimeValue("00:10:00"), "yourProceduresName"