Advance Excel PDF
Advance Excel PDF
Advance Excel
INDEX
Module-I
Extend Your Insight Office Excel 201002
Formulas.42
Module-II
Building macros in Excel..61
Programming Structure in Excel VBA.76
Excel VBA Controls' Properties and VBA Code..110
Advance Excel
Advance Excel
The Insert tab houses the commands for the objects you add to your worksheets; for
example, tables, charts, illustrations, links, and various kinds of text items, such as
column or row labels.
The Page Layout tab offers all things related to setting up the worksheet, including
choosing themes, selecting page setup options, controlling the scaling of individual
objects, selecting worksheet options, and arranging items on the sheet.
The Formulas tab includes the Function Wizard, the Function Library, the commands you
need for creating and working with named cells, commands for formula auditing, and
calculation options.
The Data tab offers commands for getting external data; managing the connections to
external links; sorting and filtering your data; removing duplicates, validating and
consolidating your data, and grouping and ungrouping cells.
The Review tab includes what you need to proof, comment on and share and protect
the sheet.
The View tab provides commands for choosing different workbook \views. Hiding and
redisplaying worksheet elements (gridlines. the ruler, the formula bar and more),
magnifying or reducing the display, and working with the worksheet window.
Tip: To find out more about the new elements in the Microsoft Office system user
interface including the new command sets, contextual tools live preview, galleries,
and morerefer to Chapter 2 A New Look.
Advance Excel
Tip: Make changes that relate to the appearance of the overall documentfor
example, adjusting margins, changing orientation, or filtering datawhile youre
working in Page Layout view. This enables you to get the best big picture sense of how
the changes will affect your worksheet when printed.
Page Layout view is also available in the view controls in the lower-right corner of the
Office Excel 2010 window. The three views displayed in the control (to the left of the
Zoom control) are Normal new. Page layout view and Page Break preview.
Tip: The Custom Views feature in Office Excel 2010 is now available in the Page Layout
tab of the user interface. Set the display features the way you want them click Custom
Views, and then click Add to create a view you can apply to other worksheets as well.
Advance Excel
And even on huge, formula-intensive worksheets you will experience faster calculations
because Office Excel 2010 now supports dual processors and multithreaded chipsets,
which enable Office Excel 2010 to take full advantage of your systems processing power
and dramatically reduce your wait time. Another speed booster: The memory
management in Office Excel 2010 has been increased from 1 GB to 2 GB. giving you
more room to work with complex, sophisticated spreadsheets that previously mixed out
your system resources. Additionally Office Excel 2010 moves the bar on some of the
limits in the earlier version; for example, now you can set unlimited formatting in the
same workbook (this used to be capped at 4.000 format types). The color palette of
Office Excel 2010 has grown to support the full 16 million colors, and now you can
create as many cell references to a single cell as your computers memory will allow
(this used to be limited to 8.000 references per cell).
Advance Excel
1. Use Page Layout view to see how your worksheet will be distributed between pages,
to switch quickly between portrait and landscape modes, and to enter headers and
footers directly on the worksheet.
2. Use Table Styles in conjunction with Themes to give your workbooks a consistent,
professional appearance.
3. Use the new conditional formatting features to highlight dates that meet dynamic
conditions, such as yesterday, today, last week, next week, or next month.
Tip: As you can see choosing a different theme changes a collection of format elements.
Several characteristics are included in each theme: the colors used the fonts, and the
effects. The three tools to the right of the Themes command enable you to set each one
of these items separately, if you prefer Setting the format of a cell used to be something
that required up-front thought and effort; now you can apply predesigned formats to
cells and ranges by simply clicking the Cell Styles command and choosing the format
from the gallery that appears. Youll find the Cell Styles command in the Home tab; just
click the command to view and select an available format.
Tip: You can create formats for your own cell styles and add them to the gallery. Start
by applying the format you want to a specific cell then click Ceil Styles in the Sheet
command tab and choose New Cell Style in the Cell Styles gallery. Review the
information in the Style dialog box and click Format if you need to make any changes
type a name for the style in the Style Name field and then click OK to save the style. The
new style you created appears at the top of the gallery in the Custom category.
Advance Excel
type your header and use the elements shown to add items you need; for example, the
page number, date, time, and worksheet name.
Tip: The Auto Header and Auto Footer commands on the left side of the header and
footer tools give you a collection of ready-made headers and footers you can apply to
your worksheet. Simply click the command and dick the selection to add it automatically
to your worksheet.
Advance Excel
The format lab provides you the means to select different chart elements, add styles to
the chart shape, including 3-D edges, shadows, bevel and more.
Tip: Office Excel 2010 includes the Smart Art option for those limes when you want to
add a sophisticated diagram to your worksheet. To create Smart Art graphics, choose
the Insert tab. click Smart Art In the Illustrations command tab. select the diagram type
you want to create choose the style you prefer, and click OK.
Advance Excel
Color scales apply coloring schemes you select to a specific range of values so that
individual cells display in a particular color based on their value.
Icon sets provide you with a set of individual characters you can apply within the cell to
show trends in a variety of ways.
Services
Excel Services is a new feature in Office Excel 2010 that enables you to save your
workbook to a server that is running Microsoft Office SharePoint Server 2010 (and also
supports Office Excel Web Access).
Here are some of the biggest benefits of using Office Excel 2010 with Excel Services:
Share and manage collaborative worksheets more securely. Display only those
worksheet areas users have permissions to see; hide confidential data, formulas, and
macros
Create, sort, filter, and modify PivotTable views using any Web browser.
To set permissions for the worksheet to enable the worksheets or ranges you
want to make available to the users you specify, open the File menu, point to Save As.
and click Excel Services.
The Save As dialog box provides an Excel Services Options button that enables you to
control which sheets are visible in the users browser. After you make your selections
and click OK. Enter the name of the shared folder in the Save In field and click Save. The
file is stored on Office SharePoint Server 2010 and your team members will be able to
access the worksheets via the Web.
Quick Facts about Office SharePoint Server 2010 and Office Excel
2010
9
Advance Excel
You can save sensitive or critical spreadsheets to Office SharePoint Server 2010 and
indicate permissions for which elements (specific worksheets, tables, charts, ranges, and
so on) will be available to other team members.
Office SharePoint Server 2010 includes the Report Center to help users create and work
with trusted Data Connections so they can safely connect with external data sources.
Use Office SharePoint Server 2010 too centrally store important spreadsheets to control
the distribution of multiple versions and ensure that business members and partners
are working with the most recent files.
10
Advance Excel
A cell reference identifies a single cell or a range of cells on a worksheet and tells
Excel where to look for the values or data you want to use in a formula.
With references, you can use data contained in different parts of a worksheet in a single
formula or use the value from one cell in several formulas. You can also refer to cells on
other sheets in the same workbook, to other workbooks, and to data in other programs.
References to cells in other workbooks are called external references. References to
data in other programs are called remote references. Excel has two cell reference styles:
The A1 style and the R1C1 reference style. By default, Excel uses the A1 reference style.
This style refers to columns with letters (A through IV, for a total of 256 columns) and to
rows with numbers (1 through 65,536).
These letters and numbers are called row and column headings. To refer to a cell, enter
the column letter followed by the row number. For example, D50 refers to the cell at
the intersection of column D and row 50. To refer to a range of cells, enter the reference
for the cell in the upper-left corner of the range, a colon ( , and then the reference to
the cell in the lower-right corner of the range.
Examples of A1-style references:
To refer to Use
The range of cells in Column A and row s 10-20 A10:A20
The range of cells in Columns A-E and rows 1-20 A1:E20
All the cells in row 5 5:5
All the cells in rows 5 through 10 5:10
All the cells in Column A A: A
All the cells in Columns B through H B: H 2
To experiment with any reference types that may be unfamiliar to you, click the
F5 key to open Excels Go To dialog box and enter a reference in the Reference box
to see the cell/range selection in your spreadsheet. With the R1C1 reference style, both
the rows and the column s on a worksheet are numbered. The R1C1 style is particularly
useful for computing row and column positions in macros. In the R1C1 style, Excel
indicates the location of a cell with an R followed by a row number and a C followed
by a column number. Toggle on or off the R1C1 reference style by choosing Tools,
Options and selecting the General tab. 3 Excels formula operators specify the type of
calculation to perform on the elements of a formula. Excel has four different types of
calculation operators: arithmetic, comparison, text, and reference.
11
Advance Excel
dates and times as values they can be added, subtracted, and included in other
calculations. For example, to determine the difference between two dates, subtract one
date from the other. View a date as a serial value and a time as a decimal fraction by
changing the format of the cell that contains the date or time to General (number)
format. For example:
Date Number
4/10/01 36991
3:15 0.1354
For a date calculation, either refer in the formula to cells that contain dates, or -- to
include actual dates in the formula surround them with double quotes. For example,
this formula:
=4/10/01 3/10/01 yields the value 31.
Excel supports two date systems: the 1900 and 1904 date systems. The default date
system for Excel is 1900. If you have a need to the 1904 date system, choose Tools,
Options, select the Calculation tab and toggle on the 1904 date system check box. The
table below shows the first date and the last date for each date system and the serial
value of each.
1900 January 1, 1900 (serial value 1)
December 31, 9999(serial value 2958465)
1904 January 2, 1904(serial value 1)
December 31, 9999(serial value 2957003)
Use the DATE function to manipulate a part of a date within a formula. Use the TIME
function to manipulate a part of a time such as the hour or minute within a formula.
See the Date & Time category of Excels built-in functions for more options.
By default, dates entered in a workbook are formatted to display two-digit years.
Use the Windows Control Panel to change the default date format if you want to display
four-digit years instead of two-digit years.
12
Advance Excel
14 Range names for an Excel list (like the simple one below) can be used to simplify
references and in calculations.
In this example, select the list (the range B3:C7 in the illustration below)and use Insert,
Name, Create to open Excels Create Names dialog. Excel guesses where the likely
names are in relation to the data. In this case, the data is in C4:C7 and the names come
from the top row and left column. With names established, you can use a shorthand
reference to refer to the numeric cells. Cell C4 can also be called January A since it falls
at the intersection of those row and column names. In like manner, Cell C5 can also be
referred to as January B. Cell E5 contains the formula =January A and displays the value
10. Cell E6 contains the formula = January A + January B and displays the value 25.
Theres another way to name a range whose values you intend to use in a calculation:
By using the special Label Ranges dialog. In this example, imagine you have a list of
values like the one at right, with the label Year99 at the top of the column. Select the
range (including the label) and choose Insert, Name, Label to open the Label Ranges
dialog. Excel fills in the label range.
Specify that youre using
Column labels and click OK.
Use this method to specify ranges that contain column and row labels on your
worksheet.
Year99
10
30
50
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.
13
Advance Excel
where you need it. If you copy a formula, you must understand Excels 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, its 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 Excels default mode when copying formulas. Its relative
addressing. 20
There may be occasions, however, when you want to override Excels 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. (Its 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
14
Advance Excel
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
Excels 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.
15
Advance Excel
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.
E F G
First
S S
HS Elem
x t
J K L M N
O P
T T T Av
1 2 3 g
G Grad
P e
Cours Sec
Last
e
t
MS
101
M0
Abena
KH
Albert
F K
Lelu
8
a
S
Kosraen
8 8 8
Promo
82
3 2 1
te
3 B
MS
101
M0
PIC
Aldis Adjoa F P
PCS
8
S
Pohnpeia 7 7 7
Promo
77
n
7 7 7
te
2 C
MS
101
M0
Elidok Ama
8
CH Puluw Puluwate 9 9 9
Promo
92
S at
se
te
4 2 0
4 A
MS
101
M0 Georg Kwek
KH Male
M K
8 e
u
S m
F C
Lang
Kosraen
Pass
5 5 6
59 Repeat
8 9 0
0 F
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
A
16
Advance Excel
Column chart
What many call a "bar chart" Excel calls a "Column chart" or column graph.
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
Female Male
0-4
-7117 7545
5-9
-7158 7932
17
-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
-965 1013
65-69
-669 639
70-74
-627 542
75-79
-281 263
80-84
-176 137
85-89
-58
41
90-94
-30
26
95-99
-8
Advance Excel
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.
18
Advance Excel
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, xaxis, 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.
19
Advance Excel
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 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.
20
Advance Excel
21
Advance Excel
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 box.Set 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.
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.
22
Advance Excel
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.
23
Advance Excel
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
1 State
C D E
Sex T3
2 Pohnpei F
80
Grand Total
Average of T3 Sex
State
3 Pohnpei M 65
Chuuk
82.5 67.5 75
4 Pohnpei F
Pohnpei
75
Grand Total
70
5 Pohnpei M 75
6 Chuuk
7 Chuuk
M 60
8 Chuuk
9 Chuuk
M 75
70
72.5
95
70
24
Advance Excel
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.
25
Advance Excel
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.
26
Advance Excel
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.
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
27
Advance Excel
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.
Location
Beach
Pond
River
Rock
Tree
10
28
Advance Excel
Tree
Tree
Tree
Tree
Tree
M 0
Tree
M 1
Tree
M 1
Tree
M 1
Tree
M 1
Tree
M 1
Pond
Pond
Pond
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.
29
Advance Excel
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.
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).
30
Advance Excel
31
Advance Excel
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.
32
Advance Excel
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:
33
Advance Excel
34
Advance Excel
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).
35
Advance Excel
36
Advance Excel
Choose Open from Microsoft Excels 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 dont 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 didnt 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
37
Advance Excel
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.
38
Advance Excel
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.
39
Advance Excel
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.
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.
40
Advance Excel
41
Advance Excel
Formulas
Calculations using addition, subtraction, division and multiplication
Excel is an electronic spreadsheet that can be likened to a great sheet of paper, divided
into 256 columns and 16,384 rows, in which we can store texts and numbers. But the
great advantage of this program is how values and texts, stored within the sheet, can be
manipulated in such a way that the user finds best, by means of a great number of a
valuable formula that can be used at any given moment.
Used for
Greater than
Less than
Equal to
Different from
Greater or equal to
Equal or less than
Addition
Subtraction
Multiplication
Division
Exponential
Percentage
Example
F5>H7
D4<H3
G5=H6
G5oC10
14>=D2
13<=G6
B1+B7
X4-9
C9*D4
D7/A2
G5A9
235*10%
Functions
Excel has pre-defined functions that facilitate a wide range of calculations and tasks. All
you need to do to make a function work is to supply it with the appropriate values in
order to make the calculation. The functions must start with the equals sign (=)
ininterpret them as formulas and not as text. It is also advisable to type the name of the
function and of the cells in capital letters.
42
Advance Excel
SUM Formula
i.e., =SUM (A1:A7) The formula will add all the values that it finds in address Al until
address A7. The formula will always be the same; all that will change, are the addresses
of the values that you wish to add up.
See the example:
In this example, all the values from Al to Dl were added. The formula used was =SUM(A1
:D1) and, on pressing Enter, the result appeared. In this case the result was 45.
To reach this result, you need to follow these steps:
1. Place the cursor in the cell that will store the result of the calculation.
2. Type in the equals sign (=) to indicate that a formula is to be entered into the cell.
3. Insert the address of the cell that contains the first data value to be added.
4. Type the plus sign (+) to show that an addition is to be made.
5. Type the cell address that contains the next result to be added and so on and so forth.
6. Press the Enter key.
However, there is an easier way to add up by using the AutoSum button %.
To work with the AutoSum button, do the following:
1. Select the values that you wish to add up.
2. 2. Then click the AutoSum button and it will show the answer.
Subtracting Cells
Imagine you have created a complex table with all your expenditure over the last six
months and wish to know what balance will be left over, in order to make an
investment. The procedure is quite simple:
1. Select the cell which will hold the result of the opera
2. Type in the equals sign (=) to indicate that a formula is to be entered into the
cell.
3. Insert the address of the cell that contains the first data value from which it is
to be subtracted.
4. Type the minus sign (-) to show that a subtraction is to be made.
5. Type the cell address that contains the value to be subtracted.
6. Press the Enter key to conclude the operation. The result should be as shown
in the image.
Multiplication Formula
The four basic mathematical operations have similar formulas in Excel. In case of
multiplication, you just need to use the same scheme you used for subtraction, changing
just the subtraction symbol for that of multiplication (*).
43
Advance Excel
Division Formula
To make a division, you must use the formula in much the same manner as before. You
just need to change the sign to division (/).
Procedure:
1. Select the cell which will hold the result of the operation.
2. Type in the equals sign (=) to indicate that a formula is to be entered into the cell.
3. Insert the address of the cell that contains the first data value to be divided.
4. Type the division sign (/) to show that a division is to be made.
5. Type in the cell address that contains the value to be divided.
6. Press Enter to conclude the operation. Copying and Moving Formulae If you make a
lot of calculations in a spreadsheet, you dont need to type in the formula every time
you use it. You can either copy or just move it.
Copying Formula
To copy a formula the procedure is as follows:
1. Click on the cell to be copied.
2. Access the Edit menu and choose Copy, or use the shortcut Ctrl + C.
3. Click on the cell or region where you wish the formulas to be copied.
4. Open the Edit menu and choose Paste, or use the shortcut Ctrl + V
Moving Formula
You can also move a formula, which will save having to retype it every time it is needed.
1. Select the cell to be moved.
2. Open the Edit menu and choose Cut, or use the shortcut Ctrl + X.
3. Click on the cell or region where you wish the formulas to be moved.
4. Open the Edit menu and choose Paste, or use the shortcut Ctrl + V.
Formulas
A simple step-by-step project that explains the basic formulas
In the previous pages you have been introduced to some of the basic concepts about
the application of formulas within Microsoft Excel. Now, we are going to learn how to
44
Advance Excel
put into practice the four basic operations in mathematics: addition, subtraction,
multiplication and division.
Addition
1. With Excel open, create a sheet with the items Products, Value and Quantity.
2. Now, fill in the items with the values you wish to add up. You can also use numbers
with decimal points.
3. To apply the formula for addition, click on cell C4 and type the formula =C2+C3. It will
give you the answer to the sum of the two figures.
Subtraction
1. To learn how to use the formula for subtraction, make a sheet with the items
Products, Value, Quantity and Sold.
2. Fill in the Sold field with the number of products that are no longer in stock.
3. Click on cell E2 and type the following formula =C2-D2. In this case the answer will
give the result of the subtraction
Multiplication
1. To multiply numbers, let us use the same sheet from the previous example.
2. Click on cell E2 and type the following formula; =B2*D2 and press Enter.
3. Repeat the same operation in order to carry out the calculation for black pen by
changing just the cells (=B3*D3).
Division
1. Now we shall make a division with values that we have in our spreadsheet. (Products,
Price of Box, Quantity in Box and Unit Value).
2. Fill in the corresponding numbers of the items (Products, Value, Quantity in Box) to
discover the unit value.
3. Now, just click in cell D2 and type the formula =B2/C2. This will return the result of
the division of the two numbers.
2
Beyond the E=MC Basics
Learn to use the most important functions of Excel
If you want to know how many students didnt reach the final average from a table
consisting of several names, you can use the formula _ COUNTBLANK. It counts the
cells that have no value. Follow these steps:
1. Create a sheet with the columns Student and Average. Fill the cells with the names
and the values of their scores.
2. To know how many students failed to reach the required average in the sheet, type
the following formula: =COUNTBLANKB2:B7)
45
Advance Excel
3. To understand the function: =COUNTBLAXK is the name of the formula; (B2:B7) refers
to the addresses of the cells.
Other formulas
COUNT: Calculates how many cells contain numbers and the numbers contained in the
lists of arguments.
Example: If all the cells in A1:A10 contain numbers except the cell A5. Which is empty
and A7, which contains a
word, then: COUNT(A1:A10) will give the answer 8.
DCOUNTA: Calculates the number of cells that are not empty, and the existing values in
the argument list.
Example: If all the cells in Al :A10 contain numbers, except the cell A5, which is empty
and the cell A7, which contains a word, then: DCOUNTA(Al :A10) will return the answer
9.
STDEV: This calculates the standard deviation from a mean within a sample. The
standard deviation is a measure of the degree of dispersion of values in relation to an
average value.
Example: Let us suppose that 10 tools made in the same machine during production are
collected as a random selection and are then measured to check their resistance to
breakage. The values of the sample (1345, 1301, 1368, 1322, 1310, 1370, 1318, 1350,
1303, 1299) are stored in cells A2:E3, respectively. STDEV estimates the standard
deviation of resistance to breakage for the entire sample. STDEV(A2:E3) equals 27.46.
ABS: Provides the absolute value of a number. The absolute value is the same figure
without a plus or minus sign.
Examples: =ABS(-4) will give us 4
=ABS(4) will also give us 4
ROUND: Rounds up the number to the nearest determined number of decimal places.
Examples: =ABS(-4) will give us 4
Examples: =ROUND(2.149;l) will give us 2.1;
=ROUND (1.475;2) will give us 1.48; =ROUND (2,5;-1) will give us 20.
46
Advance Excel
Conditional Functions
Learn how to transform your Excel spreadsheets into efficient tools for analyzing data
On opening Excel for the first time, none of us ever imagined the power and capacity of
all those rows and columns. Behind this great table, exist hundred of formulas,
functions, and filters amongst other recourses that help build Excels reputation as the
best spreadsheet editor. Nevertheless, to get the most out of this tool it is necessary to
know what these recourses are and how to use them: otherwise Excel becomes nothing
more than an enormous database, built up of hundreds of rows and columns.
In this step-by-step tutorial, we shall deal with conditional functions - formulae that
allow us to create sheets that give us results based on certain given conditions. Check
out the examples of the If, And & Or functions that we introduce here, in this step-bystep guide, and adapt their usage in accordance to your needs.
47
Advance Excel
argument: B1>10 and close the brackets. The final formula should look like this:
=AND(A1>7,B1<10).
Third Step: To finish, press Enter. Now, using the function AND, the result will only
return TRUE if all the arguments comply.
IF
Test: In this attribute, an expression will be considered to see if it has either a TRUE or
FALSE value
Value if true: The returned value, if the test argument proves to be TRUE. For example, if
we have an argument as a sequence of letters such as Approved and this argument for
the test was put as TRUE, the function IF will show Approved in the corresponding cell
of the formula. If the test is TRUE and Value if true is blank, the argument will return the
value zero.
Value if false: The returned value if the test is FALSE. For example, if this argument is a
sequence of characters Failed and the test argument is FALSE, the function IF will
show Failed. If the test is FALSE and value if false is blank, the value zero will be
returned
AND(argument1; argument2..)
In this function, all the arguments must be considered for the function to return the
value TRUE. The function AND can also be used in conjunction with the function IF,
transforming it into a twin function.
Example
=AND(5<8;13>2)~> Function will return the value True, as all arguments are true.
=AND(4>5;7>6)) > Function will return the value False, as only one of the arguments
proves to be true.
OR
Unlike the function AND, the function OR requires at least one of the tested arguments
to be true for it to return the value TRUE. This function will only return the value FALSE,
should all of the tested arguments prove to be false.
Examples
=OR(1 <2;8>4) > Function returns the value True, because all the arguments are true.
=OR(1>2;8>4)) -> Function returns the value True, because two of the arguments are
true. =OR(1>2;8<4) > Function returns the value False, because all the arguments are
false.
48
Advance Excel
Fourth Step: For the formula to return TRUE. even when only one of the two arguments
is TRUE, use the function OR. Change just the formula to OR instead of AND.
Fifth Step: There is a further logical function used to invert the logical value of an
argument, which means, if the value of a cell is true, the return will be FALSE and if the
value is false the return will be TRUE. This function is called NO.
Sixth Step: Type, for example, in cell D1: =NO C1). Apart from this, it is also possible to
mix all these functions to a
more
specific
result. i.e., =ANDORAVE D8:D16
>7;E8=10).
49
Advance Excel
;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*
50
<=
<>
Advance Excel
Description
Equals returns TRUE when the two values
are equal
Greater than returns TRUE when the first value
is greater than the second
Less than returns TRUE when the first
value is less than the second
Greater than or equal to returns TRUE
when the first value is greater than or
equal to the second
Less than or equal to returns TRUE
when the first value is less than
or equal to the second
Different returns FALSE when the
two compared values are different
=A2=A5
TRUE
=A2>A5
TRUE
=A2<A5
TRUE
=A2>=A5
TRUE
=A2<=A5
TRUE
=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
51
Advance Excel
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 todays 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.
52
Advance Excel
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.
53
Advance Excel
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 students 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).
54
Advance Excel
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
RAHUL
RAJ
ROCKY
RAHIM
WAHAB
ANIL
SACHIN
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
55
Advance Excel
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
56
Advance Excel
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
number of columns ?
57
Advance Excel
58
Advance Excel
11. You can create hyperlinks from the Excel workbook to?
A webpage on company internet
A web page on the internet
Other Office 97 application documents
All
12. The advantage of using a spreadsheet is?
Calculations can be done automatically.
changing data automatically updates calculations
more flexibility
all of the above
13. The intersection of a row and column is called?
Data
a field.
a cell
an equation
14. There are three types of data found in a spreadsheet.?
data, words, numbers
equations, data, numbers
words, numbers, labels
numbers formulas, labels
15. If you press , the cell accepts your typing as its contents.?
Enter
Ctrl+Enter
Tab
Insert
16. Which If you press , the cell accepts your typing as its contents.?
Esc
Shift
Return
Tab
17. Which is not an advantage of using computerized spreadsheets?
Flexibility of moving entries
Speed of calculation
Ability of generate tables
cost of initial setup
59
Advance Excel
18. To select several cells or ranges that are not touching each other, you would
while selecting?
Hold down the Ctrl key
Hold down the Shift key
Hold down the Alt key
Hold down Ctrl + Shift key
19. A constant is another name for this type of data:?
Number
Equation
Formula
Description
60
Advance Excel
MODULE II
61
Advance Excel
62
Advance Excel
You might not see the 3 windows on your screen. We will fix that right now and it can be
a little tricky. But once you have set them they will stay in their position always.
If there are any window open under the tool bars close them. On the menu bar of the
VBE choose "View" and select "Properties Window". The window can appear minimized,
it can be full width at the top of the screen or many other ways. You want it from top to
bottom on the right of the screen. To do so click on its blue line at the top, hold and drag
it to the bottom right corner. It is now minimized. Click again on its blue header,
hold and drag it full left (it will even disappear) toward the vertical middle of the screen.
It is now in the following position:
63
Advance Excel
Then go back to the menu bar and select "Project Explorer". From wherever it is click on
its blue header, hold and drag it all the way down in the bottom right corner. It is now
free.
Reduce the size of the "Project Explorer" to about the width of the "Properties Window"
and one third the height by using the double arrows that appear when you move the
64
Advance Excel
mouse over the border of the "Project Explorer" . Click again on its blue header, hold
and bring the top left corner of the "Project Explorer" over the top left corner of the
"Properties Window". Then let go.
You now have the "Project Explorer" over the "Properties Windows" in the left part of
your screen. The "Code Window" appears when you double click on a sheet name in the
"Project Explorer" . You will see later that the "Code Window" also appears when you
double click on a user form name or a module name.
You can resize the 3 windows by placing the cursor over the borders (*) and dragging
them right, left, up or down.
You can use "ALT/F11" to navigate from Excel to the VBE and back.
2. In the Record Macro dialog box, type "SetBackgroundColor" in the Macro Name
textbox to set the macro name. Leave all other option by default then click the Ok
65
Advance Excel
3. In the Background Color Panel, select the Light Yellow color box. This action will set
the background of the current cell (A1) in light yellow color.
4. To stop the macro recording, click the Stop button (the navy blue rectangle) on the
Macro Recorder toolbar.
66
Advance Excel
Now you have recorded a macro that set cell background to light yellow.
2. Expand the Modules folder in the Project Explorer by clicking on the plus (+) sign.
67
Advance Excel
3. Double click the Module1 folder to see the sub routine (marco).
As the figure shows, the name of the sub routine is "SetBackgroundColor". The color
index for the light yellow is 36. The background pattern is solid.
2. Run the recorded macro by select Tools...Macro...Macros... or press [Alt] and [F8] at
the same time.
68
Advance Excel
3. The Macro dialog box displayed. Since there is only one macro in the module, by
default the only macro, SetBackgroundColor is selected. Click the Run button to run the
macro.
69
Advance Excel
Note that, Worksheets.Range("A1", "B5") = "AB" will yield the same result as the above
example.
The following place "AAA" on cell A1, A3, and A5 on
Sheet2.Worksheets("Sheet2").Range("A1, A3, A5") = "AAA"
Range object has a Cells property. This property is used in every VBA projects (very
important). The Cells property takes one or two indexes as its parameters.
For example,
Cells(index) or Cells(row, column)
where row is the row index and column is the column index.
70
Advance Excel
* The small gray number on each of the cells is just for reference purpose only. They are
used to show how the cells are indexed within the range.
71
Advance Excel
2. In the Insert menu on top of the Visual Basic Editor, select Module to open the
Module window (code window).
72
Advance Excel
73
Advance Excel
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.
74
Advance Excel
The output:
75
Advance Excel
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
My.Car
ThisYear
1NewBoy
Long_Name_Can_beUSE He&HisFather
Group88
Student ID
b) Declaring Variables
In VBA, one needs to declare the variables before using them by assigning names and
data types. There are many VBA data types, which can be grossly divided into two types,
namely the numeric data 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
76
Single
4 bytes
Advance Excel
Storage
Length of string
Length + 10 bytes
8 bytes
2 bytes
4 bytes
16 bytes
Length+22 bytes
Range
1 to 65,400 characters
0 to 2 billion characters
January 1, 100 to December 31, 9999
True or False
Any embedded object
Any value as large as Double
Same as variable-length string
77
Advance Excel
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
The output screen of 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
End Sub
78
Advance Excel
If you want you want part of your message to be between quotes you need to double
the quotes as in:
Input Boxes
You need to declare (create) a variable to receive the answer to a VbYesNo messsage
box or an input box.
For the input box you will write:
varAnswer = InputBox("For how many years?", "Duration")
79
Advance Excel
80
Advance Excel
81
Advance Excel
The elements index of the array starts from 0 unless Option Base 1 is specified in the
public area (area outside of the sub procedure). If Option Base 1 is specified, the index
will start from 1.
The following example assigns values to the array and displays all values in a message
box :
Option Base 1
Sub assignArray( )
Dim Arr(5)
Arr(1) = Jan
Arr(2) = Feb
Arr(3) = Mar
Arr(4) = Apr
Arr(5) = May
Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5)
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.
82
Advance Excel
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.
By replace the Redim Arr(6) with Redim Preserve Arr(6), all values will remain. For
example:
Option Base 1
Sub assignArray( )
83
Advance Excel
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
CD Sale
DVD Sale
Year 2003
1,000
1,200
Year 2004
1,500
2,000
84
Advance Excel
* 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"
Decision Structures
Using If.....Then....Else
85
Advance Excel
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 If..Then...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 singleline 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.
86
Advance Excel
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
Msgbox "You are eligible to apply for Social Security Benefit"
Else
Msgbox "You cannot drink or vote"
End If
Note that the last condition under Else is, implicitly, Age < 18.
Lets take one more example :
The Code
Private Sub CommandButton1_Click()
Dim mark As Integer
Dim grade As String
Randomize Timer
mark = Int(Rnd * 100)
Cells(1, 1).Value = mark
If mark < 20 And mark >= 0 Then
grade = "F"
Cells(2, 1).Value = grade
ElseIf mark < 30 And mark >= 20 Then
grade = "E"
Cells(2, 1).Value = grade
ElseIf mark < 40 And mark >= 30 Then
grade = "D"
Cells(2, 1).Value = grade
ElseIf mark < 50 And mark >= 40 Then
grade = "C-"
Cells(2, 1).Value = grade
ElseIf mark < 60 And mark >= 50 Then
grade = "C"
Cells(2, 1).Value = grade
ElseIf mark < 70 And mark >= 60 Then
grade = "C+"
Cells(2, 1).Value = grade
ElseIf mark < 80 And mark >= 70 Then
87
Advance Excel
grade = "B"
Cells(2, 1).Value = grade
ElseIf mark <= 100 And mark > -80 Then
grade = "A"
Cells(2, 1).Value = grade
End If
Output :
88
Advance Excel
89
Advance Excel
Explanation:
To set the cell align alignment to center, we use the following procedure:
Range("A1:B1").Select
With Selection
.HorizontalAlignment = xlCenter
End With
We can use the statement case value1 to value 2 to specify the range of values that
fulfill the particular case.
You should also include the error case where the values entered are out of the range or
invalid. For example, if the examination mark is from 0 to 100, then any value out of this
range is invalid. In this program, I use case else to handle the error entries.
One More Example:
Select Case Grade
Case Is >= 90
LetterGrade = "A"
Case Is >= 80
LetterGrade = "B"
Case Is >= 70
LetterGrade = "C"
Case Is >= 60
LetterGrade = "D"
Case Else
LetterGrade = "Sorry"
End Select
90
Advance Excel
Loop Structures
This feature makes repetitive works easier.
For ... Next
Use For ... Next loop if the number of loops is already defined and known. A For ... Next
loop uses a counter variable that increases or decreases in value during each iteration of
the loop. This loop structure is being used the most for our examples on this site.
Here is an example of the For ... Next loop:
For i = 1 to 10
Cells(i, 1) = i
Next i
In this VBA program, you place the command button 1 on the spreadsheet then click on
it to go into the Visual Basic editor. When you click on the button , the VBA program will
fill cells(1,1) with the value of 1, cells(2,1) with the value of 2, cells(3,1) with the value of
3......until cells (10,1) with the value of 10. The position of each cell in the Excel
spreadsheet is referenced with cells(i,j), where i represents row and j represent column.
Note that the counter variable i, by default, increase by an increment of 1.
For ... Next Loop With Step
You can use the Step Keyword to sepcify a different increment for the counter variable.
For example:
For i = 1 to 10 Step 2
Cells(i,1) = i
Next i
91
Advance Excel
This looping process will print values with an increment of 2 on row 1, 3, 5, 7 and 9 on
column one.
You can also have decrement in the loop by assign a negative value after the Step
keyword.
For example:
For i = 10 to 1 Step -2
Cells(i,1) = i
Next i
This looping process will print values with an increment of -2 starts from 10 on row 10,
8, 6, 4 and 2 on column one.
DO.........LOOP
In the previous chapter, you have learned to use the For........Next loop to execute a
repetitive process. In ts chapter, you will learn about another looping method know as
the Do Loop. There are four ways you can use the Do Loop as show below.
92
ANIMATIX COMiP) U
T.E..R...E..D
IOhNile
Do
...U
LoCoApTW
(ii) Do until.............Loop
(iii) Do while............Loop
(iv) Do............Loop until
Example 1
Private Sub
CommandButton1_Click()
Dim counter As Integer
Do
counter = counter + 1
Cells(counter, 1) = counter
Loop While counter < 10
End Sub
In this example, the program
will keep on adding 1 to the
preceding counter value as
long as the counter value is
less than 10. It displays 1 in
cells(1,1), 2 in cells(2,1)..
until 10 in cells (10,1).
Example 2
Examle 3
Private Sub
Private Sub
CommandButton1_Click() CommandButton1_Click()
Dim counter As Integer Dim counter , sum As Integer
Do Until counter = 10
'To set the alignment to center
counter = counter + 1
Range("A1:C11").Select
Cells(counter, 1) = 11 - With Selection
counter
.HorizontalAlignment =
Loop
xlCenter
End With
End Sub
Cells(1, 1) = "X"
In this example, the
Cells(1, 2) = "Y"
program will keep on
Cells(1, 3) = "X+Y"
adding 1 to the preceding
counter value until the Do While counter < 10
counter value reaches
counter = counter + 1
10. It displays 10 in
Cells(counter + 1, 1) = counter
cells(1,1), 9 in cells(2,1)- Cells(counter + 1, 2) = counter
.. until 1 in cells (10,1). * 2
sum = Cells(counter + 1, 1) +
Cells(counter + 1, 2)
Cells(counter + 1, 3) = sum
Loop
End Sub
In this example, the program
will display the values of X in
cells(1,1) to cells(11,1). The
value of Y is X2 and the values
are display in column 2, i.e.
from cells(2,1) to cells(2,11).
Finally, it shows the values of
X+Y in column 3, i.e. from
cells(3,1) to cells(3,11)
93
Example 2
Example 3
One thing to be caution is that sometimes the loop might be a infinite loop. And it
happens when the condition never becomes false. In such case, you can stop the loop
by press [ESC] or [CTRL] + [BREAK].
94
95
and
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.
96
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:
97
Types of Functions
There are two types of Excel VBA functions; one is the built-in functions while the other
one is the user-defined functions. We can use built-in functions in Excel for automatic
calculations. Some of the Excel VBA built-in functions are Sum, Average, Min (to find the
minimum value in a range), Max (To find the maximum value in a range), Mode, Median
and more. However, built-in functions can only perform some basic calculations, for
more complex calculations, user-defined functions are often required. User-defined
functions are procedures created independently from the event procedures. A Function
can receive arguments passed to it from the event procedure and then return a value in
the function name. It is normally used to perform certain calculations.
Writing Function Code
98
In the Visual Basic Editor window, insert a module by clicking Insert on the menu bar,
and then click on Module, as shown in Figure.
In the module environment, key in the function code for the function Area_Rect , as
shown in the diagram below.
99
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.
10
0
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
10
1
10
2
10
3
10
4
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
10
5
10
6
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
Creating a Financial Calculator
Excel VBA can be programmed to perform complex financial calculations. Here we have
created a financial calculator to calculate the periodic payment for a loan taken from the
bank. Below is the Excel VBA code for the financial calculator and its output interface.
Private Sub CommandButton1_Click()
Dim N As Integer
Dim p, pmt, rate, I, PVIFA As Double
p = Cells(2, 2)
rate = Cells(3, 2)
N = Cells(4, 2) * 12
I = (rate / 100) / 12
PVIFA = 1 / I - 1 / (I * (1 + I) ^ N)
pmt = p / PVIFA
Cells(5, 2) = Format(pmt, "$#,##0.00")
End Sub
The formula to calculate periodic payment is payment=Initial Principal/PVIFA, where
PVIFA is known as present value interest factor for an annuity. The formula to
compute PVIFA is 1/i - 1/i(1+i)n where n is the number of payments. Normally you
can check up a financial table for the value of PVIFA and then calculate the payments
manually.
The function Format is to determine the number of decimal places and the use of the $
sign.
10
7
10
8
Explanation:
rng is declared as range and we can set it to include certain range of cells, here the
range is from A1 to A10.
Then I used the For .......Next loop to scan through the selected range
rng.Cells(i).Value read the value in cells(i) and then passed it to the variable mark.
To do selective addition, I used the statement Select Case....End Select
Finally, the results are shown in a message box
10
9
Tab Order
Once you have added the controls here is an important feature. The user can use the
mouse to move from one control to the other but he should also be able to move from
one control to the other by entering a value in one and clicking "Enter" or "Tab" and the
focus will be set on the next control where he is supposed to enter a value not on a
label. More importantly when the user enters a value in the final control you ant the
focus to be on the right command button (Submit) and not on another one like " Close
Form" .
To make sure that the user moves from one control to the next one in a set order you
need to set the tab order. To do so, right click on the form itself and select the "Tab
Order" item. Follow the instructions. The first control in the list will be the one that is
active (flashing cursor within) when the form is activated. Bring the controls that are
not to be used by the user (labels) at the end of the list. For the controls that are not to
be used you can also set the "TabStop" property of the individual control to "False" in
the properties window.
Managing Controls
You can move the controls by clicking on them holding and moving them around. You
can resize them by selecting them and using the different handles around them. You can
copy or cut them by right clicking on them and choosing the right menu item.
Once you have added your controls you might want to align a few of them or resize a
few so that they are all the same size. To do so you first need to select many controls at
11
0
When you let go of the button all the controls that are touched by the frame are
selected.
Right click on any of the selected controls and this contextual menu appears:
You can then align the controls (7th menu item) or make them the same size (8th menu
item).
11
1
In the Properties window of the VBE you MUST change the name "(Name)" of the form,
its caption (the name in the blue band at the top of the UserForm) and you can also
modify the default setting of any of the 32 other properties of the form.
When you name a form always use the prefix "frm" like in "frmDatabase" and be as
descriptive as you can be so that your code will be easy to read. Always use one or more
upper case letters in the name. When you write "frmdatabase.show" in lower case
letters Excel will capitalize some letters "frmDatabase.Show" letting you know that the
name is spelled correctly.
The caption is what your users will se at the top of the userform. Be as informative as
possible and complete the information with a label if necessary.
11
2
Else than the Name and Caption there are just a few properties that you might want to
modify. You can select a different color for the background with the property
"BackColor".
By default the userform appears in the center of the screen. If you want it to show
somewhere else set the "Start" property to "0-Manual" and use the "Top" and "Left"
properties to set a new position.
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:
frmCity.Show
The line of code to close the userform is:
frmCity.Hide or Me.Hide "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" .
11
3
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.
11
4
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
frmPassword.Hide
End Sub
The content of the combo box "cbxInput" is entered in cell "F1" of the sheet "Code" and
the form (frmPassport) is closed.
11
5
List Boxes
Before we begin on the List Box
The difference between a combo box and a list box is that the combo box is a dropdown 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
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.
Combo Boxes
Before we begin on the Combo Box
The difference between a combo box and a list box is that the combo box is a dropdown 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.
11
6
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 friendly Excel drop-down lists in the website on
Excel.
When you double click on the combo box in the Visual Basic Editor you will see all its
properties in the Properties 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.
and,
11
7
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:
11
8
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.
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.
11
9
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
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()
frmWeighing.Show
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:
12
0
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.
Open many workbooks with macros in them. When you go to the menu
"Tool/Macro/Macros.." you will notice that you have access to all the macros from all
the open workbooks. This means that you can store ALL your useful Excel macros in a
single workbook (call it myMacros.xls) and have access to them while the workbook is
opened. Let's say for example that you have designed a macro that multiplies the
content of a cell by 2. If "myMacros.xls" is open you can call this Excel macro from any
12
1
This window is no problem if you or close colleagues are the only users of the workbook.
But in other rare cases where you distribute your workbooks to many users you will
probably prefer to have a more useful error message.
Here is the basic way to handle errors.
A VBA procedure usually runs from Sub to End Sub. In a VBA procedure that includes an
error handler it will run from Sub to Exit Sub but if there is an error happening during
the execution it will jump to a special address where the error handler resides.
So to add error handling capabilities to any of your VBA procedures you follow these
steps:
1- Add an Exit Sub right before End Sub
2- Between these two lines add an address ending with a colon (addJump: for example)
3- Make room between the address line and End Sub to enter your code handling the
error.
12
2
Adopt the same attitude as you have with documents attached to Emails. If you know
the origin of the file you may enable the macros if not click on "Disable Macros" and you
are fully protected. You can look at the workbook but the VBA procedures (macros) are
not operational. You can go to the Visual Basic Editor to take a look at the macros. If
nothing looks suspicious close the workbook and re-open it enabling the macros.
12
3
Forms Controls
ActiveX Controls
VBA Controls
12
4
Forms controls can be used on worksheets and chart sheets. Forms controls can also be
placed within embedded charts in Classic Excel (though not in Excel 2010). ActiveX
controls can only be used on worksheets. Excel responds to a Forms control after the
user finishes interacting with it (i.e., unclicks). Excel responds continuously to an ActiveX
control. If a Forms slider control is linked to a cells value, the user has to slide the bar
on the control, then release it before the cell updates. If an ActiveX ScrollBar is linked to
the cells value, the cell updates continuously as the user slides the bar along the
control.
In general I use the Forms controls, unless I need the continuous response of an ActiveX
scrolllbar.
Formatting Controls
Forms controls can be formatted as if they were regular shapes (Excel 95 to Excel 2003
shapes; the new shapes in Excel 2010 are different animals altogether), although the
options are not as extensive as for shapes, and vary for different control types. The
button dialog (below) is much like that for shapes with various Font, Size, Alignment,
and similar tabs, although the button is stuck with its gray color and rectangular shape.
A regular shape can be assigned a macro in much the same way, with all the shapes
formatting options.
12
5
Also depending on the control, there is a tab for properties specific to the control. For a
Drop Down or List Box control, there is a means to select an input range, containing the
list of items appearing in the control, and another for a cell link, which is where the
selected item in the control is stored.
12
6
12
7
Project Assignment:
Make a project for a Shopping mall as per the following requirements:
Category
Electronic Goods
Clothing
Items
Television
Refrigerator
Microwave
Sari
Shirts
Panjabi Suits
12
8
12
9