Excel TipsNTricks

Share Embed Donate


Short Description

Download Excel TipsNTricks...

Description

EXCEL BOOK OF TIPS AND TRICKS kcchantnd

1

1 Excel In General -

Shortcuts

-

TIP 1.0 : The Best Shortcut Keys in Microsoft Excel

Ctrl+Z Undo Ctrl+C Enter, Ctrl+V Ctrl+X Copy, Paste, Multiple Paste, Cut Ctrl+F, Ctrl+H Find, Find&Replac Find&Replace e Ctrl+P, Ctrl+S, Ctrl+F4, Alt+F4 Print, Save, Close, Close Excel Ctrl+Arrow Move to edge of region Ctrl+* Select current region Ctrl+A Select all cells Ctrl+Home Ctrl+End Select A1, Select last cell in used range Ctrl+Shift+End Select from active cell to last cell in used range. Ctrl+Shift+Home Select from active cell to A1 Ctrl+Page Down Ctrl+Page Up Move to the next sheet, Move to the previous sheet Ctrl+Tab Move to next open workbook Ctrl+N Open new workbook Shift+F11 Insert new worksheet Shift+F3 Paste function window =+FunctionName+Ctrl+A Insert new function

2

Alt+F11 Open VBE Ctrl+Shift+Enter Array formula Ctrl+F3, F3 Define name, Paste name Ctrl+Spacebar Shift+Spacebar Select columns, Select rows Ctrl+1, Ctrl+B, Ctrl+U Format cells, Bold, Underline Ctrl+; , Ctrl+shift+: Current date, Current time

Tip 1.1 : Easily delete data from cells in the worksheet in Microsoft Excel

The shortcuts Ctrl+Shift+End and Ctrl+Shift+Home allow you to quickly select a cell that contains data and extend the selection to the beginning of the worksheet or the last used cell in the worksheet. Example: You want to clear the contents of all cells from cell A20 to the last used cell ( cell Z1000 for example ) in the worksheet, Select cell A20, Press Ctrl+Shift+End, Press Delete.

Tip 1.2 : Hiding or unhiding a row or rows/column or columns in Microsoft Excel Rows Hide - select a cell or cells, and press Ctrl+9. Unhide - select the cells above and below the hidden row, and press Ctrl+Shift+9. Columns Hide - select a cell or cells and press Ctrl+0. Unhide - select the cells to the left and right of the hidden column, and press Ctrl+Shift+0.

Tip 1.3 : Moving between open workbooks in Microsoft Excel From the Window menu, select a workbook from the list of open workbooks. The keyboard shortcut for moving between open workbooks is Ctrl+Tab. To move back between open workbooks press Ctrl+Shift+Tab

Tip 1.4 : Searching all sheets in a workbook in Microsoft Excel

3

To search for text, use the keyboard shortcut Ctrl+F or choose Edit, Find. To search and replace text, use the keyboard shortcut Ctrl+H or choose Edit, Replace. Searching and replacing all sheets in the Workbook

1. From sheet tab short cut menu choose Select all sheets. 2. Press Ctrl+F or Ctrl+H to find and replace. Note The Ctrl+F keyboard combination combination works in Excel 97 version only single sheet.

Tip 1.5 : Copy & paste data / formulas to thousands of cells in Microsoft Excel Example: Copy text from cell A1 to cells A2 through A5000 ( see screen shot).

1. In cell A1, type Excel Book. 2. Copy cell A1. 3. Select cell A2. 4. Click the arrow beside the Name Box. 5. Type A5000. 6. Press Shift+Enter (select an adjacent range of cells). 7. Press Enter (paste).

4

Tip 1.6 : Quickly delete the Formula without deleting the calculation result in Microsoft Excel

Select a cell containing a formula, press F2 (edit) and then press F9(calculate) and press Ctrl+Enter. Tip 1.7 : Creating Charts with F11 in Microsoft Excel To illustrate, look at the screen shot, which shows sales data broken down by zone. Select a cell in the table, and press F11. The result: Excel opens a chart sheet, a sheet in your workbook that contains a new chart

5

Tip 1.8: Setting the Default Chart Type in Microsoft Excel You can change the default chart type by pressing F11 or by selecting a different chart type from the Chart toolbar. Select a chart sheet or select an embedded chart, and right-click. From the Chart menu, select the chart type you want from the list, and click Set as default chart. Click OK. Tip 1.9 : Updating Charts by Dragging and Dropping in Microsoft Excel If you have a chart with data for 1999 through 2001 and then enter a new column for 2002, you can drag and drop the new data on the chart. Highlight the cells with the new data . Using the mouse, click the black border

6

around the range and begin dragging the range towards the chart. When the mouse pointer is over the chart, release the mouse button.

-

Files importing issues

Tip 1.10 : When importing text files a minus sign appears to the right of the number in Microsoft Excel Problem A negative number that is imported into Excel is often formatted as text with the minus sign (-) on the right side instead of the left. Excel does not sum up negative numbers that are formatted as text, and the results will not reconcile. Solution Enter a formula to solve both problems. It will move the minus sign (-) to the left side of the number, and it will format the data in the cell as a number instead of as text. The Function ( see screen shot): =VALUE(IF(RIGHT(A1,1)= =VALUE(IF( RIGHT(A1,1)="-",RIGHT(A1,1)& "-",RIGHT(A1,1)&LEFT(A1,LE LEFT(A1,LEN(A1)-1),A1)) N(A1)-1),A1))

Tip 1.11 : When importing text files Data not formatted as a number or date properly in Microsoft Excel Problem Often, columns with numerical data or columns that contain date data are formatted as text columns. Changing the formatting of the column from text to number format is often not efficient. Solution 1 - Multiply by 1 Enter the number 1 into the cell and copy it. Select the column that is formatted as text, right-click, and select Paste Special. Select Multiply from the dialog box, and click OK. Solution 2 -Text to Columns Select the column that is formatted as text. From the Data menu, select Text to Columns, and then select the Fixed width option. Skip Step 2. In Step 3, select the General option from the Column data format, and click Finish. To change the column formatting to date formatting, select the Date option (under Column data format), and then click End.

-

Sheets, Workbooks

Tip 1.12 : Moving between sheets in a workbook in Microsoft Excel To move to the next sheet in the workbook, press Ctrl+Page Down. To move to the previous sheet in the workbook, press Ctrl+Page Up.

Tip 1.13 : Changing the font size of the Sheet name in Microsoft Excel The Sheet tabs in a workbook are part of the Scroll Bar. Change the font size in the Scroll Bar option to change the font size of the Sheet name in the tab.

7

The default settings for the window view in Excel are determined by the Windows operating system and Excel. 1. Minimize all applications, press Windows+ m and right-click the desktop. 2. Select Properties, and select the Appearance tab

Tip 1.14 : Create a hyperlink from a string in Microsoft Excel To create a hyperlink for a file path and name (for example), enter the following text in cell A1: c:\ExcelTip\tips.xls

In cell A2, enter the following formula to create the hyperlink: =HYPERLINK(A1) (Try Using Names to perform the same trick)

Names, Range Names

-

Tip 1.15 : Range Name syntax in Microsoft Excel •



A Name must begin with a text character and not a number (after that, you can add numbers). A Name consists of adjacent characters. Join two words by using an underscore. For example, the name Excel Book is illegal. Type Excel_Book.

8







You cannot use a Name that could otherwise be confused as a cell reference. For example, you cannot use A1 or IS2002 because these are already cell references. There is no limit on the number of names you can define Be sure to define unique names for a specific workbook. Defining Defining a Name that resembles names in other sheets only complicates your work.

Tip 1.16 : Define a Range Name in Microsoft Excel

There are two ways to define a Name: Type the text directly in the Name box

1. Select Cell A1. 2. In the Name box, type the text. 3. Press Enter. Use the Define Name dialog box

1. Select cell B1. 2. Press Ctrl+F3, or from the Insert menu, select Name, Define… 3. Type the text in the Names in workbook box. 4. Click OK

Tip 1.17 : Automatically defining Names according to the text in the top row and the left column in Microsoft Excel

1. Open a workbook with a data range (see screenshot). There is text in the top row and in the left column. 2. Select the current region and press Ctrl+*. 3. Press Ctrl+Shift+F3, or from the Insert menu, select Name, Create.

9

4. Select the options Top row and Left column. 5. Click OK

Tip 1.18 : Saving a Formula or Numeric value in the Name box in Microsoft Excel

When working in Excel, you use certain formulas over and over again. Instead, you can enter a formula and save it in the Define Name dialog box in the Refers to box. Example: A formula for calculating the number of the previous year: =Year(Today())-1

10

Explanation: The formula calculates and returns the number of the previous year 2002.

1. Press Ctrl+F3. 2. In the Names in workbook box, type LastYear. 3. Type the formula =YEAR(TODAY())-1 in the Refers to box. 4. Click OK. Enter the formula into a cell in the sheet. 1. Type the = sign. Press F3. 2. Select the name LastYear, and click OK.

Tip 1.19 : Saving values in the Define Name dialog box In the Define Name dialog box, you can save values in the Refers to… box, just as you saved the formula in the example above. Example: The rate of exchange for the Euro, defined with the Name Euro, is set at 0.88.Type the amount in Cell A1. In Cell B1, type the formula =A1/Euro. You do not have to type the text Euro. Instead, use the F3 shortcut. Updating a value that was saved as a Name Press Ctrl+F3, select the name Euro, change the value of the rate of exchange in the Refers to… box, and click OK

-

Security , Protection

Tip 1.20 : Password to prevent opening a workbook in Microsoft Excel

In all Excel versions, you can use a password to prevent opening a workbook. 1. From the File menu, select Save as.

11

2. Select Options. In Excel 2002 you will find new option, select Tools, Options, Security tab.. 3. Type the password twice, and click OK.

Tip 1.21 : Password to protect a workbook in Microsoft Excel

Protecting a workbook prevents the structure from being changed. By assigning a password to a workbook, you prevent sheets from being deleted, new sheets from being inserted, and hidden sheets from being opened. From the Tools menu, select Protection, Protect Workbook . Type a password in the Password box, and click OK. Now confirm the password, and click OK again. Tip 1.22 : Protecting a sheet in Microsoft Excel New in Excel 2002 xp.

From the Tools menu, select Protection, Protect Sheet . In Excel 2002, the Protect Sheet dialog box allows you to select the operations you want users to be able to perform. Under Allow all users of this worksheet to, select the checkboxes for the operations you want to leave unprotected.

Printing

-

Tip 1.23 : Printing Comments in Microsoft Excel.

From the File menu, select Page Setup, and click the Sheet tab. Before printing, select one of the following options in the Comments box: •





None - Will not print comments. At end of sheet - Will print the comments on a separate page after printing the sheet. As displayed on sheet - Will only print the comments that are displayed. displayed.

Print a Single Comment Select a cell containing a Comment. From the File menu, select Page Setup, Sheet. In the Comments box, select At end of sheet. Now click OK, and then click the Print icon. Tip 1.24 : Inserting a picture (company logo) in the header in Microsoft Excel 2002 xp

1. From File menu choose Page setup. 2. Select the Header/Footer tab. 3. Click Custom Header.

12

4. Select Left area. 5. Click the Picture icon (second from right). In the Insert Picture dialog box, search for and select the logo or picture you want to add. 6. Click Insert, Click OK.

Tip 1.25 : Inserting a watermark behind the text in Microsoft Excel

Reports such as a company's financial statements are, by their very nature, confidential. Insert the text "Confidential" behind the data in the report in such a way that it does not interfere with reading the report. 1. Display the WordArt toolbar. Select one of the toolbars, right-click, and select the WordArt toolbar. 2. On the WordArt toolbar, click the Insert WordArt icon (A). 3. From the WordArt Gallery, select any example, and click OK. 4. In the WordArt Edit Text dialog box, type "Confidential" (or any other text), and select the font and the font size. 5. Right-click the WordArt , and from the shortcut menu, select the Colors and Lines tab. 6. In Fill, select Color, No Fill. 7. In Line, Color, select a color that is not too light. 8. Click OK. 9. Right-click, and from the shortcut menu, select Order, Send to Back. 10. Adjust the object's size and location to suit the sheet

Tip 1.26 : Preventing charts from being printed in Microsoft Excel

Select a chart, and right-click. From the shortcut menu, select Format Chart Area . Select the Properties tab, and clear the checkbox beside Print Object. Click OK.

13

-

Charts

Tip 1.27 : Replacing Data Markers with Pictures in Microsoft Excel

Shaking up the normal routine every once in a while cannot hurt. Jazzing up charts with interesting shapes makes a strong visual statement when displaying results. In the figure below, a number of pictures were added. You can add letters to data markers in any order you like or replace data markers with flags or anything else;  just use your imagination. 1. In the Chart, select the desired data markers (if you want to replace them with the same picture). 2. From the Insert menu, select Picture. 3. From the Insert Clip Art pane (in Excel version 97 or 2000, choose from File menu), select the picture you want to use to replace the column.

14

15

2 Excel Text, Editing and Formatting -

Formatting

Tip 2.0 : Add text to Number format in Microsoft Excel Press Ctrl+1 (Format Cells), Choose Number tab, from Category Choose Custom, in the Type box enter : "Credit" #,##0_;"Debit" [Red](#,##0); Tip 2.1 : Color even numbered rows in Microsoft Excel

Coloring even numbered rows in Microsoft Excel can done using conditional formatting: 1. Select the rows you want to apply the color 2. From the format menu choose "Conditional Formatting" 3. In Condition 1 choose "Formula Is", enter the formula =MOD(ROW(),2)0 =MOD(ROW(),2)0 in the box Choose any format and press OK

16

Tip 2.2 : Formatting numbers according to criteria in Microsoft Excel

There are two ways to format numbers according to criteria: •

Custom formatting for a number with criteria



Conditional formatting (see screen shot)

Using custom formats for numbers with criteria

Your options for coloring a number are not limited to displaying negative numbers red. You can color positive and/or negative numbers in any color you wish (do not get excited - the number of colors is limited to eight, and most are difficult to read). Do this by adding the name of the color to the number format in brackets. Example: [BLUE] #,##0 ;[RED](#,##0)

A positive number is displayed in blue; a negative number is displayed in red; and 0 is displayed in blue (since there is no third section, 0 receives the format of the positive number by default). Add a condition to the formatting, and have each section be displayed in a different color: [BLUE] [>5000]#,##0 ;[RED](#,##0); #,##0

17

-

Editing

Tip 2.3 : Transposing Data in Microsoft Excel

Transpose is used to change a vertical range of cells to a horizontal range or vice versa. 1. Copy a range of cells (see cells A1:C9 in the screenshot). 2. Select a cell in the active worksheet or any other worksheet and rightclick. 3. From the shortcut menu, select Paste Special. 4. Check the Transpose check box.

18

Tip 2.4 : Extracting characters from text in Microsoft Excel Using formulas to extract characters from text See Screen shots - A budget item number or an index number in accounting is made up of three parts: •

a department number - the first three digits.



the expense item number - the next three digits.



and secondary description of the expense - the last two digits.

Use the formulas shown in Row 6 to extract these portions from the t ext. You can find the formulas for extracting characters in the Text category, under the Paste function.

19

Tip 2.5 Parsing characters from text without formulas in Microsoft Excel Use Text to Columns to parse text.

1. Select column A. 2. Choose Data, Text to Columns. 3. In step 1 of 3, select Fixed width. 4. Click Next. 5. In step 2 of 3, you parse the data in the column by clicking the mouse between columns you want to parse. 6. Click Next. 7. In step 3 of 3, in the Destination box, enter cell B1. 8. Click Finish.

20

Tip 2.6 : Separating first name and last name without using formulas in Microsoft Excel

The cells in Column A contain a list of names, first name and last name. 1. Select Column A or the range of cells containing the list of names. 2. From the Data menu, select Text to Columns. 3. In Step 1 of 3, select Delimited. 4. In Step 2 of 3, select the Space option. 5. In Step 3 of 3, in the Destination box, select Cell B1, and click Finish

Tip 2.7 : Typing dates in cells quickly in Microsoft Excel

Typing a large amount of data in cells in the sheet can be tiring if it includes a series of dates. Minimize the work by typing the day of the current month and adding the following formula to insert the month and year. =DATE(YEAR(TODAY()),MONTH(TODAY()),A1)

Type a full number in the cell and change it to a date by using the formula below. For example, type 10222002. The result is 10/22/2002. =LEFT(A1,2)&"/"&MID(A1,3,2)&"/"RIGHT(A1,4)

21

3 Excel Date and Time How Excel Works with Dates Excel considers dates as numbers. Each date is assigned a unique serial number . For example, the 27th September 1999 was date serial 36430. Fortunately, you don't need to know this but the fact that all dates have numerical values can be very useful. Windows uses the 1900 date system in which 1st January 1900 is date serial 1, 2nd January 1900 is date serial 2 and so on. When you type a date into a cell, Excel shows you a date but is thinking of a number. To find out the serial number of a date, select the cell containing the date then go to Format > Cells. Go to the Number tab and click General in the Category list. The date's serial number will appear in the Sample box on the right. You can make use of these numbers in all sorts of ways. You can add a number to a date to give a date that number of days later (or subtract a number to get a date before), you can take one date from another to find out how many days in between. There are lots of ready-made date functions too.

Tip 3.0 : Calculate difference between Dates in Microsoft Excel Use the formula DATEDIF to calculate the difference between dates. The results of the calculation are displayed as days, full months, and full years. The formula is not located in Paste Function in the Date & Time category. You must enter the formula manually.

22

Tip 3.1 : Calculating the quarter number in Microsoft Excel

This section, including the figure below, explains how to calculate the quarter of a calendar year and of fiscal years that begin in July or October. To calculate a quarter for a calendar year, see the syntax of the formula for Cell B2 as shown in Cell B15(see screen shot). To calculate a quarter for a fiscal year that begins in October, see the syntax of the formula for Cell B2 as shown in Cell B17. To calculate a quarter for a fiscal year that begins in July, see the syntax of the formula for Cell D2 as shown in Cell B19. The formula INT rounds the result of the calculation to a whole number, which represents the quarter.

23

Tip 3.2 : Filtering by the date field in Microsoft Mi crosoft Excel Excel does not sort data according to cell format, but according to cell value. When sorting by date, Excel sorts the date according to its number. For example, the serial number of the date September 9, 2001 is 37164. If the cell format is changed to "mmmm", the result of the format is September. When sorting the data list, Excel ignores September and only relates to the number 37164. With AutoFilter, as opposed to Sorting, Excel relates to the date format and allows you to filter data according to format.

1. Turn off the AutoFilter. From the Data menu, select Filter, AutoFilter. 2. Copy the Date column. 3. Select two columns to the right of Date, right-click, and from the shortcut menu, select Insert Copied Cells (pasting by inserting copied cells allows you to insert two columns and paste the copied column into them). 4. In Cell D1, type the heading Month, and in Cell E1, type the heading Year. 5. Select the Month field. To select it quickly, select Cell D2, and press Shift+SpaceBar. 6. Press Ctrl+1 (Format Cells). 7. In the Number tab, select Custom . 8. In the Type box, enter the format, "mmmm" "mmmm" (full month format). 9. Click OK. 10. Select the Year field. To select it quickly, select Cell E2, and press Shift+SpaceBar. 11.Press Ctrl+1. 12.In 12. In the Number tab, select Custom. 13.In 13. In the Type box, enter the format, "yyyy" (year format). 14.Click 14. Click OK. 15.Select 15. Select one of the cells in the Year field, and click the AutoFilter icon.

24

Tip 3.3 : Calculating the difference between hours in Microsoft Excel

Calculate an employee's working hours. In the screen shot, notice the format in Cells E4:E8 is hh:mm. The number 1 in the formula IF represents a time value that exceeds 24 hours in a day. See line 5 in the example. An employee named Mark arrived at work at 23:00 in the evening and finished work at 7:00 the next morning. The result is calculated as 8:00 working hours.

25

4 Excel Formula and Fucntions -

Working with Formulas

Tip 4.0 : Handling error in Formula results in Microsoft Excel

Entering formulas into cells in Excel sheets is not foolproof. It is impossible to completely avoid mistakes, but there are ways t o keep them to a minimum. Combining the IF formula with the ISERROR formula returns a calculation whose result is TRUE, if the result of a calculation returns an error. For example:

In Cell A1, type the number 100. In Cell B1, type the formula =A1/A2. The calculation returns an error - #DIV/0! The error is created when you try to divide a number in a cell by 0 (A2). To avoid displaying an error in a cell:

1. In Cell C1, enter the t he formula =ISERROR(B1). The formula returns the result TRUE. That is, Cell B1 contains an error in t he calculation of the formula (the formula ISERROR is located in the category Information in the Paste Function dialog box).

2. In Cell D1, enter an IF formula =IF(C1,0,B1). 3. Combine the formulas into one nested formula. From Cell C1, copy the formula (without the = sign), and paste it into Cell D1 instead of C1. 4. From Cell B1, copy the formula (without the = sign), and paste it twice instead of the digit 0 and instead of B1. The result - one nested formula: =IF(ISERROR(A1/A2),0,A1/A2). Tip 4.1: Printing the Formula syntax in Microsoft Excel

Use the usual method of printing in Excel to print from the sheet while formulas are displayed using Ctrl+~.

Tip 4.2 : Use a function to convert text to proper case in Microsoft Excel Text in upper case: GEORGE W. BUSH The Function: Result:

=PROPER(A1) =PROPER(A 1) George W.Bush

26

Lookup formulas

-

Tip 4.3 : Combine the VLookup and Match formulas in Microsoft Excel

The VLookup formula returns data from any column you choose in the data table, simply change the number of the column in the third argument. Although it sounds simple, there is a catch. •

How can you determine the number of a column in a data table that contains numerous columns?



How can you easily change the number of the column in the third argument of  the VLookup formula?



How can you easily change the column number in multiple formulas in a worksheet from which complex reports are prepared or in a sheet that

contains multiple VLookup formulas?

Solution

Insert the Match formula in the third argument of the VLookup formula. Step 1: Define 2 names, see screen shot

1. Select Row 1, press Ctrl+F3, type the name Row1 in the Names in workbook field, and click OK. 2. Select the data table by pressing Ctrl+*. Then press Ctrl+F3, enter Data in the Names in workbook field, and click OK. Step 2: Enter the Match formula

1. Open an adjacent worksheet, and select cell A1. 2. In cell A1 type 4/1/2001. 3. In cell B1, enter the formula =MATCH (A1, Row1, 0). (Be careful to enter the value 0 in the third argument to specify the search for an exact value.) 4. Results of calculation: 7. Step 3: Enter the Vlookup formula

1. Enter the account number 201 into cell A2. 2. Enter the formula =VLOOKUP(A2,Data,B1) =VLOOKUP(A2,Data,B1) in cell B2. In the third argument of  the VLookup formula, select a cell which contains the Match formula. 3. Calculation results: 7,981. •

Step 4: Combine the formulas

27

1. In the formula bar (Match formula) of cell B1, select the formula without the = sign, press Ctrl+C, and click the Cancel sign (from the left of the formula in the formula bar). Select cell B2, and in the formula bar, select the address B1. 2. Press Ctrl+V and press Enter. 3. The final result is a nested formula is =VLOOKUP (A2, Data, MATCH(A1, Row 1, 0))

28

Tip 4.4 : Combine the Index and Match formulas in Microsoft Excel

Step 1: Define a name Define a Name to column B ( see screen shot ). In the example, the Name is ColB. Step 2: Enter the Match formula •

Select a new sheet. In cell A1, enter one text from the expenses list.



Calculate the row number. In cell B1, enter the formula =MATCH (A1, ColB, 0). The result of the calculation is 9.



In cell A2, enter the date 4/1/2001.



Calculate the column number. In cell B2, enter the formula =MATCH (A2, Row1, 0). The result of the calculation is 7.

Step 3: Enter the Index formula •

In cell C1, enter the formula =INDEX(Data, =INDEX(Data, B1, B2). The result is 345.

Step 4: Combine (nesting) the formulas Now you will use the technique of copying and pasting a formula formula from the formula bar (without the = sign) into a different formula. •

From the formula bar of cell B1, copy the Match formula without the = (equal) sign.



Click the X to the t he left of the formula (to cancel).



Select the C1 cell; in the formula bar, select the B1 address; and press Ctrl+V.



Use the same technique to copy the Match formula from the B2 cell to the formula bar in cell C1 (instead of the B2 address).

The combined formula is : =INDEX(DATA, =INDEX(DA TA, MATCH(A1, ColB, 0), MATCH(A2, Row 1,0)

29

30

5 Excel Data Tip 5.1 : Guidelines to consider before sorting data in Microsoft Excel •

Selecting cell

Do not select a column or data range in a data list on a sheet. Select only a single cell. Click the Sort icon to automatically sort the entire list. The data will be sorted according to the field of the cell selected. •

Formulas

Be careful when sorting data if there are formulas in the cells. Sorting data when cells are linked to other rows or cells in other sheets could distort

the calculations. Be meticulous when sorting a list with formulas that have Names (which are defined with absolute references by default) or with formulas that have absolute references. •

Insert a sequence column to restore original order

Insert an additional column into the data list with ascending numbers, numbers, 1,2,3,…(do not use a formula) before sorting the data. If a list includes a column with consecutive dates, use this column as the first sorting column

Tip 5.2 : Change the auto save default file location in Microsoft Excel

From the Tools menu, select Options, General tab. A new Excel file is automatically saved for the first time (if you have not specified a location on the hard disk) in the My Documents folder on the C: drive. Change the default location as desired Tip 5.3 : Using the COUNTIF function to filter a list into a unique record in Microsoft Excel

1. In Cell B1(see screen shot), enter the text Unique Record. 2. Select Cell B2, and enter the formula =IF(COUNTIF($A$2:A2,A2)>1,1 =IF(COUNTIF($A$2:A2,A2)>1,1,0). ,0). 3. Copy the formula from Cell B2 to Cell B40 (the customer list in Column A extends through Cell A40). 4. From the Data menu, select Filter. 5. Open the filtering drop-down list in Cell B1 by clicking the arrow, and select 0. 6. Notice the unique record in Column A.

31

Explanation:

The COUNTIF function counts the number of cells within a range that meet the given criteria. For example, the COUNTIF function returns the number of times a customer appears in a list. The IF function uses the results of the COUNTIF calculation. If the result of the calculation is greater than 1, the result of calculating the formula is 1. If  it is not, the result is 0. Because the range runs from an absolute cell ($A$2) to a relative cell (A2), the cell range checked by the COUNTIF functions changes when the formula is copied. With AutoFilter, you can filter the rows according to the criterion 0.

32

Tip 5.4 : Consolidate with formulas if the row & column headers of all worksheets are identical in Microsoft Excel

If you have several worksheets and every worksheet has an identical structure that is, the headings in row 1 and column A are identical from sheet to sheet, you can create a total worksheet using simple formulas. Example:

In the workbook 3 sheets - January, February and March contain tables with salary data. On every sheet, the items in cells A2:A8 are identical. On every sheet, the employees listed in B1:H1 are identical and never change. Add a new worksheet, change the worksheet name to Total. Use a formula like the one shown in cell B2 ( see screen shot ) to add the other sheets. The formula in Cell B2 is =SUM (January:March!B2). The technique for entering a formula to sum a single cell on a number of sheets. 1. Select Cell B2 in the sheet name Total. 2. In the cell, type =SUM, and press Ctrl+A (the shortcut for displaying the formula argument box). 3. In the first argument box, select the name of the first sheet in the range January. 4. Press Shift, and select the last sheet in the range March. 5. Click OK.

33

6 Just a pinch of VBA Tip 6.0 : Using the Macro Recorder in Microsoft Excel

Open Excel and the VBE (Visual Basic Editor). Unless it has been changed, the VBE window contains the Project Explorer window and the Properties window (these can be accessed from the View menu). Project Explorer: Works like a file manager. Helps you navigate around the code in your 

workbook. Properties Window: Shows the properties of the currently active ac tive object (e.g. Sheet1) of the

current workbook (e.g. Book1). Exercise 1: Recording a Macro. This exercise shows what happens when a macro is recorded and demonstrates the difference between recording absolute and relative references.

1.

On an empty worksheet in a new workbook, select cell C10 2. Start the Macro Recorder with option to save macro in This Workbook . At this point the VBE creates a new Modules folder. It's quite safe to go and look at it - your actions won't be recorded. Click the [+] next to the folder and see that the VBE has places a module in the folder  and named it Module1. Double-click the module icon to open its code window. Switch back to Excel. 3. Make sure that the Relative Reference button on the Stop Recording toolbar is NOT pressed in. 4. Select cell B5 and stop the recorder. 5. Switch to the VBE and look at the code: Range("B5").Select 6. Now record another macro, exactly the same way, but this time with the Relative Reference button pressed in. 7. Switch to the VBE and look at the code: ActiveCell.Offset(-5, ActiveCell.Offset(-5, -1).Range("A1").Select -1).Range("A1").Select 8. Now record another macro, but instead of selecting cell B5, select a block of cells 3x3 starting at B5 (select cells B5:F7) 9. Switch to the VBE and look at the code: ActiveCell.Offset(-5, ActiveCell.Offset(-5, -1).Range("A1:B3").Select -1).Range("A1:B3").Select 10. Play back the macros, having first selected a different cell than C10 (for Macro2 and Macro3 the starting cell must be in row 6 or below - see step 11 below) Macro1 - always moves the selection to B5 Macro2 - moves the selection to a cell 5 rows up and 1 column to the left of the selected cell. Macro3 - always selects a block of six cells starting 5 rows up and 1 column to the left of the

selected cell.

34

11. Run Macro2 but force an error by selecting a cell in row 5 or above. The macro tries to select a non-existent cell because its code is telling it to select a ce ll 5 rows above the starting point, and that's off the top of the sheet. Press Debug to be taken to the part pa rt of the macro that caused the problem. NOTE: When the VBE is in Debug mode the line of code that caused the problem is highlighted in yellow. You must "reset" the macro before you can proceed. Click the Reset button on the VBE toolbar or go to Run > Reset. The yellow highlighting disappears and the VBE comes out of Debug mode. 12. It is important to try and anticipate user error like this. The simplest way is to modify the code to simply ignore errors and move on to the next n ext task. Do this by adding the line… On Error Resume Next … immediately above the first line of the macro (underneath the line Sub Macro1() 13. Run Macro2 as before, starting too high on the sheet. This time the line you typed tells Excel to ignore the line of code that it can't execute. There is no error message and the macro exits having done all it can. Use this method of handling errors with caution. This is a very simple macro. A more complex macro would probably not perform as expected if errors were simply ignored. Also, the user has no idea that something has gone wrong. 14. Modify the code of Macro2 to include a more sophisticated error handler thus: Sub Macro2() On Error GoTo ErrorHandler  ActiveCell.Offset(-5, ActiveCell.Offset(-5, -1).Range("A1").Select -1).Range("A1").Select Exit Sub ErrorHandler: MsgBox "You must start below Row 5" End Sub 15. This time the user is presented with a dialog box when something goes wrong. If there is no error the line Exit Sub causes the macro to finish after it has done its job - otherwise the user  would see the message even if there were no error. Improving Recorded Macros The good way to learn the basics of VBA is to record a macro and see how Excel writes its own code. Often, though, recorded macros contain much more code than is necessary. The following exercises demonstrate how you can improve and streamline code that has been produced by a recorded macro. Exercise 2: Improving on Recorded Macros This exercise shows that when macros are recorded, often more code is generated than necessary. It demonstrates the use of the With statement to précis the code.

1. Select any cell or block of cells. 2. Start the macro recorder and call c all the macro FormatCells. The Relative References setting will not be relevant.

35

3. Go to Format > Cells > Font and choose Times New Roman and Red . Go to Patterns and choose Yellow . Go to Alignment and choose Horizontal, Center  Go to Number  and choose Currency . 4. Click OK and stop the recorder. 5. Click the Undo button (or Ctrl+Z ) to undo your changes to the worksheet. 6. Select a block of cells and run the FormatCells macro. Note that it can not be undone! Type in the cells to check the result of the formatting. 7. Look at the code: Sub FormatSelection() Selection.NumberFormat Selection.NumberFormat = "$#,##0.00" With Selection .HorizontalAlignment .HorizontalAlignment = xlCenter  .VerticalAlignment .VerticalAlignment = xlBottom .WrapText = False .Orientation = 0 .ShrinkToFit = False .MergeCells = False End With With Selection.Font .Name = "Times New Roman" .FontStyle = "Regular" .Size = 10 .Strikethrough = False .Superscript = False .Subscript = False .OutlineFont = False .Shadow = False .Underline = xlUnderlineStyleNone xlUnderlineStyleNone .ColorIndex = 3 End With With Selection.Interior  .ColorIndex = 6 .Pattern = xlSolid .PatternColorIndex = xlAutomatic End With End Sub

36

8. Note all the extra instructions that have been recorded. Delete lines of code so that only the following remains: Sub FormatSelection() Selection.NumberFormat Selection.NumberFormat = "$#,##0.00" With Selection .HorizontalAlignment .HorizontalAlignment = xlCenter  End With With Selection.Font .Name = "Times New Roman" .ColorIndex = 3 End With With Selection.Interior  .ColorIndex = 6 End With End Sub 9. Run the macro to test the edited code. It still works as before. 10. Now modify the code even further: Sub FormatSelection() With Selection .NumberFormat = "$#,##0.00" .HorizontalAlignment .HorizontalAlignment = xlCenter  .Font.Name = "TimesNewRoman" "TimesNewRoman" .Font.ColorIndex = 3 .Interior.ColorIndex = 6 End With End Sub 11. Test the macro. Everything still works and the code will run much faster. 12. Try recording the same macro using toolbar buttons instead of going to the dialog box: Change the Font to Times New Roman Change the Font Colour to Red  Change the Fill Color to Yellow  Click the Center button Click the Currency button 13. Look at the code. You still get lots of stuff that you don’t necessarily want. Excel is recording all the default settings. Most of these are safe to delete. 14. Experiment with editing directly directly into the code to change colours, the font, the number format etc. Exercise 3: Watch a Macro Being Recorded This exercise shows that you can learn by watching the macro build as it is being recorded. It is also an example of when sometimes the With statement isn’t appropriate.

1.

Open the file VBA01.xls.

Whilst this worksheet is visually OK and can be understood by the user, the presence empty

37

cells can cause problems. Try filtering the data and see what happens. Go to Data > Filter > Autofilter and filter by Region or Month. It is clear that Excel does not make the same assumptions that the user does. The empty cells need to be filled. 2. Tile the Excel and VBE windows (vertically) so they are side-by-side. 3. Select any cell within the data. If it is an empty cell it must be adjacent to a cell containing data. 4. Start the macro recorder and call the macro FillEmptyCells . Set to record Relative References. 5. In the VBE window find and double-click the module (Module1) for the current workbook to open the editing pane, then switch off the Project Explorer window and the Properties window (only to make space). 6. Record the new macro as follows: Step 1. Ctrl+* (to select the current region) Step 2. Edit > Go To > Special > Blanks > OK (to select all the empty cells in the current region) Step 3. Type =[UpArrow] then press Ctrl+Enter (to place your typing into all the selected cells) Step 4. Ctrl+* (to select the current region again) Step 5. Ctrl+C (to copy the selection - any method will do) Step 6. Edit > Paste Special > Values > OK (to paste the data back into the same place but discarding the formulas) Step 7. Esc (to come out of Copy Mode) Step 8. Stop Recording. 7. Look at the code: Sub FillEmptyCells() Selection.CurrentRegion.Select Selection.SpecialCells(xlCellT Selection.SpecialCells(xlCellTypeBlanks).Select ypeBlanks).Select Selection.FormulaR1C1 Selection.FormulaR1C1 = "=R[-1]C" Selection.CurrentRegion.Select Selection.Copy Selection.PasteSpecial Selection.PasteSpecial Paste:=xlValues, Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _  False,, Transpose:= False False Application.CutCopyMode Application.CutCopyMode = False End Sub 8. Note the use of the space-and-underscore “ _” to denote the splitting of a single line of  code on to a new line. Without this Excel would treat the code as two separate statements. 9. Because this macro has been recorded with well thought out commands, there is little unnecessary code. In the Paste Special everything after the word “xlValues” can be deleted. 10. Try out the macro. Then use the AutoFilter tool and note the difference.

38

Tip 6.1 : Sum the digits numbers in a cell using custom VBA function in Microsoft Excel Alt+F11 to open Visual Basic Editor (VBE). From the Insert menu, select Module (to add a module). Enter the following lines of code into the module: • • •

Function SumDigits( SumDigits(Number) Number) Dim i As Integer For i = 1 To Len(Number) SumDigits = SumDigits + Val(Mid(Number, i, 1)) Next i End Function To test the function: • • • •

To test the function, open Paste Function (Shift+F3). From the User Defined category, select the SumDigits function. In the function box, select any cell that contains a date. Click OK.

Tip 6.2 : Hide an excel sheet without the option of unhiding it using VBA in Microsoft Excel

To hide a sheet so that no body can unhide it without knowing the password for the Vb Project, simply open the VB Editor and change the visible property to 2 i.e. xlsheetveryhidden. The sheet should disappear from the Unhide sheets command command.. The only way to unhide it is to change the property back to 0 i.e. xlSheetNormal using the password to the VBProject.

39

Tip 6.3 : Convert negative values va lues treated as text using VBA in Microsoft Excel When you import numbers from data sources outside Excel it sometimes happens that the negative values is treated as text if they have the minus sign after the value. With the macro below you can convert these negative numbers to a valid negative value Excel can perform calculations with: Sub ConvertNegNumbers() Dim cl As Range, a As Integer  If TypeName(ActiveSheet) "Worksheet" Then Exit Sub  Application.ScreenUpdating  Application.ScreenU pdating = False  Application.StatusBar  Application.Stat usBar = "Converting negative values..."

40

a = Selection.Areas.Cou Selection.Areas.Count nt If a = 1 And Selection.Cells.Count = 1 Then ActiveSheet.UsedRange.Select ActiveSheet.UsedRange.Select For a = 1 To Selection.Areas.Count For Each cl In Selection.Areas(a).Cells Selection.Areas(a).Cells If Right(cl.Formula, 1) = "-" Then cl.Formula = "-" & Left(cl.Formula, Len(cl.Formula) Len(cl.Formula) - 1) End If  Next cl Next a  Application.StatusBar  Application.Stat usBar = False  Application.ScreenUpdating  Application.ScreenU pdating = True End Sub

Tip 6.4 : Set up conditional formatting for an area with VBA in Microsoft Excel

Question: In the selected area, the maximum value is to be marked violet with a conditional formatting Answer: Enter following code in a standard module. Sub ConditionalForm ConditionalFormat() at() With Selection .FormatConditions.Delete .FormatConditions.Add .FormatConditions. Add Type:=xlExpression, Formula1:= _  "=" & Range("Field"). Range("Field").Cells(1).Addres Cells(1).Address(False, s(False, False) & _  "=MAX(" & Selection.Address & ")" .FormatConditions(1).Interior.Col .FormatConditions (1).Interior.ColorIndex orIndex = 39 End With End Sub

41

Tip 6.5 : Build an Excel Add-In in Microsoft Excel About Add-Ins

An Excel Add-In is a file (usually with an .xla or .xll extension) that Excel can load when it starts up. The file contains code (VBA in the case of an .xla Add-In) that adds additional additional functionality to Excel, usually in the form of new functions. Add-Ins provide provide an excellent way of increasing the power of Excel and they are the ideal vehicle for distributing your custom functions. Excel is shipped with a variety of  Add-Ins ready for you to load and start using, and many third-party Add-Ins are available. This article shows you how to write a custom function using Excel VBA and how to save and install it as an Add-In. Custom functions are often referred to as UDFs (User Defined Functions). If you have never built a UDF before, this is a good place to start, or you might like to take a look at the tutorial Writing Your First VBA Function in Excel which demonstrates the process in detail with some more

examples. In the Excel tutorial Working Out a Person's Age - An Introduction to Nested IF Statements I showed how to use IF statements to calculate someone's age from their date of birth. Surprisingly, Excel does not have a built-in function for this commonly-required commonly-r equired calculation so it is an ideal candidate for a custom function. If you are already comfortable comfortable with writing custom functions, you can go straight to the section explaining how to save your UDFs UDFs as an Add-In. Add-In. [Jump to Add-In section] section] Write the Function An Add-In can contain as many UDFs as you want, and you can add more later simply by opening and editing the Add-In file. Step 1: Add a Code Module to a New Workbook

Start Excel or, if you already have Excel open, create a new empty workbook. Open the Visual Basic Editor from Tools > Macro > Visual Basic Editor (Keys: ALT+F11). In the Project Explorer pane select VBAProject (Book1). This selects the empty workbook.

If you were already working in Excel the name might be different - check the name in the title bar of the Excel window if you aren't sure. If the Project Explorer is not visible open it by going to View > Project Explorer.

42

From the Insert menu choose Module. This adds a new empty code module to the selected workbook. You will also see the module appear in the Project Explorer pane.

Step 2: Enter the Code

In the code window type the line... Function Age(DoB As Date) ...and press ENTER. The VB editor automatically enters the line "End Function" and places your cursor in the empty space between them. Typing "Function" defines the code that follows as a function, as opposed to a macro or subroutine, which is denoted by the word "Sub". Next is the function's name, which can be anything you like. Keep your function names simple and descriptive. Spaces aren't allowed so separate words with underscores (e.g. Age_in_years) or, preferably, with capitals (e.g. AgeInYears). A function usually needs one or more "arguments". These are entered in brackets after the function name. An argument is a piece of information that the function uses to perform its calculation. When declaring the arguments it is good practice to specify the data type. In this case only one argument is needed, the date of birth that will be used to calculate the person's age. For simplicity, I have called this argument "DoB". Arguments work like variables in macros. When you type the word "As" after the argument's name the VB editor presents you with a list of possible entries. You can type or pick from the list.

Between the Function and End Function statements, press TAB (to indent your code for clarity) and type the line...  Age = Int((Date - DoB) / 365.25)

This tells Excel how to work out the function. It uses two built-in functions, INT (which makes a whole number - or integer - out of the result) and DATE (a visual basic function equivalent to Excel's TODAY() function that returns the current date).

43

The statement effectively reads... "Take today's date and subtract from it the supplied date of birth. Divide the result by 365.25 and show the answer as a whole number by rounding down." The finished function should look like this: Function Age(DoB Age(DoB As  As Date) Date)  Age = Int((Date - DoB) / 365.25) End Function

Step 3: Test the Function

You can try out the function right away. Switch to Excel and in your empty workbook (the same one that you are using to create the function's code module) enter a date into a cell. In another cell enter your function in the same way as you would use one of Excel's built-in functions, e.g. =Age(A1)

A UDF is available to all open workbooks whenever its host workbook (the workbook containing the UDF's code module) is open. However, if you try to use the function in a different workbook you can encounter a problem...

The other workbook can't find the function so the #NAME? error appears. To avoid this happening you could add the host workbook's name to the function to tell Excel where to find it.

This works but is very clumsy and demonstrates one of the reasons why the best place for your custom functions is inside an Excel Add-In (with some exceptions... see note below.) below.)

44

Adding Features to the Function Allowing for the Absence of Data

A disadvantage of many functions is that when you prepare a worksheet in advance of its receiving data (e.g. in a template where you want the functions to be in place ready to calculate the user's input) the functions try to calculate on empty cells, often producing errors or nonsense results. If our Age function tries to calculate an empty cell it still produces a result, in this case 102 (the current year being 2002). This happens because it takes the value of the empty cell to be zero, and interprets day zero as January 0 1900. This is logical to Excel because the first day it knows about is day 1, which is January 1 1900. Normally you would try to anticipate this by entering your age function as part of an IF statement e.g. =IF(ISBLANK(A1),"",age(A1)) The IF statement tells Excel to enter a value of "nothing" (represented by "") if the data cell is blank but to calculate the Age function if it contains a value.

' This works fine, but you can save yourself the trouble by incorporating this sort of  troubleshooting into the code of the function itself. Modify the function code as follows: Function Age(DoB As Date Date)) If DoB If  DoB = 0 Then  Age = "" Else  Age = Int((Date - DoB) / 365.25) End If  End Function

Alternatively a custom error message could be included by replacing the pair of  quote marks in code line 3 with a message in quotes e.g. Age = "No Birthdate" . The result would be...

45

Making the Function More Accurate

The calculation used in the example above is very accurate, but not completely accurate. It works on the principle that there is an average of 365.25 days in a year (usually 365 but 366 every fourth year) so dividing a person's age in days by 365.25 should give their age in years. This works fine most of the time but it can (rarely) throw up an error. If t he person in question has their birthday today and were born on a year that is a multiple of 4 years ago, the calculation will be a year out. A small possibility, but if we're going to do it we might as well do it right! In my tutorial Working Out a Person's Age - An Introduction to Nested IF Statements I showed how to use IF statements in Excel to calculate someone's age from their date of birth, with complete accuracy. I could do the same in VBA for my custom

function (although the syntax of a VBA IF statement is slightly different to that in Excel) but I prefer to use a CASE statement. Excel doesn't have the CASE statement but VBA does. I find CASE statements easier than IF statements to figure out when the logic is slightly complex. Here is the code for my improved function: Function Age(DoB As Date Date)) If DoB If  DoB = 0 Then  Age = "No Birthdate" Else Select Case Month(Date) Case Is < Month(DoB)  Age = Year(Date) - Year(DoB) - 1 Case Is = Month(DoB) If Day(Date) If  Day(Date) >= Day(DoB) Then  Age = Year(Date) - Year(DoB) Else  Age = Year(Date) - Year(DoB) - 1 End If  Case Is > Month(DoB)  Age = Year(Date) - Year(DoB) End Select End If 

46

End Function

TIP: Select the lines of code in the grey box above, copy them (Keys: CTRL+C) and paste them directly into your VBA code window (Keys: CTRL+V). How the code works...

Function Age(DoB As Date Date))

Gives a name to the function and declares that a single argument is needed, which must be a date.

If DoB If  DoB = 0 Then Age = "No Birthdate"

An IF statement to determine whether there is a value in the data cell. The value of an empty cell is read as zero. If  that is true then the function returns the text "No Birthdate".

Else Select Case Month(Date) Case Is < Month(DoB) Age = Year(Date) - Year(DoB) - 1

If the data cell is not empty, consider the month that it is today... If today's month is before (i.e. less than) the month of the person's date of birth, they have not had their birthday, so their age is this year minus their birth year minus 1.

Case Is = Month(DoB)

If today's month is the same as the month of the person's date of birth we need to know whether or not they have had their birthday yet so...

If Day(Date) If  Day(Date) >= Day(DoB) Then Age = Year(Date) - Year(DoB)

If the today is equal to or past the day of  their birthday, then they have had their birthday (or it is today) so their age is this year minus their birth year...

Else Age = Year(Date) - Year(DoB) - 1

...otherwise, they have not had their birthday so their age is this year minus

End If 

their birth year minus 1.

Case Is > Month(DoB)

If today's month is after (i.e. greater

Age = Year(Date) - Year(DoB)

than) the month of the person's date of  birth, they have had their birthday, so their age is this year minus their birth year.

47

End Select

Closes the CASE statement, the IF

End If 

statement and the Function.

End Function This calculation may seem rather complex but you only have to type it once! When you have created your function all you ever have to type is its name. Creating an Excel Add-In Step 1: Adding a Description to the Function

When a function is inserted via the function wizard (i.e. the Paste Function tool) the user sees a description of the function that helps them choose the correct one. This isn't the case with custom functions ...

48

If you want a description you have to add it yourself. Here's how... Go to Tools > Macro > Macros to open the Macro dialog box. You will see all available macros listed but no custom functions. In the Macro name: text box type the name of the function you want to describe

Click the [Options] button to open the Macro Options dialog box. (If the Options button is greyed out the function name you entered has not been recognised. Check your typing.) Type a description for your function in the Description: text box...

Click [OK] to close the Macro Options dialog and then click [Cancel] to close the Macro dialog. The description has now been assigned to the function. You can repeat the procedure to amend the description if required. This description is now shown when the custom function is selected in the Function Wizard [click the thumbnail below to see a full-sized image]...

49

Step 2: Save the Workbook as an Add-In The workbook containing your code module now has to be saved as an Excel Add-In (*.xla) file. In the Excel window go to File > Save to open the Save As dialog. Enter a name for your Add-In file (the usual file naming rules apply) and use the Save as type: option to change the file type to Microsoft Excel Add-In (*.xla) .

50

Before clicking [OK] check the location in which you are saving the Add-In file. This will vary depending upon your particular set-up. On my computers the locations are: Excel XP(2002) on Windows XP: C:\Documents C:\Docume nts and Settings\User Settings\UserName\App Name\Application lication Data\Micros Data\Microsoft\AddIns oft\AddIns Excel 2000 on Windows 98: C:\Windows\Application C:\Windows \Application Data\Micro Data\Microsoft\AddIns soft\AddIns Excel 97 on Windows 98: C:\Program Files\Microsoft Office\Office\Lib Office\Office\Library rary

You can store your Add-In anywhere you like but, if you want it to be listed along with the built-in ones, you should save it into the correct location. Excel XP and Excel 2000 will automatically take you to the correct folder but Excel 97 does not. TIP: To check the save location, first set the Save as type: to Microsoft Excel Add-In then open the Save in: drop-down list to reveal the path to the save folder. You can now close the original workbook (Book 1). You do not need to save the changes if prompted. Step 3: Add a Description to the Add-In It is a good idea to add a description to the Add-In itself. This description will be displayed in the Add-Ins dialog box when you choose an Add-In to install. First, use the file manager to locate your Add-In file. Right-click on the file icon and choose Properties from the context menu. In the file properties dialog click the Summary tab. Type a description of your Add-In in the Comments: text box. If  you wish you can also type a name for your Add-In in the Title: text box. This is useful if you have chosen a short or cryptic name for your *.xla file but would like to show a more descriptive name in the Add-Ins dialog. I could give my Add-In file the filename mgfunctions.xla but assign it the title Martin's Functions. Finally click [OK] to accept your changes. You Add-In is now ready for installation, and can be distributed to other users if required. Step 4: Install the Add-In If Excel has not been shut down since you created your Add-In (or since one was copied to the computer's hard disk) restart Excel to make sure that it refreshes its list of available Add-Ins. Go to Tools > Add-Ins to open the Add-Ins dialog. If you have stored your Add-In in the default location you will see its name displayed in the Add-Ins available: window (if you have stored your Add-In in a different folder, use the [Browse] button to find it). Click on your Add-In's name to see its description at the bottom of the dialog box.

51

To install your Add-In place a tick in the check-box next to your Add-In's name and click [OK]. [Click the thumbnail below to see a full-sized image]...

As soon as the Add-In is installed its functions will be available in Excel. Find them in the User Defined section of the Function Wizard (Paste Function Tool) or simply type them into a cell as you would any built-in function. The Add-In will remain installed until you return to the Add-Ins dialog and uninstall it by removing the tick from the check-box.

52

Making Additions and Changes to an Add-In Your Add-In file can contain as many modules and custom functions as you want. You can add them at any time. If your Add-In is installed you will see it listed in the Project Explorer pane of the VB editor. Locate the module containing your functions and make whatever additions and changes you want. If your Add-In is not installed, find the Add-In file and double-click it to open it in Excel. You will not be able to see it in the Excel window but it will appear in the VB editor's Project Explorer. Remember to save your changes! Do this from the VB editor window with File > Save [click the thumbnail below to see the full sized image]...

Adding Comments to Your Code It's easy to add notes (properly called "comments") to your VBA code. Enter an apostrophe (i.e. single quote mark) and then type. The apostrophe tells the code compiler to ignore everything that follows it on the same line so it isn't treated as executable code and the compiler doesn't try to run it. Anything you type after the apostrophe is "commented out" and is coloured green in the VB editor's code window...

You can use this technique to add explanatory notes to your code (ever returned to some code you wrote a while ago and wondered what on earth it means?).

53

You can also temporarily comment out lines of code so that they don't run - useful for testing your code. If you think you don't need a line of code, don't delete it but comment it out first. Then test your code to see if it still works. If everything is OK you can now delete the line. If your code fails, simply remove the apostrophe and your line of code is restored. Password Protecting Your Code VBA allows you to password-protect your code, whether it is the macro code behind a regular workbook or the code modules of an Add-In. Password-protecting code prevents unauthorised viewing of your code for purposes of security or copyright. To password-protect your Add-In locate it in the VB Editor. Right-click its name in the Project Explorer pane and choose VBAProject Properties... from the context menu. In the VBAProject - Project Properties dialog click the Protection tab. Place a tick in the Lock project for viewing check box, then enter and confirm your password. Click [OK] and go to File > Save to save your changes. [Click the thumbnail below to see the full-sized image].

The password-protection will take effect from the next time Excel is opened. Any attempt to view the Add-In's code module will result in a request for the password...

54

Assigning Add-In to Custom Toolbar Buttons and Menu Items Add-Ins aren't just for containing functions. They may contain useful macros. You may want to assign a macro that is contained in an Add-In to a custom toolbar button or custom menu item. Normally to do this you would right-click on your new button or menu item and choose Assign Macro and pick your macro from the list provided. However, the names of macros contained in Add-Ins are not shown in the list. Don't worry! Just type the name of the macro in the Macro Name: box at the top of the dialog. Excel will find it and the macro will run as expected when the button is clicked or the menu item chosen. A Final Word of Caution! A custom function that is located in a code module within a workbook will go wherever the workbook goes. In other words if you open the workbook file on a different machine, or e-mail it to someone else, the function t ravels with the workbook and will always be available. If your workbook refers to a custom function contained in an Add-In, the workbook will only be able to calculate the function when the Add-In is present. If you mail the workbook to someone else you will have to mail them the Add-In too! If you want to use custom functions contained in an Add-In in a the code of another workbook, you will have to set a reference to the Add-In. Read the article How to Use Your Excel Add-In Functions in VBA for details.

55

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF