Module-I Extend Your Insight Office Excel 2010 02 Extend Your Insight Office Excel 2010 F
Module-I Extend Your Insight Office Excel 2010 02 Extend Your Insight Office Excel 2010 F
Module-I Extend Your Insight Office Excel 2010 02 Extend Your Insight Office Excel 2010 F
50
15
You can now use the “label range name” in calculations.
For example, this formula:
=SUM(Year99) returns the value 140. The formula =SUM(Year99, 100) returns the value 240.
As a quicker alternative to using the Insert, Name, Label command, you can select a range (not including its header)
and use the Name Box to assign a range name. Then use that range name in calculations, as above. A named cell (or
range) is treated as an absolute reference in a formula. If you assign a cell or range a name and then want to change
it, you can. But Excel offers no simple method. The only way to change a range name is to use Insert, Name, Define,
add the new name, and then delete the old name.
Understanding Relative, Absolute, & Mixed Addressing
You may often want to use the same formula in one or more places in a worksheet. It’s most efficient to build the
formula one time and then copy it to the other locations where you need it. If you copy a formula, you must understand
Excel’s relative and absolute addressing. When you copy a formula Excel uses relative addressing as the default. That
is, when you copy the formula to a new location Excel adjusts the cell references in the copied formula relative to its
new location. In the illustration at left below, the formula in Cell D4 is used to calculate the total sales in January and
February for Dept 1: =(B4+C4). We need the same basic formula in Cells D5 and D6 for
Departments 2 and 3. Although we could enter two new formulas, it’s easier to copy the formula in D4 to these locations.
Point with the mouse to the “fill box” at the lower righthand corner of Cell D4 and drag down through Cells D5 and D6
to copy the formula. For each copied formula, Excel automatically adjusted the cell references to refer to the data in
the correct row. This is Excel’s default mode when copying formulas. It’s relative addressing. 20
There may be occasions, however, when you want to override Excel’s relative addressing default. In the example
below, the formula in Cell E4 (in the Tax column) multiplies the Dept 1 Total Sales value (Cell D4) and the 5% value
(Cell B1). The result is correct for this row. However, if we copy the formula in E4 down to E5 and E6 for Depts 2 and
3, the result for those rows is not correct. In the absence of any other instruction, Excel has again used relative
addressing in the formula copy. The formulas in Cells E5 and E6 read as follows:
=D5*B2
=D6*B3
The first reference in each of these formulas is OK. We do want the copied formulas to refer to the Total Sales values
for their respective rows (Cells D5 and D6). The problem is with the reference to Tax in Cell B1. The master formula in
Cell E4 correctly reads =D4*B1. But the copied formula in E5 refers to Cell B2 (an empty cell), resulting in a calculation
of $0.00. And the copied formula in E6 refers to Cell B3 (which holds the text value “Jan”), resulting in a #VALUE error
statement. To make sure the copied formulas in this case refer to the correct Tax cell, use absolute addressing for
the reference to Tax. Absolute addressing in a formula fixes the reference to a cell no matter where the formula is
copied. Absolute addressing can apply to a single cell, a range of cells, or to one, several, all, or none of the cells
referred to in a formula.
Specify absolute addressing with a dollar sign (an arbitrarily selected symbol) before the row reference and the column
reference. For example, a relative reference in a formula to the Tax value in Cell B1 is written as B1. An absolute 21
reference in a formula to the Tax value is written as $B$1. (It’s also possible to “fix” just the row but not the column by
writing B$1 or just the column and not the row by writing $B1. This is called mixed addressing.)
Here we specified absolute addressing to refer to the Tax cell in the “master” formula in E4. Copying the master formula
to E5 and E6 results in correct values for those formulas.
Tip: When positioned over a cell or range reference on the formula bar, the F4 key cycles through the four addressing
options: completely relative, completely absolute, absolute row but not column, and absolute column but not row. That
is: B1, $B$1, B$1, and $B1.
Finding Formulas
Excel’s Go To feature provides a quick way to identify all the calculations in your worksheet. Click Edit, Go To or hit F5
to open the Go To dialog. Click the Special button on the Go To dialog to open the “Go To Special” dialog. In the “Go
To Special” dialog, choose “Formulas” and the type of data you want to select. Then click OK. Excel highlights all the
formulas of the type you selected. Using the Go To, Special,
“Errors” option to find incorrect formulas can be useful when debugging a spreadsheet.
Data Form
When a spreadsheet is designed for data the menu item Data: Data Form can be used for data entry. Select Data Form
from the Data menu. Click on the New button in the upper right corner. Enter the data shown below. Use the Tab key
to move to the next field blank. Do NOT use the down arrow key: it will cause the Data form to "go blank." The reason
for this is because the down arrow generates a next New record.
Use of the tab key to move from one field to the next has been a standard in the data entry industry for over 30 years.
The Tab key will work in Excel, Microsoft Access, and fill-in-the-blank fields found on the Internet and all other data
entry applications.
The Choose function
The choose function selects the Nth item from a list. The syntax for choose is
=choose(n,firstItem,secondItem,thirdItem,fourthItem,…) where n must be a cell address that contains an integer. The
Nth item is chosen by the integer. Click in the cell P2.
Enter =CHOOSE(O2+1,"F","D","C","B","A")
Note the O2+1: there is no zeroth item allowed in choose. The O2+1 converts a GP of 0 to 1 (there is no zeroth element
of a list in Excel. Special note for users of Microsoft Works only: In a single encounter with Microsoft Works 4.0 there
appears to be a zeroth element in the choose function.)
Fill down the grade column. The worksheet should now look something like:
A B C D E F G H I J K L M N O P
Cours Sec S T T T Grad
1 e t Last First x S t HS Elem Lang 1 2 3 Av g Pass GP e
M0 Abena KH 8 8 8 Promo
MS
101 8 Albert a F K S Lelu Kosraen 3 2 1 82 te 3 B
2
M0 7 7 7 Promo
MS
101 8 Aldis Adjoa F P PIC S PCS Pohnpeia n 7 7 7 77 te 2 C
3
C
M0 CH Puluw Puluwate 9 9 9 Promo
MS
101 8 Elidok Ama F S at se 4 2 0 92 te 4 A
4
MS
101 M0 Georg e Kwek M K KH Male m Kosraen 5 5 6 59 Repeat 0 F
5
8 u S 8 9 0
Charting
Note that Office 97 does things a little differently in a slightly different order with dialog boxes that, unfortunately, look
very different. Design for charting is like designing for data. Include a field name row at the top of the data. Make the
leftmost ("first") column a column of labels. The Dist worksheet is set up this way already.
Grade GP Count
C 2 8 Column chart
D 1 6 What many call a "bar chart" Excel calls a "Column chart" or column graph.
F 0 3 To make a column chart, select the cells A1 to A6. Hold down the Control (Ctrl) key and select
the cell C1 to C6. The control key allows the selection of non-adjacent data. Always include all
label rows and columns in the selection, this will cause automatic labeling of the chart axes.
Click on Next to leave step 1.
Click on Column chart option in the middle of the top row of step 2 and then on Next. Click on format option 1 in the
upper left corner of step 3 for a basic column chart and then on Next.
The dialog box for step 4 is the first of two options dialog boxes that are important. This is where one can specify
whether the data is in rows or columns. If one has more than one label row or column, this is the place to specify
multiple label rows or columns. We have only one label column if we used the Control key properly. Excel should have
chosen the following set-up:
In step 5 options dialog box select No under "Add a legend?" For a single data set a legend is unnecessary. If desired,
type in a chart title, x-axis and y-axis label. Click on finish
Other types of charts: Population Pyramid
Age Female Male
0-4 -7117 7545
5-9 -7158 7932
10-14 -7288 7656
15-19 -5893 6532
20-24 -4703 4489
25-29 -3528 3514
30-34 -3407 3393
35-39 -2949 3049
40-44 -2456 2975
45-49 -1660 1941
50-54 -1160 1111
55-59 -1091 998
60-64 -9651013
65-69 -669639
70-74 -627542
75-79 -281263
80-84 -176137
85-89 -58 41
-30
90-94 26
95-99 -8 4
There are many types of charts available. The math teacher is likely to find the x-y scatter diagrams useful for graphing
functions. Put the x values in the first column and the y-values or a function in the second column.
Excel will, with a little thought, make specialty graphs that are not immediately evident from an inspection of the chart
wizard. In attempt to stretch thinking, the following will produce a population pyramid type chart.
Select the data including the field names row and the labels column. Note the use of negative values for the first column.
Click on the Chart wizard button in the tool bar.
Drag the mouse to set the location of the chart on the worksheet.
Click on Next.
Click on Bar chart option and then on Next.
Click on option 8 for then on Next.
This first of two options dialog boxes is important. This is where one can specify whether the data is in rows or columns.
If one has more than one label row, this is the place to specify multiple label rows. It is likely that no adjustments need
to be done for this graph: Excel 95 will likely "guess" correctly based on the existence of a field name row and the label
column. Click on Next when done.
In this second options dialog box select Yes under "Add a legend?" The wizard may already have selected yes. For
two or more data columns a legend is informative. A field name row is necessary for Excel to correctly set up the legend.
Type in a chart titled, x- axis, and y-axis labels. Click on finish.
Click on the Options button in the Chart Type dialog box. Click on the Options tab at the top of the Format Bar Group
dialog box.
Set the Overlap to 100 and the gap width to 0. Click on OK. Click outside the area of the graph to turn off the hash
mark border. This also takes Excel out of the graphing mode and into the regular mode.
Intermediate Excel: Subtotals
Using Excel to generate subtotals by course and section
Suppose we wanted to know whether our course averages differed from one section to the next or wanted to know the
relative performance of the students by state or gender. Excel can sort and summarize such data using subtotals. In
order for Excel to generate subtotals the data must be sorted by the criterion to be summarized.
Click in cell A1 of the Grades sheet of the Gradebook workbook. Do not select any cells: sort will make the presumption
that only the selected cells are to be sorted and will mix up the data. Choose Sort from the Data menu. Excel should
have detected the field names and the radio button "My List has… Header Row" should already have been selected
by Excel. Good initial design for data is important to proper sorting and subtotaling. Sort by Course and Then By Sect
and Then By Last (name). Click on OK.
Set up the subtotals Choose Subtotals from the Data menu in Excel.
Set at "At Each Change in" to Sect by clicking on the downward pointing triangle on the right side of the "At Each
Change in" list box.
Set the "Use Function" list box to Average.
In the "Add Subtotal to:" list click on the check boxes next to T1, T2, T3, Avg, and GP. Scroll the list box to see T1, T2,
T3, Avg, and GP. Click on OK.
Note the change in the worksheet: a new panel has appeared on the left, the subtotals control panel. There are three
levels shown at the top by three numbered buttons. Click on button number 1 to see only the Grand Average.
Click on button number 2 to see the individual section averages. Note the buttons with the plus signs that appear.
Clicking on a plus sign button opens up the details for a single section. After clicking on a plus button, a minus button
appears. Click on the minus button to collapse the section.
Click on button number 3 to see the list of all students.
Suppose we now wanted to see the overall student averages by state. Changing a subtotals view is a three phase
process.
1. Remove the existing subtotals 2. Resort by state (the new criteria)
3. Reapply the subtotals.
The key concept here is that the sort order must mirror the "subtotal at each change in" choice. Subtotals subtotal at
each change as Excel moves down the list. If the states are not in alphabetic order, then at each and every change of
state from row to row Excel will insert a subtotal. Subtotals on one field cannot be resorted on another without removing
all existing subtotals first, hence the first step of removing the subtotals.
Phase one: Choose Subtotals from the Data menu and then click on the Remove All button.
Phase two: Choose Sort from the Data menu. Sort by State and Then By Sect and Then By Last Click on OK.
Phase three: Set up the subtotals.
Choose Subtotals from the Data menu in Excel.
Set at "Each Change In" to State by clicking on the downward pointing triangle on the right side of the Each Change In
list the Use Function list box to Average.
In the "Add Subtotal to:" list the check boxes may still be checked from the earlier exercise. If they are not checked,
then click on the check boxes next to T1, T2, T3, Avg, and GP. Scroll the list box to see T1, T2, T3, Avg, and GP. Click
on OK.
Other subtotal functions
Subtotals functions include sum (the additive total), count (how many items), the average, the maximum value in the
subset, the minimum value in the subset, and standard deviations among other specialized functions. The sum and
average functions are the most commonly needed functions. On the worksheet tab labeled Inventory is an example of
an inventory spreadsheet demonstrating the use of the Sum function to tally up the value of property in the A204
laboratory. Click on the Subtotal control panel numbered buttons to explore the different levels of this spreadsheet.
Filtering
Filtering allows one to display subsets of the data based on specific condition. Suppose we want to display only the
students who will be on the deficiency list, those with an average less than 70. Start filtering by removing the subtotals.
Choose Subtotals on the Data menu and then click on the "Remove All" button.
Choose Sort on the Data menu and sort by last name and then by first name. Click on OK.
Scroll to the top of the worksheet. From the Data menu choose Filter. On the submenu that pops up choose Autofilter.
Small grey buttons with triangles in them should appear in the top row of your spreadsheet.
Click on the grey button in the M (Avg) column to see a "drop- down" list of options. This list includes preset values one
can select to filter the data. Choose (Custom…), the third item down the list. The following dialog box should appear:
Use the little "down triangle" button to the right of the equals sign in the first blank under the word "Avg" to choose a
less than < sign.
Either select 70 from the drop down list in the next box or type 70 in the next blank box as seen above. Click on OK.
The result is a list of students who are deficient (below 70). If one chooses print with a filter on then only the names
shown will print.
Getting back all of your data: Choose Filter again from the Data menu and this time select "Show All" on the submenu.
Filters are another powerful use of Excel provided that your spreadsheet is set up in database format (field names in
row one and no blank rows, one physical item per row in rows two and higher). Assets larger or smaller than a given
number could be displayed, or students with a TOEFLs above or below a specific point could be shown. The "Top ten"
filter option can display just that, the "top ten" in a category.
Pivot tables
Using Excel to set up a pivot table to study course versus gender grade averages. This section presumes that the
worksheet named Dist has already been inserted in the workbook during work on the frequency function.
Pivot tables are easiest to set up when the spreadsheet is designed for data. Field names should be in row one of the
table, with data below. There should be no blank rows within the data.
Pivot tables (known in Microsoft Access as a cross-tab table) groups data by two categories, producing summary
information such as average, sum, or count according to two or more categorizations. As a part of this process, pivot
tables have the ability to take categories in data rows and turn them into field names. The result feels like a "rotation"
of the data, hence the name Pivot table. As an example, the data on the left below is pivoted to produce the result on
the right.
A B C D E F G H
Average of T3
1 State Sex T3 Sex
Pohnpei F 80 F M Grand Total
2 State
Pohnpei M 65 Chuuk 82.5 67.5 75
3
Pohnpei F 70 Pohnpei 75 70 72.5
4
Pohnpei M 75 Grand Total 78.75 68.75 73.75
5
Chuuk F 95
6
Chuuk M 60
7
Chuuk F 70
8
Chuuk M 75
9
The result are averages based on state and sex. The data in the Sex column, F and M, has become field names in a
new row one of a table. The data has, in a sense, been "pivoted" or "rotated" up out of a column and tabulated across
as field names in a new table (hence the use of term "cross-tab" by Microsoft Access).
To start a pivot table in the Gradebook workbook, click anywhere inside the field row or the data rows of the Grades
worksheet. Do not select a cell, just have the cursor in a cell inside the data to be pivot tabled. Choose Pivot Table from
the Data menu. Click on Next in the first dialog box. The default Microsoft Excel List or Database is usually selected
and is the correct selection.
Click on Next in the second dialog box. If the spreadsheet is designed properly for data then Excel will have correctly
detected the data range.
Dialog box three presents the screen where choices are made as to row and column groups.
Drag and drop the button marked State (St) from the right hand area of the dialog box to the area marked Row.
Drag and drop the button marked Sex (Sx) from the right hand side to the Column area.
Drag and drop the button marked Avg from the area on the right to the Data area.
Double click on the Avg button in the Data layout area at the center of the screen. From the PivotTable Field pop- up
dialog box choose the function average. Note that all of the basic functions are available including sum, average, and
count among others. These are the same functions we encountered on the first day. Click on OK.
Click on Next.
The next dialog requests a location for the pivot table. Click on the Dist worksheet tab (created during the frequency
function lesson). Click in A15 (below the chart if one exists in the grade book). Click on Finish.
The data in the resulting PivotTable summarizes averages by state and sex for the fictional College of Micronesia-FSM
spreadsheet. To make the data more presentable:
Select the data in the pivot table by dragging the mouse across the number data.
Choose Cells… on the Format menu.
The dialog box should open to the Number tab. If not, click on the tab marked Number.
Click on the item Number in the Category list box.
Note the default number of decimal places is preset to 2. This can be changed. For now, click on OK and the numbers
in the table will be displayed to two decimal places.
Graphing Pivot Tables
The data in a pivot table can be graphed to produce charts as was covered in the second session. Be careful to select
only the state and sex breakdown data and not the grand total data. Look carefully at the diagram below and the note
following the diagram.
Making the selection shown must be done by dragging from C20 to A16. Dragging from
A16 to C20 is not possible as A16 is a button that activates when clicked
Note that in the particular chart shown has been adjusted by rotating the chart 180? from the initial position. This was
done by double-clicking on the chart and then choosing 3-D View from the Format menu. In the 3-D View dialog box
the rotation was set to 200? (initial rotation was 20?).
Pivot tables are best produced by good data designs. In turn, good data designs are produced by considering the pivot
table implications. Good design requires that each data row be a single object or instance, not a an aggregate of data.
Gradebooks almost naturally generate good data designs: a single student in a single class per row (a "student-seat").
In other applications forethought may be necessary. In a study of lizards, for example, proper design of a good table is
likely to involve listing each individual lizard in its own row. This would be as opposed to a table where each row was a
location and the data was the number of lizards in that location. The following fictitious table is not well thought out from
a pivot table perspective. For example, although the original tallies might have indicated the number of females with
tails, the resulting table has lost that information. The design is also prone to typographic errors that result in internally
inconsistent data: examine the sum of the number of males and females on trees.
Number
Location Number Num w/
Number of
of lizardsFemales of Males tail
Beach 2 1 1 0
Pond 6 3 3 5
River 8 5 3 4
Rock 7 5 2 7
Tree 10 6 5 9
A better design would have been:
Location Sex With Tail
Tree F 1
Tree F 1
Tree F 1
Tree F 1
Tree F 1
Tree M 0
Tree M 1
Tree M 1
Tree M 1
Tree M 1
Tree M 1
Pond F 0
Pond F 1
Pond F 1
Pond M 1
Pond M 1
Pond M 1
… and so forth. The resulting table can be subtotaled or pivoted to obtain accurate summary information. Although the
original data table will be lengthy, most reports will use the results of subtotal calculations and pivot tables. The table
may have typographic errors, but the totals will at least be consistent with the data, there will not be any internally
conflicting data. Typos will also not likely affect counts the way they can in the earlier table.
VLookup Function
In Excel, the VLookup function searches for value in the left-most column of table_array and returns the value in the
same row based on the index_number.
The syntax for the VLookup function is:
VLookup( value, table_array, index_number, not_exact_match )
value is the value to search for in the first column of the table_array. table_array is two or more columns of data that is
sorted in ascending order. index_number is the column number in table_array from which the matching value must be
returned. The first column is 1. not_exact_match determines if you are looking for an exact match based on value.
Enter FALSE to find an exact match. Enter TRUE to find an approximate match, which means that if an exact match if
not found, then the VLookup function will look for the next largest value that is less than value.
Simple Vlookup Tutorial
Let's assume we are given the following sales table:
If you wish to retrieve Dan's January sales (hence cell B3), the vlookup function will be: =vlookup("Dan" , a2:c4 , 2 ,
false)
Let's go over the different parts of the function in plain English (note the highlighted parts in the following sentence,
taken out directly from the formula):
The function will look for the word "Dan" at the first (left) column of the range a2:c4. It will retrieve the value adjacent to
it on the 2nd column (thus the "January" column). The word "False" tells the function to find Exactly the word "Dan",
and not something close or similar to it.
A way to make the function more readable is to name the table, and use this name in the vlookup function:
Select the table (no need to include the headers row), and write a name inside the name box (its located at the top left
of the screen). In our vlookup example, we used the name "salesTable" (Try to avoid using spaces).
Thus, the function can now look like this: =vlookup("Dan",salesTable,2,false).
And if you don't want to retrieve always Dan's January sales, but to retrieve the name that will be written in cell A6?
=vlookup(A6,salesTable,2,false)
And if you wish the function to retrieve February's sales (instead of January)?
=vlookup(A6,salesTable,3,false)
When and how should you use the Vlookup function?
When you have a table with data, and you wish to retrieve specific information from it.
Actually whenever you are looking up a name in a phone book, you are performing a “real” vlookup action: you look up
the name of your recipient on the first (most left) column, and when finding it, you retrieve the number appearing next
to that name. An implementation of the vlookup in Excel could be: You have an Excel table with student names and
their grades. You wish that you could somewhere in the sheet type a student name, and immediately retrieve his grade
(based on the data in the table). To achieve this, you can use "Vlookup": the function will look for the student’s name
in the first column in the table, and will retrieve the information that is next to is name in the second column (which is
his grade). Check the video links above to learn how exactly the vlookup function is written and implemented inside the
worksheet. Another vlookup example:
You have a big table consisting thousands of bank accounts.
You wish to retrieve in another worksheet information regarding some specific accounts. To achieve this, you can type
these specific account numbers, and put a Vlookup function next each one of them. The function will look for the
account numbers in the big table, and retrieve relevant information from it.
The difference between “Exact match” and “Closest match”:
When you use the Vlookup Excel function to retrieve information based on a student name or a bank account number,
you cannot allow it to find something close or similar to “Jake”, or close to the account number “3647463”, but rather it
has to find them exactly.
But sometimes you have a table that defines ranges, for example:
$5,000 – “Small deposit”
$20,000 – “Medium deposit”
$100,000 – “Big deposit” $500,000 – “Huge deposit”
If you want the Vlookup to find the description for a deposit of $23,000 (which should retrieve “Medium deposit”), you
will ask it to find a close match, and it will find $20,000. This is very useful when dealing with dates. Look at the following
table:
4/1/2008 – Payment on time.
6/1/2008 – Late with payment (small fine). 8/1/2008 – Very late with payment (big fine).
If you would like to find what happens with a payment made on 7/14/2008, the function will relate it to the date 6/1/2008
and retrieve us “Late with payment (small fine)”. Please note – the function will always retrieve the smaller closest
match (in case it doesn’t find an exact match). A drop down list enables you to choose a value from a list, instead of
typing it.
Creating a drop down list in Excel 2010:
1. Write the list somewhere inside the worksheet. It is recommended to have it sorted alphabetically in ascending
order, for this is the order in which they will appear in the drop down list.
2. Name the list, by selecting its range and writing its name in the name box. In this example we named it "cities":
3. Select the cell in which you want the drop down list to appear. In this example we selected cell B2:
4. Choose the "Data" tab from the ribbon.
5. Click the "Data Validation" button.
It will look like one of the two following examples, depends on your screen resolution:
OR:
6. A dialog box will appear. Click the words "Any value" and choose "List".
7. Click inside the "Source" text field, and write =[the name you gave to the list] (in our example: =cities).
8. Click the OK button.
Done! Now you have a drop down list inside your selected cell.
How to Import a Delimited File into Excel
Whether they are created manually or exported from another software application, delimited files are a commonly used
to store important data. The trouble with data is that it is not very valuable unless you have some way to manipulate
and study it. While delimited files are a nice way to store data, it’s not very practical to try to study the data in the raw
form of these files. Importing the delimited file into MicrosoftExcelwill allow you to use all the tools of Excel to analyze
your data and to present the findings of your analysis in a clear manner.
Step 1
Choose “Open” from Microsoft Excel’s File menu, and navigate to the folder that contains your delimited file. Make sure
that you have chosen the option to view all file types. If you don’t do this, you will not be able to see your file in the
folder. Double-click on the file name to open it. Excel will automatically enter “Text Import Wizard” mode.
Step 2
Choose “Delimited” as the file type that best describes your data on the first screen of the Text Import Wizard. Then
click “Next” to go to the next screen.
Step 3
Select the delimiter that is used in your delimited file. If you didn’t know what the delimiter was before beginning the file
import, you can usually scan the data and determine which character is being used. In our example, the file is comma-
delimited. After selecting the delimiter, click “Next” to proceed.
Step 4
Assign the data format to each field that you are importing. The default data format is “General,” and this is the format
you should keep unless any of your data fields contains dates or consists of data that you want to keep as text. Click
“Next” to finish the import after you have finished assigning data formats to all fields.
Step 5
Save the resulting spreadsheet as an Excel file. Now you are ready to manipulate and study your data with the tools in
Excel.
Excel Scenario Manager
Excel's Scenario Manager is a tool that can be used to determine different projected outcomes of data by changing
different cells within a Worksheet model. A scenario is a specific set of values that Excel can save for you and
automatically substitute into your Worksheet. This means that you could have a spreadsheet displaying numerical data
that is relevant to a certain date, month, topic or whatever and using the Scenario Manager you can enter different
values into the worksheet to forecast the outcome of the data. These values (or Scenarios) can be retained for future
use and are stored in a hidden part of the workbook which can be retrieved by asking the Scenario Manager to show
the Scenario that uses those specific values.
Remember, all that Scenarios are are just a different version of the same worksheet with each different version using
a different set of input values in the nominated cells.
For Scenarios to work correctly, you should first set up a base or default Scenario, on a worksheet in Excel. It is from
this default Scenario that all other Scenarios are defined.
Go to Tools>Scenarios to activate the Scenario Manager. You will see a message telling you "No Scenarios are
defined". Choose Add to add your default Scenario.
Give your Scenario a name, Base, Original or Default or a name you can easily identify will be fine.
Click in the next box Changing cells: You will notice here that the cell that was your active cell in the Workbook
will be referenced here.
Click the collapse dialog button to collapse this dialog box up so that you can easily select the cells from the
Worksheet that you wish to reference.
Click on the collapse dialog button again to expand the full Scenario Manager box. If you wish to type a comment
in, then click into the Comment: box and do so.
There are two options at the bottom of this dialog box. They are Prevent changes and Hide, with Prevent
changes being the default. If you select Prevent changes, then all your Scenarios will be locked and will be unable to
be edited. It is important to note here that you MUST also protect your Worksheet via the Tools>Protection>Protect
sheet option for this option to take effect. If you then with to edit your Scenarios, you must first unprotect your
Worksheet, then de-select the Prevent changes option to proceed. The Hide option when selected will do exactly as
said and Hide your Scenarios. This option also requires sheet protection for it to take effect.
Click the OK button. Once you click on the OK button the Scenario Values dialog box will appear. This is where
you must enter values into the scenario cells. As the first scenario is your default Scenario, the values in the cells that
we specified in the Changing Cells: box have been picked up so we need to make no changes here, we need only
click the OK button. This will now take us back to the Scenario Manager and you will see the name of your Scenario.
Adding Scenarios
There is no limit to the number of Scenarios that you can apply to your worksheet
model. Adding a scenario is done in basically the same way as creating a default scenario.
Go to Tools>Scenarios to display the Scenario Manager dialog box and select Add to display the Add
Scenario dialog box.
Under Scenario name: give your new Scenario a name. You need make no changes to the Changing cells: box
as the cells we nominated in your Default scenario show here.
Click OK. This will show the Scenario values dialog box and this time you will need to change the values.
Click OK.
You will now have two Scenarios available you.
Displaying Scenarios
Now you can display your Scenarios to show how they change the outcome of your data by asking the Scenario
Manager to show a particular scenario.
Select Tools>Scenarios
Click on the Scenario name you want to see Click Show.
Drag the dialog box out of the way and have a look at the values in the worksheet. One you have done this, click on
the next Scenario name and then Show, and again peruse the values in the worksheet. Click on Close when you
no longer wish to view your Scenarios.
Excel Consolidation to Consolidate and Summarize Data from Different Worksheets
Consolidation is the process of combining values from several ranges of data either from within the same or different
workbooks. It can be used to summarize data from different worksheets into master worksheet and create a report
using a variety of calculations. Consolidate is found under the Data Menu; Data>Consolidate.
Consolidate by Position
Used when worksheet data is identical in order and location. This type of Consolidation is the easiest and works using
a layering operation. This means that once you open the workbook(s) you wish to consolidate, you specify the ranges
to consolidate, then the values in one worksheet are overlaid on those of another worksheet until all the worksheets
are overlaid. It is then that you can select the calculation to be performed on your data. No formulas are used to
perform this type of Consolidation, although you can set up the consolidation to update automatically when the source
data changes, by checking the create links to source data box, rather than manually which is the default.
Consolidate by Category
Used when data is organized differently but has identical row and column labels. This type of Consolidation is a little
trickier to perform, but works in nearly the same way. When you select your data to consolidate, you must this time
include your row and/or column headings. Excel will then examine the row and/or column headings and will be able to
plot the layout of your Worksheets and Consolidate your data for you by examining the contents of the ranges to be
used.
Consolidate using 3-D Formulas
Used when worksheet data does not have a consistent layout or pattern. 3-D formulas are formulas that refer to multiple
worksheets and can be used to combine this type of data. A formula such as =SUM(Sheet1!A6,Sheet2!C12,
Sheet3!H9) can be used to add cells from different worksheets to consolidate into a Summary sheet. This type of
Consolidation does not use the Consolidate dialog box found under Data>Consolidate, but is created entirely as a
formula, so therefore will automatically update if the data it is dependent on changes
First Step: Taking advantage of the same table of data for the positions and salaries we saw before, we shall now
calculate the retention of income tax in accordance with the different salary bands.
Second Step: For this task, add a new column which should be placed next to the Salary column. Give it the tide Tax,
as shown in the illustration.
Third Step: On the “Tax” column, we calculate the tax retention for each employee. In this case, we have to use the
combination of functions IF and AND so that the condition deals with these three conditions.
Fourth Step: Click on the cell D4 and type in part of the formula “=IF(C4<=500;Exempt;” (Without the inverted
commas). If the condition holds true for the tested cell, there will be no tax retained for this position.
Fifth Step: To test the second salary band between INR 500 and INR 1,000, add the function AND, so that the formula
becomes i’=IF(C4<=500;”Exempt”;IF(AND(C4>500:C4<= 1 000 ;50;”.
Sixth Step: To finish the formula, add the argument 100 to the formula so that there is tax retention for the upper salary
band over INR 1,000. The complete formula is
“=IF(C4<=500:”Exempt”;IF(AND(C4>500;C4<= 1000 :50: 100))”
The Functions IF & OR
Employee benefits in accordance with the salary band and department in which each employee works.
First Step: Now, to illustrate the combined use of the functions IF and OR, we shall insert two columns in the position
and salary table - Health Plan and Department.
Second Step: In this case, the company offers the benefit of a health plan only for those workers who receive up until
INR 1,000 or who work in the Sales Department.
Third Step: To check which employees have the right to this benefit, select the first cell in the column Health Plan,
which in our case here is the cell E4 to insert the function. IF(B4=”Manager”;2500))) which corresponds to the condition
test for the three positions and their respective salaries.
Fourth Step: With the numbers now different, try changing the second sign = in the formula in CI for <>. The result
changes to TRUE.
Fifth Step: To copy the function to all the rows of the Salary field, just position the pointer of the mouse in the lower
right hand corner of the cell and drag until you reach the end of the table-
;Logical Operators
In order to make conditional calculations, you need to pay particular attention to the logical operators. Open a blank
spreadsheet and type in the formulas for the test. In this example, you will be able to check how two of the operators
word = equal) and <> (different).
First Step: Select the cell Al from your table and type the value 10. Then, select cell B and type the value 10 as well.
Second Step: In cell CI, type the following formula =A1=B1. It will test the values, returning TRUE.
Third Step. If you alter the value in one of the cells, the message in C1 automatically changes to FALSE.
Operators
In the table opposite (below/above), you will find all the logical operators used in conditional functions, complete with a
description, examples and the results that are generally obtained. ft*
Operator Description
Equals returns TRUE when the
= two values =A2=A5 TRUE
are equal
Greater than returns TRUE when
> the first value
is greater than the second =A2>A5 TRUE
Less than returns TRUE when
< the first
value is less than the second =A2<A5 TRUE
Greater than or equal to returns
>= TRUE
when the first value is greater
than or
equal to the second =A2>=A5 TRUE
Less than or equal to returns
<= TRUE
when the first value is less than
or equal to the second =A2<=A5 TRUE
Different returns FALSE when
<> the
two compared values are different =A2oA5 FALSE
Percentage Formulas
Discover how to use this simple but useful function, step by step >>
Percentages are frequently used in several Activities in our day to day routines. They very often arise in expressions
which reflect _ increases or reductions in prices, figures or quantities. We frequently hear phrases such as: petrol has
gone up by 10% (which means that for every INR 100 worth of petrol, there has been an increase of INR 10 ; the client
received a 20% discount on all the goods (which means that for each INR 100, a discount of INR 20 dollars was given
on the price); of all the players that play for Brazil. 90° o are crack players (meaning in 100 players that play for the
squad, 90 are exceptional goal scorers).
Two simple examples:
1. A shop launches a promotion of “10% OFF” on all its products. If one item of merchandise originally costs INR
120.00. how much will the discount price be? The discount will be 10% of the value of INR 120.00. Therefore, 120 x
10/100= 1200/100= 12 Therefore, we deduct INR 12.00 from INR 120.00: 120- 12 =108 With the sale promotion price,
we pay just INR 108.00.
2. A class has 100 students, 40% of which are girls. What is the number of girls and boys? The number of girls is:
100 x 40/100 = 40 And the number of boys can be determined as: 100 - 40 = 60.
Complicated? Although the examples are easy, Excel allows even such obvious calculations to be made quickly and
easily. The calculation is the same as if you were using a calculator but the difference is that you add addresses into
the formula. Follow the step-by-step tutorial.
1. Imagine that a client makes a purchase of INR 1,500 and that you wish to give a discount of 5% on the value of
the purchase. Make a table with the fields: Clients, Value, Discount and Price to Pay.
2. After having formatted the spreadsheet, fill it in with the name of the client and the value of the product. In the
column marked Discount, insert the formula for determining percentage.
3. In the cell below Discount, enter the formula =B2*5/100 or even =B2*5%. Press Enter to check the result.
4. To discover the real value of the product to be purchased by the client, enter the subtraction formula = B2-C2.
5. So that you may understand the formula: B2 refers to the address of the purchase value, * is the multiplication
sign, whilst 5 /100 is the value of the discount, divided by 100.
6. In this formula you will be multiplying the address of the purchase value by 5 and dividing it by 100, thus generating
the value of the discount.
INSERTING DATES
Automate the insertion of days, months and years in your spreadsheets. If you work with Excel spreadsheets and
frequently need to insert dates, then follow this tutorial. The Date formula allows you to put a date into a cell, without
the need of typing it in. Furthermore, you can also discover any day of the week that corresponds to a particular date.
Formulas for Dates and Days of the Week.
1 .To insert today’s date in a spreadsheet, all we need to do is position the cursor in the cell in which we wish the date
to appear and type =TODAY ().
2. You can also insert the day of the week corresponding to a date. The day is given by a whole integer which varies
between 1 (Sunday) and 7 (Saturday), by default. 3. Select a cell and click on it with the right hand button of the mouse.
In the tab Number, choose the item Date and, in Type, select the format with the day of the week and the date.
4. In the cell, type the date to discover the day of week it corresponds to. Press Enter.
5. Note that Excel will supply the day of the week of any date you require.
6. You can further discover the day of the week of several dates all at the same time. Select all the cells with the
dates and change their format into day of the week.
To calculate the number of days between two dates, simply subtract them.
For example: B2=08/08/2000 and 83=27/08/2000. The formula B2-B3 will provide us with the resulting number of
days. In this example, the result will be 19. Note that the date in the cell needs to be formatted as a number; otherwise
Excel will provide a date as an answer instead.
Maximum, Minimum, And, Average
Learn how to discover the extreme values and averages in spreadsheets
Excel offers a range of tools to facilitate the daily routine of the user. One of these is the option of obtaining the average
from a list of ranging values. Apart from this, you can also discover Which figures in the lists are the maximum and
minimum values? Follow the next step-by-step tutorial and see how easy it is to use this resource
The Formula for Maximum
Imagine you have a sheet with names and ages of various students in a school and need to know what the maximum
age of any student is. To discover this, all you need to use is the maximum formula.
1. Create a table with the names and ages of students from a school. In column A, enter the names and in column
B. the ages.
2. Now let us type Maximum Age in cell A15. Cell B15 will be where we want to show the result of the maximum
figure.
3. In cell B15, type the formula =MAX (B2:B14). Note that B2 corresponds to the first cell of the figures and B14 is
the last.
Whenever subtracting dates and hours, check that you have created the formula correctly. The dates and hours
must be positive values. If a date or hour formula
produces a negative result, Excel will display in the length of the cell.
Formula for Determining the Minimum
This formula shows the minimum value of a range of cells. To discover the minimum weight of any of the children in
our list, do as follows.
1. Let us use the same spreadsheet that we saw for the maximum formula but we shall add another column to include
the relative weights of the students.
2. Now. we shall enter the data concerning each student’s weight. In cell CI5, write: Minimum Weight.
3. In cell D15. you must enter the formula =ML\(C2:C 14 . Should you use the same values as shown in the image,
then the result will be 25.
Formula for Determining the Average
The formula for determining the average is very useful one to know in order to discover the average value (age, for
example) in a long list or table.
1. Let us now discover the average age of students in the school. To do this, we shall use the same sheet we used in
the previous examples. 2. Now we shall enter the data concerning each student’s weight. In cell CI5, write:
Minimum Weight. In cell D15 you must enter the formula =ML\(C2:C 14 .Should you use the same values as shown in
the image, then the result will be 25.
1. Insert a row in the sheet and write Average in cell A15. In cells B15 and C15, you will obtain the average age and
weight of the students.
2. In cell B15, type =AVERAGE(B2:B14) to discover the average age, whilst in cell C15, type =AVERAGE(C2:C14).
Interaction Between Tables
Create a formula to make calculations using data from separate spreadsheets Imagine you have a plan for
household expenditure and that in each sheet of the file there are the sums of incomes and expenditure of each member
of the family. You can link the result of two or more sheets to facilitate things, for example, to see the running total of
the balance after every payment by each person.
In this step-by-step tutorial, we shall use a plan with the expenses of a couple and we are going to include, in our sheet,
the balance of funds after the payment of each of the bills. Follow the steps given below:
Office Assistant and Functions
If you wish to include functions into your spreadsheet and can’t easily remember them, you can take advantage of
Excel’s Functions Assistant. You can access it by means of the Insert menu, Function.
There, you will find a whole range of formulas and explanations about what each of them does. To access any of them,
click on its name and then click on OK. A screen will appear in which you can determine which cells will make up the
calculation. Excel also shows the formulas most recently used by the user.
1. In the spreadsheet that is to contain the formula, select a cell in which you want to insert the result of another sheet.
2. If you are creating a new formula, enter = (equals sign.
3. To create a link with another sheet in the open workbook, click on the one which contains the cells you wish to
link.
4. After opening the sheet that will receive the result, insert the formula as in the example: =Cristina!C 10+Marcelo!C
14.
5. So as to understand this formula: =Cristina! is the name of the table in which the figure to be added is: C10 is the
cell that contains this value in the sheet;
Marcelo ! is the name of the second sheet and C14 is the cell with the second value to be added.
6. To conclude the formula, press Enter. Note that: if you created a different table from the example, the cells inserted
in the formula
ASSIGNMENTS
Assignment:1
NAME OF THE STUDENT HINDI ENGLISH HISTORY MARATHI GEOGRAPHY
74
RAHUL 58 48 85 71
RAJ 74 85 48 74 65
ROCKY 65 58 54 82 25
RAHIM 86 69 71 65 74
WAHAB 57 68 91 58 47
ANIL 56 67 81 45 55
SACHIN 75 74 58 75 65
STEPS TO BE DONE: Take a new sheet and create the data as shown. And alot do the formula like ( Total, Avg.,
Min, Max, Grade, Result)
Option to be Used: Home panel is to be used
Assignment 2:
STEPS TO BE DONE: Open a new file and do the editing for the data. Cut the marks of the Sachin and paste it into
Wahab data. As shown above.
Option to be used: Home panel clipboard option is to be used
Assignment: 3
STEPS TO BE DONE:
1. Insert a column.
2. Delete cell.
3. Delete row.
4. Change the size of the rows, columns to 25" and 23"
Option to be used: Home panel
Assignment: 4
STEPS TO BE DONE:
1. Open a file and enter the data as given below.
2. Use different Text Alignment for first row.
3. Change the Font and Font Size of the second row. 4. Use Border for outline the text.
Option to be used: Home panel font, paragraph
Assignment: 5
STEPS TO BE DONE:
Open the file and enter the data as given below. Sum the products of all four Products and prepare a chart showing
details of sales of all three products for all four products.
Option to be used: Insert panel Charts option. And sum formula
Assignment: 6
STEPS TO BE DONE:
Open a new file and enter the data as given below. Use the pivot table and pivot chart and analyze the data Option to
be used:
Insert panel > Tables > Pivot Table
Assignment: 7
STEPS TO BE DONE:
Create data sheet as shown below and do the following
1. Using page break option makes the columns B-3 to be printed on page 1 and F5 on page 2
2. Set margins of the page 0.75" left & right and 0.75" top & bottom
3. Print the grid lines
4. Display IMAC SOLUTIONS PVT. LTD. Corporation Ltd in the header and page numbers in the footer
5. Preview the document in print preview
OPTION TO BE USED:
1. Page Break
2. Page Setup
3. Print Preview
Assignment: 8
STEPS TO BE DONE:
1. Select one column and sort by ascending order.
2. Again select other column sort by descending order.
3. Select three columns and sort the first column by ascending order, other two by descending order
OPTION TO BE USED:
Data panel > Sort and Filter
Assignment: 9
STEPS TO BE DONE:
Create a data sheet as shown below and validate Rate field to accept minimum 1 to 2 month dates.
Option to be used: Data panel > Data tools
Solve the question
1. Which of the following is the latest version of Excel ?
Excel 2000
Excel 2002
Excel ME Excel XP
2. Excel files have a default extension of ?
XLS XLW
WK1 123
3. A typical worksheet has number of columns ?
128
256
512
1024
4. All formula in Excel start with ?
%
+
=
-
5. The divide symbol is ?
. /
D
D
)
6. The multiplication arithmetic operator is represented by which of the following symbols?
^
*
/X
7. On an excel sheet the active cell in indicated by …? A dark wide boarder
A dotted border
A blinking border None of above
8. Using the F11 shortcut key to create a chart on chart sheet creates? A default chart
A 2-dimensional column chart
4. Click the Run button, , press [F5], or go to Sub/UserForm to run the program.
5. The message box pops up with the "Hello World!" greeting.
2. To place a command button on the spreadsheet and start programming by clicking the command button.
In order to place a command button on the spreadsheet, you need to click View on the MS Excel menu bar and then
click on toolbar and finally select the Control Toolbox after which the control toolbox bar will appear. Then you click on
the command buttton and draw it on the spreadsheet.
Next, you click on the command button and the Visual Basic Editor will appear. Then you enter the statement as shown
in the figure. The first statement will fill up cell A1 to cell A10 with the phrase "Visual Basic" while the second statement
add the value in cell A11 and cell B11 and then show the sum in cell C11. It is that simple.
The output:
Working with Variables in Excel VBA
The Concept of Variables
Variables are like mail boxes in the post office. The contents of the variables changes every now and then, just like the
mail boxes. In VBA, variables are areas allocated by the computer memory to hold data. Like the mail boxes, each
variable must be given a name. To name a variable in VBA, you have to follow a set of rules, as follows:
a) Variable Names
The following are the rules when naming the variables in VBA
It must be less than 255 characters
No spacing is allowed
It must not begin with a number Period is not permitted
Examples of valid and invalid variable names are displayed in Table.
Valid Name Invalid Name
My_Car
b) Declaring Variables
In VBA, one needs to declare the
1NewBoy variables before using them by
assigning names and data types.
ThisYear There are many VBA data types,
Long_Name_Can_beUSE He&HisFather *& is not acceptable which can be grossly divided into two
types, namely the numeric data
Group88 Student ID * Spacing not allowed types and non-numeric data types
i) Numeric Data Types
Numeric data types are types of data that consist of numbers, which can be computed mathematically with various
standard operators such as add, minus, multiply, divide and so on. In VBA, the numeric data are divided into 7 types,
which are summarized in Table.
Type Storage Range of Values
Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to 3.402823E+38
Single 4 bytes for positive values.
-1.79769313486232e+308 to -4.94065645841247E-324 for negative values
Double 8 bytes 4.94065645841247E-324 to 1.79769313486232e+308 for positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use +/-
Decimal 12 bytes 7.9228162514264337593543950335 (28 decimal places).
Numeric Data Types
ii) Non-numeric Data Types The nonnumeric data types are summarized in Table.
Data Type Storage Range
String(fixed length) Length of string 1 to 65,400 characters
String(variable length) Length + 10 bytes 0 to 2 billion characters
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Variant(text) Length+22 bytes Same as variable-length string
Table: Nonnumeric Data Types
You can declare the variables implicitly or explicitly. For example, means that the variable sum is declared implicitly
and ready to receive the input in Text1 textbox. Other examples of implicit declaration are volume=8 and
label=¡±Welcome¡±. On the other hand, for explicit declaration, variables are normally declared in the general section
of the codes' windows using the Dim statement. The format is as follows:
Dim variableName as DataType
Example 2.1
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim BirthDay As Date
You may also combine them in one line, separating each variable with a comma, as follows: Dim password As String,
your Name As String, Fortnum As Integer.
If the data type is not specified, VB will automatically declare the variable as a Variant. For string declaration, there are
two possible formats, one for the variable-length string and another for the fixed-length string. For the variable-length
string, just use the same format as Example 2.1 above. However, for the fixed-length string, you have to use the format
as shown below: Dim VariableName as String * n
where n defines the number of characters the string can hold. For example, Dim
yourName as String * 10 mean yourName can hold no more than 10 Characters.
Example
In this example, we declared three types of
variables, namely the string, date and currency.
Private Sub CommandButton1_Click()
Dim YourName As String Dim BirthDay As
Date
Dim Income As Currency
YourName = "Alex"
BirthDay = "1 April 1980"
Income = 1000
Range("A1") = YourName
Range("A2") = BirthDay
Range("A3") = Income
The output screen of Example
End Sub
Message Boxes (MsgBox) in VBA for Excel
In VBA for Excel the message box (MsgBox) is the primary tool to interact with the user. You can use it to inform, alert
or ask the user (with a Yes/No message box) if he is sure that he wants a certain critical procedure to run (deleting
things). The code in VBA for Excel to generate the following basic message box is: MsgBox "Thank you"
If you want you want part of your message to be between quotes you need to double the quotes as in:
End If
End Sub
The code for message box with Yes No Cancel button:
Private Sub CommandButton1_Click()
Dim message As Integer
message = MsgBox("Click Yes to Proceed, No to stop", vbYesNoCancel, "Login")
If message = 6 Then
Range("A1").Value = "You may proceed"
ActiveWorkbook.Activate
ElseIf message = 7 Then
ActiveWorkbook.Close
End If End Sub
* The number inside the array, i.e. Arr(1), is the index. One (1) is the index of the first element in the array.
Resize an Array with Redim Statement
The ReDim statement is used to size or resize a dynamic array that has already been formally declared.
For example, if you have already declared an array with an element value of 5 and decided to change the number of
the element to 6, you can do the following to resize the array:
Redim Arr(6)
We incorporate it into our last example:
Option Base 1
Sub assignArray( ) 'Dim Arr(5)
Redim Arr(6)
Arr(1) = “Jan” Arr(2) = “Feb” Arr(3) = “Mar”
Arr(4) = “Apr”
Arr(5) = “May” Arr(6) = “Jun”
Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5)
End Sub
Note that the Dim Arr(5) statement is commoned out, because leaving this original statement in the sub will causing a
compile error.
Manage Dynamic Array
A word of caution in using the Redim Statement to resize an array - resize the array can erase the elements in it. In
the following example, all the values assigned prior to resize the array are erased. Only the value assigned to the array
after resize remains.
Option Base 1
Sub assignArray( ) Redim Arr(5)
Arr(1) = “Jan”
Arr(2) = “Feb”
Arr(3) = “Mar”
Arr(4) = “Apr”
Arr(5) = “May”
Redim Arr(6)
Arr(6) = “Jun”
Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" &Arr(4) & "-" & Arr(5) & "-" & Arr(6) End Sub
By replace the Redim Arr(6) with Redim Preserve Arr(6), all values will remain. For example:
Option Base 1
Sub assignArray( )
Redim Arr(5)
Arr(1) = “Jan” Arr(2) = “Feb” Arr(3) = “Mar”
Arr(4) = “Apr” Arr(5) = “May”
Redim Preserve Arr(6)
Arr(6) = “Jun”
Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5) & "-"
& Arr(6) End Sub
Create Multi-Dimensional Array
An array can also store multiple dimensional data. To simplify our tutorial, example on a two-dimensional array is
used. Assume you have data of a local store's yearly sale in the following table and you want to store the data in a
two-dimensional array:
Year 2003 Year 2004
CD Sale 1,000 1,500
DVD Sale 1,200 2,000
First we create the array as follow:
Dim Arr(2,2)
Then we assign the values into the array. We treat the first dimension as the year and the second dimension as the
product sale:
Arr(1,1) = 1000
Arr(1,2) = 1200
Arr(2,1) = 1500
Arr(2,2) = 2000
We now display the values of the array with a message box:
Msgbox "Sale of CD in 2003 is " & Arr(1,1) & vbCrLf & "Sale of CD in 2004 is " _ &
Arr(2,1) & vbCrLf & "Sale of DVD in 2003 is " & Arr(1,2) & vbCrLf _& "Sale of DVD in 2004 is " & Arr(2,2)
The complete precedure is as followed:
Option Base 1
Sub multDimArray( ) Dim Arr(2,2)
Arr(1,1) = 1000
Arr(1,2) = 1200
Arr(2,1) = 1500
Arr(2,2) = 2000
Msgbox "Sale of CD in 2003 is " & Arr(1,1) & vbCrLf & "Sale of CD in 2004 is " _
& Arr(2,1) & vbCrLf & "Sale of DVD in 2003 is " & Arr(1,2) & vbCrLf _& "Sale of DVD in 2004 is " & Arr(2,2)
End Sub
* vbCrLf stands for VB Carriage Return Line Feed. It puts a return and a new line as shown in the message box
above. The underscore "_" on the back of the first line of the message
box means
"continue to the next line"
Using If ..Then .Else
Visual Basic Editor in MS Excel is just as powerful as the stand alone Visual Basic compiler in the sense that you can
use the same commands in programming. For example, you can use Else to control program flow and display certain
output based on certain conditions in MS Excel. Here, I am going to demonstrate the concept using one example. IF
Then Statement
The IF Then is a single condition and run a single statement or a block of statement.
Example, the following statement set variable Status to "Adult" if the statement is true: If Age >= 18 Then Status =
"Adult"
You can also use multiple-line block in the If statement as followed:
If Age >= 18 Then
Status = "Adult"
Vote = "Yes"
End If
Note that in the multiple-line block case, End If statement is needed, where the single- line case does not. IF Then Else
The If Then Else statement is used to define two blocks of conditions - true and false.
Example:
If Age >=22 Then
Drink = "Yes"
Else
Drink = "No"
End If
Again, note that End If statement is needed in this case as well since there is more than one block of statements.
Nested IF
It is possible to nest multiple IF functions within one Excel formula. You can nest up to 7 IF functions to create a complex
IF THEN ELSE statement.
The IF Then ElseIf is used to test additional conditions without using new If Then statements.
For Example:
If Age >= 18 and Age < 22 Then Msgbox "You can vote"
ElseIf Age >=22 and Age < 62 Then
Msgbox "You can drink and vote"
ElseIf Age >=62 Then
ModulesandProcedures
A procedure is defined as a named group of statements that are run as a unit. A statement is simply 1 complete line of
code. VBA procedures are used to perform tasks such as controlling Excel’s environment, communicating with
databases, calculating equations, analyzing data…etc .
VBA has two types of procedures:
Sub procedures and
Function procedures.
Sub Procedures
Sub procedures are written when you want to command Excel like creating a chart, analyzing data, coloring cells,
copying and pasting data etc.
Function Procedures
Function procedures are created when you want to make your own custom worksheet functions or perform a calculation
that will be used over and over again. Note that Sub procedures can also do calculations.
Modules and Procedures and Their Scope
A module is a container for procedures as shown in our prior examples. A procedure is a unit of code enclosed either
between the Sub and End Sub statement or between the Function and End Function statements.
The following sub procedure (or sub routine) print the current date and time on cell C1: Sub ShowTime()
Range("C1") = Now()
End Sub
The following function sum up two numbers:
Function sumNo(x, y) sumNo = x + y End Function
A Procedure:
A Function:
In the module environment, key in the function code for the function Area_Rect , as shown in the diagram below.
Now, you can return to the Excel spreadsheet and enter the function in any cell. In this Example, the function is entered
in cell C1 and the values of width and height are entered in cell A1 and cell B1 respectively. Notice that the value of
area is automatically calculated and displayed in cell C1.
The formula can be copied and updated to other cells by using the Autofill method, i.e. by dragging the place holder on
the bottom right corner of the cell, as shown in Figure below.
Few Examples:
Methods normally do something or perform certain operations. For example,
ClearContents is a method of the range object. It clears the contents of a cell or a range of cells. You can write the
following code to clear the contents:
Private Sub CommandButton1_Click()
Range(A1:A6).ClearContents
End Sub
You can also let the user select his own range of cells and clear the contents by using the
InputBox function, as shown in Example
Private Sub CommandButton1_Click() Dim, selectedRng As String
selectedRng = InputBox("Enter your range")
Range(selectedRng).ClearContents
End Sub
In order to clear the contents of the entire worksheet, you can use the following code:
Sheet1.Cells.ClearContents
But if you only want to clear the formats of an entire worksheet, you can use the following syntax:
Sheet1.Cells.ClearFormats
To select a range of cells, you can use the Select method. This method selects a range of cells specified by the Range
object. The syntax is
Private Sub CommandButton1_Click()
Range("A1:A5").Select
End Sub
This example allows the user to specifies the range of cells to be seleted.
Private Sub CommandButton1_Click() Dim selectedRng As String
selectedRng = InputBox("Enter your range")
Range(selectedRng).Select
End Sub
To deselect the selected range, we can use the Clear method.
Range(CiRj:CmRn).Clear
In this example, we insert two command buttons, the first one is to select the range and the second one is to deselect
the selected range.
Private Sub CommandButton1_Click()
Range("A1:A5").Select
End Sub
Private Sub CommandButton2_Click()
Range("A1:A5").Clear
End Sub
Instead of using the Clear method, you can also use the ClearContents method. Another very useful method is the
Autofill method. This method performs an Autofill on the cells in the specified range with a series of items including
numbers, days of week, months of year and more. The format is Expression.AutoFill(Destination, Type)
Where Expression can be an object or a variable that returns and object. Destination means the required Range object
of the cells to be filled. The destination must include the source range. Type means type of series, such as days of
week, month of year and more. The AutoFill type constant is something like XlFillWeekdays, XlFillDays, XlFillMonths
and more.
Example
Private Sub CommandButton1_Click()
Range(A1)=1
Range(A2)=2
Range("A1:A2").AutoFill Destination:=Range("A1:A10") End Sub
In this example, the source range is A1 to A2. When the user clicks on the command button, the program will first fill
cell A1 with 1 and cell A2 will 2, and then automatically fills the Range A1 to A10 with a series of numbers from 1 to 10.
Example
Private Sub CommandButton1_Click()
Cells(1, 1).Value = "monday"
Cells(2, 1).Value = "Tuesday"
Range("A1:A2").AutoFill Destination:=Range("A1:A10"), Type:=XlFillDays
End Sub
This example allows the user to select the range of cells to be automatically filled using the Autofill method. This can
be achieved with the use of the InputBox. Since each time we want to autofill a new range, we need to clear the contents
of the entire worksheet using the Sheet1.Cells.ClearContents statement.
Private Sub CommandButton1_Click()
Dim selectedRng As String Sheet1.Cells.ClearContents
selectedRng = InputBox("Enter your range")
Range("A1") = 1
Range("A2") = 2
Range("A1:A2").AutoFill Destination:=Range(selectedRng)
Calling Sub Procedures and Function Procedures
There are two ways to call a sub procedure. The following example shows how a sub procedure can be called by other
sub procedures.
Sub z(a)
MsgBox a End Sub
Sub x()
Call z("ABC") End Sub
Sub y() z "ABC" End Sub
Sub z procedure takes an argument (a) and display the argument value ("ABC") in a message box. Running either
Sub x or Sub y will yield the same result.
The following example calls a function procedure from a sub procedure.
The ShowSum sub procedure calls the sumNo function and returns an "8" in a message box.
Sub ShowSum() msgbox sumNo(3,5)
End Sub
Function sumNo(x, y) sumNo = x + y End Function
If there are procedures with duplicate names in different modules, you must need to include a module qualifier before
the procedure name when calling the procedure.
Workbooks
Each object contains its own methods and properties.
A Property represents a built-in or user-defined characteristic of the object. A method is an action that you perform
with an object. Below are examples of a method and a property for the Workbook Object:
Workbooks. Close
Close method close the active workbook
Workbooks. Count
Count Property returns the number of workbooks that are currently opened
A lot of VBA beginners start their career using Cells. For example:
Cells(1,1).Select is the same thing as Range("A1").Select and Cells(11,31).Select is the same as
Range("AE11").Select.
I strongly recommend that you use Range instead of Cells to work with cells and groups of cells. It makes your
sentences much clearer and you are not forced to remember that column AE is column 31.
The only time that you will use Cells is when you want to select all the cells of a worksheet like in:
Cells.Select To select all cells and then to empty all cells of values or formulas you will use:
Cells.ClearContents worksheets
You access a worksheet named "Balance" with:
Sheets("Balance").Select
Note that the word " Sheets" is plural and never forget the quotes within the parenthesis
You cannot select a sheet that is hidden so you will need to write:
Sheets("Balance").Visible= True Sheets("Balance").Select and then if you want to hide the sheet again:
Sheets("Balance").Visible= False
The name of a sheet must not have more than 31 characters and cannot include certain special characters like ? : \ /
[ ] . If you don't respect these rules your procedure will crash. The following lines of code will generate an error
message:
Sheets("Sheet1").Name= "Balance and Introduction to Numbers" because there are more than 31 characters including
the spaces
Sheets("Sheet1").Name= "Balance: Introduction" because of the special character :
Sheets("Sheet1" ).Name= "" because the name cannot be blank
You cannot go directly from a sheet to a cell on another sheet. For example if the active sheet is "Balance" and you
want tot go to cell A1 of a sheet named "Results" you cannot write:
Sheets("Results").Range("A1").Select You must take two steps:
Sheets("Results").Select Range("A1").Select
We have already seen basics for the range object. Let’s learn few more properties.
To select a single cell you will write: Range("A1").Select
To select a set of contiguous cells you will use the colon and write:
Range("A1:G5").Select
To select a set of non contiguous cells you will use the comma and write:
Range("A1,A5,B4").Select
To select a set of non contiguous cells and a range you will use both the colon and the comma:
Range("A1,A5,B4:B8").Select
Some objects have default properties. For example, Range's default property is Value.
The following yields the same outcome. Range("A1") = 1 and Range("A1").Value = 1
Here are examples on how to set and to get a Range property value:
The following sets the value of range A1 or Cells(1,1) as "2005". It actually prints "2005" on A1.
Range("A1").Value = 2005
The following gets the value from range A1 or Cells(1,1).
X = Range("A1").Value
Method can be used with or without argument(s). The following two examples demostrate this behavior.
Methods That Take No Arguments: Worksheets("Sheet").Column("A:B").AutoFit
Methods That Take Arguments:
Worksheets("Sheet1").Range("A1:A10").Sort _
Worksheets("Sheet1").Range("A1")
Worksheets("Sheet1").Range("A1") is the Key (or column) to sort by.
Sometime a method takes more than one argument. For example, the Open method for the Workbook object, takes
12 arguments. To open a workbook with password protection, you would need to write the following code:
"", , , ,"pswd"
Since this method takes so many arguments, it is easy to misplace the password argument. To overcome this potential
problem, one can use named arguments like the following example:
fileName:="", password:="pswd"
You can also assign an object to an object variable using the Set Statement.
For example:
Dim myRange as Range
Set myRange = Range("A1:A10")
Project Assignments
The Code
Opening and Closing the Userform
The first thing to do is to create code to call your userform. Here is a basic line of code doing so:
The line of code to close the userform is: or "Me" being the general name of the active form
The "Hide" sentence is usually part of the code of a command button on the form. A user clicks on a "GO" , "SEND,
"SUBMIT" or "CANCEL" button and part of what must happen is that the userform disappears from the screen.
Labels
In the toolbox the label has this icon . The label is a passive control meaning that the user never really acts on it. It is
there to inform the user and to label other controls like text boxes, combo boxes or list boxes.
Properties
The other interesting properties of the label are:
- TabStop: To make the control invisible for the "Tab" and "Enter" keys (see Tab Order) set this property to "False" .
- WordWrap: If you want to write more than one line of text in a label set this property to "True" .
Code
There is not much coding developed for the labels although there are 8 events related to the label. For example there
is an event named "MouseMove" . If you develop code within this event it is executed when the mouse moves over the
label. If the code is the following:
MsgBox "Don't forget to " a message box will appear when the user moves the mouse over the label. You can stack
many labels one over the other and make their "Visible" property to "False" . You can then make any of the labels
visible from an event related to another control. For example if a user chooses a certain value in a combo box a certain
label appears.
Text Boxes In the toolbox the text box has this icon .
The text box is the simplest control to require an entry from the user. The user types something in it and this value can
then be used in your VBA procedure. You will usually add a label to accompany the text box.
For most controls including the VBA for Excel text box there are general properties that allow you to set the font, the
color of the font, the color of the background, the type of background, the type of border and other design features.
Using the 3 windows in the Visual Basic Editor you will see the following properties in the "Property" window when the
text box is selected.
Properties
The other interesting properties of the text boxes are:
- WordWrap to be able to write more that one line on a button,
- ControlTipText which generates a small comment box when the user moves the mouse over the control. You can
use this property to give explanations and instructions about the command button,
- Enabled and Visible are properties that you can change programmatically to disable or render invisible a command
button following a previous selection in another control of the userform,
- TabIndex is a property that you change through the " Tab Order" functionality as shown in the UserForms section.
- MaxLength to limit the number of characters entered by the user,
- Value or Text which is the text show in the text box when the userform is activated ("Enter your Name" for example)
To ask users to submit a password to run certain macros develop a userform with a text box and a command button.
In the text box you can modify the "PasswordChar" property so that when the user enters the password nobody around
can read it. Use an asterisk, an ampersand or any other character in it.
Code
The most important thing to remember is that a text box is what its name says it carries text. So if you want to send a
numerical value from a text box to a cell you must use the "Value" thing:
Range(" A1" ).Value=tbxInput.Value
Command Buttons
In the toolbox the command button has this icon . The command button is a very active control and there is always
VBA code behind it.
The command buttons are usually placed at the bottom of the form and serve to complete the transaction for which the
form has been created. The caption of these buttons are usually "Go" , "Run" , "Submit" , "Cancel" , etc.
Properties
The other interesting properties of the command button are:
- WordWrap to be able to write more that one line on a button,
- ControlTipText which generates a small comment box when the user moves the mouse over the control. You can
use this property to give explanations and instructions about the command button,
For advanced users there are the:
- Enabled and Visible properties that you can change programmatically to disable or render invisible a command
button following a previous selection in another control of the userform.
Code
Name your command button before developing your code. VBA uses the name of the command button when it creates
lines of code related to events. So if you don't name your command button VBA will create the private sub:: Private
Sub CommandButton1_Click() as if you name the command Button " cmbSubmit" for example the private sub will start
with:
Private Sub cmbSubmit_Click()
If you name your command buttons after private subs have been created they won't work anymore.
A very simple VBA procedure for the command button would look like this:
Private Sub cmbSubmit_Click()
Sheets("Code").Range("F1").Value = cbxInput.Value
End Sub
The content of the combo box "cbxInput" is entered in cell "F1" of the sheet "Code" and the form (frmPassport) is
closed.
List Boxes
Before we begin on the List Box
The difference betweena combo boxand a list box is that the combo box is a drop- down list and the user can submit a
single value from the drop-down list. The list box shows a certain number of values with or without a scroll bar and the
user can select one or more values.
Combo Box List Box
If you are looking for a drop-down list (also called pull-down lists) to use on a regular worksheet see the much easier
and user friendlyExcel drpdwnlistsin the website on Excel.
When you double click on the combo box in theVisualBasic Editoryou will see all its properties in theProperties window.
No programming is needed to submit the list of values that will be offered to the user within the combo box. Look for
the RowSource property. The RowSource Property:
The values that should appear in the drop-down list of the combo box are submitted in the RowSource property. For
example if the value of the RowSource property is Balance!A1:A12 The values residing in cell A1 to A12 of the sheet
named Balance will be offered as choices to the user who clicks on the small arrow of the combo box. The rules to
submit the RowSource property is the name of the sheet where the list resides followed by an exclamation point (!),
the address of the first cell, a colon and the address of the last cell.
IMPORTANT NOTE: if there is a space or a special character within the name of the sheet where the list resides you
must surround it with simple quotes like in 'New Balance'!A1:A12.
Option Buttons, Check Boxes and Frames
In the toolbox the option button has this icon , the check box has this one and, the frame this one .
You don't need to add a label to accompany the check box or the option button because they come with their own.
The check boxes and the option buttons are both used to offer the user a choice. The main difference between check
boxes and option buttons is that if you have 5 of each on a form a user can check all 5 check boxes but can only select
one of the option buttons.
If you want to create two sets of option buttons read below on frames and option buttons. If you don't want to use
frames to create groups of option buttons you will need to use the "GroupName" property of the option buttons. All
option buttons with the same GroupName work together.
Properties
- WordWrap to be able to write more that one line in the caption,
- ControlTipText which generates a small comment box when the user moves the mouse over the control. You can
use this property to give explanations and instructions about the option button or the check box.
- Enabled and visible are properties that you can change programmatically to disable or render invisible an option
button or a check box following a previous selection in another control of the userform.
Frames
Frames are also a passive control. Frames are used to improve the layout of the userform. You can use them around
a group of controls that have something in common.
Frames become more important to manage option buttons. If you have two sets of option buttons on a userform and
you don't place them within a frame they all work together and you can choose only one. If you put each set within a
frame you can choose one in each set.
When you move a frame its entire controls move with it.
Advance form controls
Spin Button
In the toolbox the spin button has this icon .
You can ask a user to enter a value directly in a text box but you can make things a little fancier by using a text box
and a spin button.
The spin button is not really used by itself. Because the spin button doesn't show its value it is usually used with a text
box. The text box shows a number and by clicking on the arrows of the spin button the value in the text box is increased
(or decreased) by 1, or 5 or 10 by whatever value that is set within the properties of the spin button.
Properties
The other interesting properties of the spin buttons are:
- Min is the minimum value of the spin button. It can be negative
- Max is the minimum value of the spin button. It can be negative
- Small is the value of the change when the user clicks on the arrows
- Large is the value of the change when the user clicks on the scroll bar of the spin button
Image Control
There is a control in the toolbox called "Image" . Within this control you can show all kinds of pictures. You set an image
control on a userform and you submit a picture in the property "Picture" . The picture becomes part of the control and
userform.
Fitting the Picture
The first thing that you want to do is to fit the picture in the image control to make the size of the control adapt to the
size of the picture.
When you are in the Visual Basic Editor and you single click on an image control a frame appears around it with 8
stretchers (picture below). If you double click on the middle stretcher (when a two tips arrow shows) of the right side or
on the middle one at the bottom or on the bottom right corner stretcher the image control will adapt to the size of the
image. Double clicking anywhere else will take you to the VBA code and will not adapt the control size to the picture
size.
PictureSizeMode Property
Another interesting property of the image control is the PictureSizeMode.
If the property is set to the default value 0-frmPictureSizeModeClip the control size can be changed without the picture
size being modified. So you can see only part of the picture or there can be a background behind it which color you can
change at will. If the property is set to the 1-frmPictureSizeModeStretch the picture is resized as the control is. The
image fills the control.
If the property is set to the 3-frmPictureSizeModeZoom the picture is resized as the control is but the picture and
background are present.
Event handling
When does the VBA procedure (macro) start? When an EVENT happens. The event is what triggers the VBA Excel
procedure. Clicking on a text box on the worksheet
95% of the VBA procedures that you develop are triggered by a click on a button located on a worksheet.
I prefer using text boxes rather than VBA command buttons because they are much easier to maintain and allow much
more creativity in the design. You can use the font that you like and the background color that fits your needs. If you
are a little creative you can add 3D effects, special borders and the likes.
A few note on Excel text boxes:
I always keep the Excel drawing toolbar visible at the bottom of my screen
You create text boxes by a left click on the icon , let the button go, then go to the worksheet left click, hold and stretch
the text box. When the border of the active text box is made of diagonal lines you can work the text inside the text box.
If you click again on the border it becomes a set of dots and you then can work the text box itself. Right click on the
border in any of the two states and you will see that the menus are different.
First you develop a macro in a module in the VBE. Then you click ob the text box and when the border becomes a set
of dots right click on it and select "Assign a macro" . Select a macro from the list that is offered to you. A simple macro
to call a userform would look like this:
Sub proUserFormWeighing() End Sub
You can assign a VBA macro to a text box and also to a WordArt, a picture or any other shape from the " Drawing"
toolbar.
Once a button (image, word art or text box) has been assigned a macro or an hyperlink you need to select it with a right
click to modify it.
Download one of these buttons (right click on it in your browser and choose "Save image as" ). Save it on your desktop:
Insert the image that you have imported on the first sheet " Insert/Picture/From File/Desktop/ .gif" . Once the image has
been added to the sheet, right click on the image, select "Assign Macro" and select a macro from the list. Click "OK" .
Now click on the image.
You can "borrow" all kinds of buttons from the Internet or create your own from the "Design" toolbar and use them as
triggers for your VBA procedures.
VBA Controls