Cours Excel

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

XlMaxi Course Manual

Contents
LOOKUP FUNCTIONS: .................................................................................................................................................3
VLOOKUP .................................................................................................................................................................3
HLOOKUP .................................................................................................................................................................4
LOOKUP...............................................................................................................................................................5
MATCH......................................................................................................................................................................5
INDEX........................................................................................................................................................................6
INDIRECT..................................................................................................................................................................7
CHOOSE ...................................................................................................................................................................7
USING DATABASE FUNCTIONS:.................................................................................................................................8
DSUM ........................................................................................................................................................................8
DMIN .......................................................................................................................................................................11
DMAX ......................................................................................................................................................................14
DCOUNT .................................................................................................................................................................17
CHARTS ......................................................................................................................................................................20
WATERFALL CHARTS ...........................................................................................................................................20
TORNADO CHARTS ...............................................................................................................................................22
Creating a PivotTable...................................................................................................................................................22
Modifying data and refreshing the Pivot Table.........................................................................................................26
Grouping data within a Pivot table ...........................................................................................................................28
MACROS .....................................................................................................................................................................30
RECORDING A MACRO .........................................................................................................................................30
USERFORMS..........................................................................................................................................................31
DATA VALIDATION

LOOKUP FUNCTIONS:

VLOOKUP
In Excel, the VLookup function searches for value in the left-most column of table_array and returns the value in the
same row based on the index_number. The syntax for the VLookup function is: VLookup( value, table_array,
index_number, not_exact_match ) value is the value to search for in the first column of the table_array. table_array is
two or more columns of data that is sorted in ascending order. index_number is the column number in table_array
from which the matching value must be returned. The first column is 1. not_exact_match determines if you are
looking for an exact match based on value. Enter FALSE to find an exact match. Enter TRUE to find an approximate
match, which means that if an exact match if not found, then the VLookup function will look for the next largest value
that is less than value. Note: If index_number is less than 1, the VLookup function will return #VALUE!. If
index_number is greater than the number of columns in table_array, the VLookup function will return #REF!. If you
enter FALSE for the not_exact_match parameter and no exact match is found, then the VLookup function will return
#N/A.

HLOOKUP
In Excel, the HLookup function searches for value in the row of table_array and returns the value in the same
column based on the index_number. The syntax for the HLookup function is: HLookup( value, table_array,
index_number, not_exact_match ) value is the value to search for in the first row of the table_array. table_array is
two or more rows of data that is sorted in ascending order. index_number is the row number in table_array from
which the matching value must be returned. The first row 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 FALSE to find an approximate match, which
means that if an exact match if not found, then the HLookup function will look for the next largest value that is less
than value. Note: If index_number is less than 1, the HLookup function will return #VALUE!. If index_number is
greater than the number of columns in table_array, the HLookup function will return #REF!. If you enter FALSE for
the not_exact_match parameter and no exact match is found, then the HLookup function will return #N/A.
LOOKUP

In Excel, the Lookup function returns a value from a range (one row or one column) or from an array. There are 2
different syntaxes for the Lookup function: Syntax #1 In Syntax #1, the Lookup function searches for value in the
lookup_range and returns the value in the result_range that is in the same position. The syntax for the Lookup
function is: Lookup( value, lookup_range, result_range ) value is the value to search for in the lookup_range.
lookup_range is a single row or single column of data that is sorted in ascending order. The Lookup function
searches for value in this range. result_range is a single row or single column of data that is the same size as the
lookup_range. The Lookup function searches for the value in the lookup_range and returns the value from the same
position in the result_range. Note: If the Lookup function can not find an exact match, it chooses the largest value in
the lookup_range that is less than or equal to the value. If the value is smaller than all of the values in the
lookup_range, then the Lookup function will return #N/A. If the values in the Lookup_range are not sorted in
ascending order, the Lookup function will return the incorrect value.

MATCH
In Excel, the Match function searches for a value in an array and returns the relative position of that item. The syntax
for the Match function is: Match( value, array, match_type ) value is the value to search for in the array. array is a
range of cells that contains the value that you are searching for. match_type is optional. It the type of match that the
function will perform. The possible values are: match_type Explanation 1 (default) The Match function will find the
largest value that is less than or equal to value. You should be sure to sort your array in ascending order. If the
match_type parameter is omitted, the Match function assumes a match_type of 1. 0 The Match function will find the
first value that is equal to value. The array can be sorted in any order. -1 The Match function will find the smallest
value that is greater than or equal to value. You should be sure to sort your array in descending order. Note: The
Match function does not distinguish between upper and lowercase when searching for a match. If the Match function
does not find a match, it will return a #N/A error. If the match_type parameter is 0 and a text value, then you can use
wildcards in the value parameter. Wild card Explanation * matches any sequence of characters ? matches any single
character

INDEX
In Excel, the Index function returns either the value or the reference to a value from a table or range. Syntax #1 -
Returning a value The first implementation of the Index function returns the value from a table or range. The syntax
for the Index function is: Index( array, row_number, column_number ) range is a range of cells or table. row_number
is the row number in the array to use to return the value. column_number is the column number in the array to use to
return the value.
INDIRECT
In Excel, the Indirect function returns the reference to a cell based on its string representation. The syntax for the
Indirect function is: Indirect( string_reference, ref_style ) string_reference is a textual representation of a cell
reference. ref_style is optional. It is either a TRUE or FALSE value. TRUE indicates that string_reference will be
interpreted as an A1-style reference. FALSE indicates that string_reference will be interpreted as an R1C1-style
reference. If this parameter is omitted, the Indirect function will interpret string_reference as an A1-style.

CHOOSE
In Excel, the Choose function returns a value from a list of values based on a given position. The syntax for the
Choose function is: Choose( position, value1, value2, ... value_n ) position is position number in the list of values to
return. It must be a number between 1 and 29. value1, value2, ... value_n is a list of up to 29 values. A value can be
any one of the following: a number, a cell reference, a defined name, a formula/function, or a text value. Note: If
position is less than 1, the Choose function will return #VALUE!. If position is greater than the number of the number
of values in the list, the Choose function will return #VALUE!. If position is a fraction (not an integer value), it will be
converted to an integer by dropping the fractional component of the number. For example: Let's take a look at an
example: =Choose(1, "Tech", "on", "the", "Net") would return "Tech" =Choose(2, "Tech", "on", "the", "Net") would
return "on" =Choose(3, "Tech", "on", "the", "Net") would return "the" =Choose(4, "Tech", "on", "the", "Net") would
return "Net" =Choose(5, "Tech", "on", "the", "Net") would return #VALUE! =Choose(3.75, "Tech", "on", "the", "Net")
would return "the" VBA Code The Choose function can also be used in VBA code. For example: Dim LValue As
Boolean LValue = Choose(1, "Tech", "on", "the", "Net") In this example, the variable called LValue would contain
"Tech" as a value. Copyright © 2003-2006 Tech on the Net. All rights reserved. We are not responsible for any loss
or liability incurred by using this information.
OFFSET

In Excel, the Offset function returns a reference to a range that is offset a number of rows and columns from another
range or cell. The syntax for the Offset function is: Offset( range, rows, columns, height, width ) range is the starting
range from which the offset will be applied. rows is the number of rows to apply as the offset to the range. This can
be a positive or negative number. columns is the number of columns to apply as the offset to the range. This can be
a positive or negative number. height is the number of rows that you want the returned range to be. width is the
number of columns that you want the returned range to be.
USING DATABASE FUNCTIONS:

DSUM
 Open a workbook called Function DSUM. In this example, we will sum up the total value of all sales people
whose sales are above their sales targets.
 Click on cell D14.
 Click on the Formulas tab and from within the Function Library group click on the Insert Function button.

 This will display the Insert Function dialog box. Use the Category control to display Database functions.
 Select the DSUM function and click on the OK button.

 The Function Arguments dialog box will be displayed:


 Click on the Database section of the dialog box and then select cells A7:C12.
 Click on the Field section of the dialog box and enter “Sales”.
 Click on the Criteria section of the dialog box and then select cells B4:B5.

 Click on the OK button to see the results illustrated:


DMIN
 Open a workbook called Function DMIN. In this example, we will use the DMIN function to see what the lowest
sales figure of any of our sales people is.
 Click on cell D14.
 Click on the Formulas tab and from within the Function Library group click on the Insert Function button.

 This will display the Insert Function dialog box. Use the category control to display Database functions.
 Select the DMIN function and click on the OK button.
 The Function Arguments dialog box will be displayed:

 Click on the Database section of the dialog box and then select the cell range A7:C12.
 Click on the Field section of the dialog box and then click on cell C7.
 Click on the Criteria section of the dialog box and then select the cell range C8:C12.

 When you click on the OK button, you will see the result, as illustrated:
 Save your changes and close the workbook.

DMAX
 Open a workbook called Function DMAX. In this example, we will use the DMAX function to see what the
highest sales figure of any of our sales people is.
 Click on cell D14.
 Click on the Formulas tab and from within the Function Library group click on the Insert Function button.

 This will display the Insert Function dialog box. Use the category control to display Database functions.
 Select the DMAX function and click on the OK button.

 The Function Arguments dialog box will be displayed:


 Click on the Database section of the dialog box and then select the cell range A7:C12.
 Click on the Field section of the dialog box and then click on cell C7.
 Click on the Criteria section of the dialog box and then select the cell range C8:C12:

 When you click on the OK button, you will see the result, as illustrated:
 Save your changes and close the workbook.

DCOUNT
 Open a workbook called Function DCOUNT. In this example, we have a number of sales people, and their
target sales should be above 20. We wish to use the DCOUNT function to show the sales people who are
above target sales.
 Click on cell D14.
 Click on the Formulas tab and from within the Function Library group click on the Insert Function button.

 This will display the Insert Function dialog box. Use the category control to display Database functions.
 Select the DCOUNT function and click on the OK button.

 The Function Arguments dialog box will be displayed:


 Click within the Database section of the dialog box and then select cells A7:C12.
 Click within the Field section of the dialog box and then click on cell C7.
 Click within the Criteria section of the dialog box and then select cells B4:B5:
 Click on the OK button and the results will be as illustrated:

CHARTS
WATERFALL CHARTS
Excel Waterfall chart is used to show the cumulative effect of positive and negative amounts, based on a starting
value.

For example, you can project next year’s profit or cash flow starting with this year’s value, and showing the up and
down effects of changing costs, revenues, and other inputs. Waterfall charts are often called bridge charts, because
a waterfall chart shows a bridge connecting its endpoints. A simple waterfall chart is shown below:

700
600 -
100 - -
500 200 100 125
150 -
400 -
300 575
500
200
100
0
Initial First Second Third Fourth Fifth Final

Floating Column Chart Data and Calculations


The first approach most people try is to use a floating column chart, that is, a stacked column chart with the bottom
column in the stack hidden to make the others float. This range contains the calculations needed to make a floating
column waterfall chart. After the two columns of labels and values, as in the top right table, there are calculated
columns for the chart endpoints, the blank series that supports the floaters, and up and down values.

Data Crossing into Negative Territory

For data like the below, which has negative as well as positive values, the simple floating column chart approach
fails. The green and red bars are the correct length, and as long as they are located completely above the horizontal
axis, the chart is cool. But the formula computing the blank values is too simplistic, and Excel prohibits the floating
bars from floating across the axis.
Approach Using Up-Down Bars

There is another approach which takes a bit longer to chart, but the formulas are easier, and the columns in this case
are able to float anywhere, even across the axis. This approach is based on line charts and a line chart feature called
up-down bars. Up-down bars connect the first line chart value at a category to the last, like the open-close bars in a
stock chart. In fact, Excel uses up-down bars as open-close bars in its stock charts. The up bars and down bars can
be formatted individually. See above charts that address data crossing into negative territories.

TORNADO CHARTS
Tornado charts are often used to compare distributions, in the form of back-to-back histograms. Tornado charts are
particularly popular for comparing closely related populations, such as male and female age distributions.

Again, when building a model you always have to make major assumptions that drive the output. Obviously you
make your best directional estimate based upon available data. However, as you are finalizing the model the right
step is to assess the sensitivities of your output to your assumptions. One good way to show those model
sensitivities is in a tornado chart. First, select two series of data that show your max and min range for each
sensitivity variable, and put them in horizontal bar chart, like below.

CREATING A PIVOTTABLE
 Open a workbook called Pivot table. This contains the data from which you wish to create your pivot table:

 Click within the body of the data.


 Click on the Insert tab and from within the Tables group click on the PivotTable icon.
 You will see the Create PivotTable dialog box displayed.

 Click on the OK button to create your pivot table.


Dropping data into the Pivot Table
 Your screen will now look like this.

 You will see a PivotTable Field List (on the right of your screen) which helps you perform common tasks. As
you can see in the above illustration, the PivotTable Field List is launched automatically when you create your
Pivot Table. Let's put it to use.

 From within the PivotTable Field List, click on the Sales Person field.
 You should see it is displayed within the Row Labels section (bottom-right).

 From within the PivotTable Field List, click on the Customer field.

 You will see it displayed within the Row Labels section.


 Drag the Customer item into the part of the Pivot Table labelled “Column Labels”.

 From within the PivotTable Field List, click on the Total value field.

 You should see it displayed within the part of the Pivot Table labelled “Values”.
 When you have finished, the table should be as illustrated. As you can see, it is a very powerful way of
extracting and summarizing data:

Modifying data and refreshing the Pivot Table


 Following on from our previous example, you will notice that the Pivot Table was created on a new worksheet
(Sheet4), within your Excel worksheet.

 Click on the Pivot Table Data worksheet tab (Sheet 1), so that your original table of data is displayed.
 Make some changes, such as in this case change the value within cell D4, and change the value from 1 to 10:

 Click on the worksheet tab containing your Pivot Table (Sheet4), and you may notice that the Pivot Table has
not been updated to take account of your changed data:

 If necessary click on the PivotTable Tools tab in the ribbon which will display Pivot Table related items.

 From within the Data group of the ribbon, click on the Refresh icon and the table will update to take account of
your changed data.
 Your screen should now look like this.

 Save your changes but leave the workbook open.

Grouping data within a Pivot table


 Following on from the previous example, let's say that Gina and Rowan are working together as a team, and we
want to group their sales together.
 First, we need to click on cell A10 (the cell containing the text Gina).
 While depressing the Ctrl key we then need to click on cell A16 (the cell containing the text Rowan).
 When you release the Ctrl key, both items should remain selected.
 Right click over the selected cells and from the popup menu displayed select the Group command.

 The screen will then change to display the grouped results, as illustrated:
MACROS

RECORDING A MACRO
A macro is a stored sequence of actions which may be executed as a single action (and which may be executed
multiple times). A macro is also known as a subroutine. (I’ll use the terms interchangeably here.) Your VBA code will
be in the form of subroutines and functions.

Excel, like Word, allows you to record a series of actions as a macro. When you record a macro, Excel actually
produces VBA code to mimic your actions. Try this:

• Open Excel

• Click on menu item Tools, Macro, Record New Macro

• In the Record Macro box, type in the macro name, “Example1”. Click OK

• You should now see a small toolbar labeled “Stop” with two buttons.

• Click on cell B2

• Type “Hello Excel” and push your Enter key

• Highlight cell B2 again and change the font to bold by clicking the “B” button on the toolbar.

• Stop recording your macro by clicking the first button, with a small blue square, on the toolbar which
appeared when you started recording.

You’ve now written four lines of VBA code! To see it, go back to the menu and click on Tools, Macro, Visual Basic
Editor. (Keyboard shortcut Alt + F11).

In the Visual Basic editor, you will see a tree structure on the left representing your Excel workbook and its
associated code. The folder called “Microsoft Excel Objects” includes an item for each worksheet in your workbook,
as well as an item for the workbook itself. There is a second folder called “Modules” in which you should find an item
called Module1. Double-click on Module1 to display the code you recorded. It should look something like this:

Example 1.

Sub Example1()

'' Macro1 Macro

' Macro recorded 12/19/2003 by Mark “Shirley” Thorpe

Range("B2").Select

ActiveCell.FormulaR1C1 = "Hello Excel"

Range("B2").Select

Selection.Font.Bold = True
End Sub

Running a Macro

Next try running your macro. First clear cell B2, then click on Tools, Macro, Macros. Click on Macro1 and click the
Run button, or just double-click on the macro name.

Visual Basic Editor

As I mentioned earlier, the Visual Basic Editor is accessible by selecting menu item Tools, Macro, Visual Basic
Editor, or by using Alt + F11 on your keyboard. (Alt + F11 will also switch you back to Excel itself from the Editor.)
The Project Window, which appears on the left side of the screen holds a tree structure which shows up to three
“folders” for each Excel file currently open:

1. Microsoft Excel Objects: one object representing the workbook, one for each sheet in the workbook

2. Forms: user-defined forms contained in the spreadsheet (covered later)

3. Modules: collections of procedures and functions

Double-click on a module or worksheet to see the code associated with it. The code window will appear on the right.

Important Note!

You can usually figure out how to code any action in Excel by recording it in a macro and viewing the resulting macro
code.

USERFORMS
The Userform we are going to create looks as follows.
Controls

The most important Controls that can be added to an Excel VBA Userform are:

Labels

Examples of labels in our Userform are: 'Name:' , 'Phone Number:' , 'City Preference:' , 'Dinner Preference:' , etc.

Textboxes

The three boxes next to the Labels 'Name:' , 'Phone Number:' and 'Maximum to spend:' are textboxes.

Listboxes

The box next to the Label 'City Preference:' is a listbox.

Comboboxes

The dropdown-list next to the Label 'Dinner Preference:' is a combobox.

Note: a combobox is the same as a listbox except that the user can now also fill in his/her own choice if his/her
choice is not included in the list.

Checkboxes and Option buttons

'June 13th', 'June 20th' and 'June 27th' are examples of Checkboxes. 'Yes' and 'No' are examples of option buttons.

Note: Checkboxes and option buttons are primarily the same except that option buttons are dependent on each other
while checkboxes are not. This means that when you want to check one option button the other option button will
automatically uncheck.
Frames

The field with name 'Car' including the two option buttons is a Frame control.

Note: in order for option buttons to have the dependent functionality described earlier it is best to place the option
buttons in a Frame control.

Command buttons

The three command buttons at the bottom of the Userform are examples of command buttons.

Spin buttons

The spin button is placed next to the textbox at the bottom of the Userform.

Create the Userform

Now it is time to create the Userform!

1. Launch the Visual Basic Editor.

2. Click on ThisWorkbook from the Project Explorer. If the Project Explorer is not visible, click on View and then
Project Explorer.

3. From the Menu click on Insert and then Userform.

4. If the Toolbox does not appear automatically, click on View and then Toolbox.

5. Add all the controls. Once this has been completed, the result should be consistent with the picture of the
Userform shown earlier. For example, create a Label by clicking on Label from the Toolbox. Next, you can drag a
Label on the Userform. When you arrive at the CarFrame, remember to draw this Frame first before you place the
two option buttons in it.

6. Change the names and the captions of the controls. Right mouse click on each control. Then click on Properties.
Names are used in the Excel VBA code. Captions are those that appear on your screen. Change the names and
captions of the controls according to the table below.

Note: it is good practice to change the names of controls. This will make your code easier to read.

Show the Userform

To show the Userform, place a command button on your worksheet and add the following code line:

Private Sub CommandButton1_Click()

DinnerPlannerUserForm.Show

End Sub
UserForm_Initialize

The Sub UserForm_Initialize runs automatically whenever the Userform is loaded. Thus, when you use the Show
method for the Userform, the code will automatically be executed.

Private Sub UserForm_Initialize()

'Empty NameTextBox

NameTextBox.Value = ""

'Empty PhoneTextBox

PhoneTextBox.Value = ""

'Empty CityListBox

CityListBox.Clear

'Fill CityListBox

With CityListBox

.AddItem "San Fransisco"

.AddItem "Oakland"

.AddItem "Richmond"

End With

'Empty DinnerComboBox

DinnerComboBox.Clear

'Fill DinnerComboBox

With DinnerComboBox

.AddItem "Italian"

.AddItem "Chinese"

.AddItem "Frites and Meat"

End With
'Uncheck DataCheckBoxes

DateCheckBox1.Value = False

DateCheckBox2.Value = False

DateCheckBox3.Value = False

'Set no car as default

CarOptionButton2.Value = True

'Empty MoneyTextBox

MoneyTextBox.Value = ""

'Set Focus on NameTextBox

NameTextBox.SetFocus

End Sub

Result of the code: Fields are emptied, lists are populated and checkboxes are unchecked. CarOptionButton2 is set
as default, assuming that most of the people do not have a car. Finally, the last code line sets the focus on
NameTextbox as this is where we want to start when the Userform is loaded. To add this code to the Userform,
execute the following steps.

1. Launch the Visual Basic Editor.

2. Click on View and then Code from the Menu or right click on the Userform and then View Code.

3. The code window will appear showing you two drop-down lists. Choose Userform from the left drop-down list.
Choose Initialize from the right drop-down list.

4. Add the code.

Assign a macro to the Cancel button

To close the Excel VBA Userform when you click on the Cancel button, execute the following steps.

1. Launch the Visual Basic Editor.

2. Double click on DinnerPlannerUserForm from the Project Explorer.

3. Double click on the Cancel button.

4. Add the following code line:

Private Sub CancelButton_Click()


Unload Me

End Sub

Assign a macro to the Clear button

To call the Sub UserForm_Initialize when you click on the Clear button, execute the following steps.

1. Launch the Visual Basic Editor.

2. Double click on DinnerPlannerUserForm from the Project Explorer.

3. Double click on the Clear button.

4. Add the following code line:

Private Sub ClearButton_Click()

Call UserForm_Initialize

End Sub

Assign a macro to the OK button

After clicking on the OK button, the information from the Userform will be placed on your worksheet.

Private Sub OKButton_Click()

Dim emptyRow As Long

'Make Sheet1 Active

Sheets(1).Activate

'Determine emptyRow

emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Export Data to worksheet

Cells(emptyRow, 1).Value = NameTextBox.Value

Cells(emptyRow, 2).Value = PhoneTextBox.Value

Cells(emptyRow, 3).Value = CityListBox.Value


Cells(emptyRow, 4).Value = DinnerComboBox.Value

If DateCheckBox1.Value = True Then Cells(emptyRow, 5).Value = DateCheckBox1.Caption

If DateCheckBox2.Value = True Then Cells(emptyRow, 5).Value = Cells(emptyRow, 5).Value & " " &
DateCheckBox2.Caption

If DateCheckBox3.Value = True Then Cells(emptyRow, 5).Value = Cells(emptyRow, 5).Value & " " &
DateCheckBox3.Caption

If CarOptionButton1.Value = True Then

Cells(emptyRow, 6).Value = "Yes"

Else

Cells(emptyRow, 6).Value = "No"

End If

Cells(emptyRow, 7).Value = MoneyTextBox.Value

End Sub

Explanation of the code: First, we activate Sheet1. Next, we determine emptyRow. The information from the
Userform will be placed in this row. EmptyRow increases every time a record is added. Finally, we take the
information from the Userform to the specific columns of emptyRow. Double click on the OK button to add the code
just like we did with the Cancel and the Clear button.

Assign a macro to the Money Spin Button

By using the Money Spin Button the user can indicate how much he/she wants to spend. Execute the following steps
to program this:

1. Launch the Visual Basic Editor.

2. Double click on DinnerPlannerUserForm from the Project Explorer.

3. Double click on the Money Spin Button.

4. Add the following code line:

Private Sub MoneySpinButton_Change()

MoneyTextBox.Text = MoneySpinButton.Value

End Sub

Test the Userform

Exit the Visual Basic Editor, populate row 1, and test the Userform.

You might also like