Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics...

128
Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration

Transcript of Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics...

Page 1: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Excel Advanced

Ann Maes & Frederik Gailly

Department of Management information

Faculty of Economics and Business Administration

Page 2: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Information

Outline, Program, Downloads: http://allserv.ugent.be/~fgailly/ExcelAdvanced

Contact: Ann Maes ([email protected]) Frederik Gailly ([email protected])

Page 3: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Outline: Session 1

Pivot tables and graphs Data tables Scenario management Goal seek Solver Importing Financial data from the Web

Page 4: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Outline: Session 2

Macro’s Explore VBA-objects VBA selection and repetition VBA buttons and events VBA form elements

Page 5: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Pivot Tables

Transform large amounts of data from a table

or database into an organized summary

report

Ability to rotate and reorganize the

information via “drag-and drop”

Ability to filter and sort data as desired

Page 6: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Ex. Sales bookstore

Sales per category, per channel

and per year, per trimester?

Page 7: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Creating a Pivot Table

Data > Pivot Table and Pivot Chart Report Three simple steps:

Step 1: Data Location Where is the data to analyze? Pivot table or pivot chart?

Step 2: Data Source Select range of cells Select file using Browse

Step 3: Creating the Pivot Table Location Layout Options

Page 8: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 1: Data location The data is in a Microsoft Excel list We will create a Pivot Table

Page 9: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 2: Data Source

Page 10: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 3: Creating the Pivot table

Step 3 The location will be as a new worksheet Must now organize Layout

Page 11: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Layout

Field buttons

Page 12: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Terminology

Fields are categories of data (these may usually be row or

column headings in a table)

Row Fields show each value, or item, in the field as a row

Column Fields show each value as a column heading

Data Area is the main area of the table where comparative

values are shown

Grand Totals and Subtotals are sum calculations that

appear at the end of relative rows or columns

Page Field is a larger category which can group all of the

data in the table

Page 13: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Column and Row fields: define how data will be displayed in table

Page field: creates a filter for your table

Data field: what information do you want to summarize?

Pivot table template

Page 14: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

The resulting Pivot Table…

Page 15: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Pivot table Page Field

Operates like row and column fields but provides a third dimension to your data

Without necessarily viewing all its values at the same time (filter)

You can also choose to

display pivot table pages

on separate worksheets

Page 16: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Page Field

Page 17: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Exercise

Show sales per category and channel for 2002 and 2003 in separate pivot tables

Show sales per category and channel for each trimester of 2003 in separate pivot tables.

Page 18: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Modifying Pivot Table

Only selection of values of row/column/ page fields in pivot table Drop down list of variable

Change type of calculation (default Sum) field settings

More than one data-variable in pivot table

Grouping data Group and show detail > Group

Page 19: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Calculated Fields

Pivot Table Toolbar > Pivot Table > Formulas > Calculated Field to create a new field

Ex: Commission

Page 20: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Pivot Charts

Pivot Table Toolbar > Pivot Charts icon Chart is created from Pivot Table instead of initial

data table

Data > Pivot Table and Pivot Chart Report Step 1: Pivot Chart Pivot Chart created from data table

Pivot Chart has same filtering options as Pivot Table

Page 21: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Template Pivot Chart

Page 22: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Ex. Show sold units per channel and per year

! If you edit your PivotChart, changes will be made to Pivot Table and vice versa!!

Page 23: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

What-if analysis

“Allows you to change certain conditions in your worksheet to see how these changes affect the result of various spreadsheet calculations”

a One and Two-Input Data table Scenario Manager (scenario summary) Goal Seek Utilize Solver

Page 24: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Sensitivity Analysis: Data Table

To track how small changes in inputs affect the results of formulas in your model that are dependent on those inputs.

Two varieties:

one-variable data table

two-variable data table

Page 25: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

One-Way Data Table

List of values for input variable

One or more formula

Data Table Matrix with values

Page 26: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

One-Way Data Table

Enter references to formulas to compute across the top (or side)

Enter input data,

Select the cells comprising the table and use Data | Table…

Specify which input value

is varied

Page 27: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example

Calculate the monthly payment for a loan of 12400 EUR of 4 years when you consider a constant interest rate of 11%

What would the monthly payment be when the interest rate varies (10%; 10,5%; 11%; 11,5%; 12%;12,5%;13)

Page 28: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Result…

Page 29: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

What if…

Not only uncertainty about interest rate but also about amount to loan.

Calculate monthly payment for loan at different interest rates en for several amounts (10000, 11000, 12000, 13000, 14000)

Two-way data table

Page 30: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Two-Way Data Table

List of values for input variable

List of values for other input variable

Data Table Matrix with values

Formula or reference to formula

Page 31: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Two-Way Data Table

Enter reference to formula in top left-hand corner of table

Enter values for input data, in left column and top row

Select cells in table, and use Data | Table…

Specify which input values

are specified in the table

Page 32: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Two-way data table

Page 33: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Scenario management

To perform what-if analyses with more than two input variables use scenarios, which are: A set of values for multiple cells that Excel can put into a

worksheet Created based on existing spreadsheets in Excel

Use the Scenario Manager to set up and view different scenarios.

As you view each scenario, Excel uses the values in the scenario as input to calculate the results.

Page 34: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Ex. Scenario Management

Page 35: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Scenario Management: define several scenarios

Use Tools > Scenarios … menu optionAdd scenarios (with Add… button)

Page 36: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Adding additional Scenarios

Page 37: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

View and edit scenarios Scenarios defined you can view one by selecting the

name of the scenario you want to see in the Scenario Manager dialog box and click Show and then Close.

Excel will display the original spreadsheet, with the values from the scenario you chose.

You can edit your scenarios from the Scenario Manager Select the scenario you want to edit, and click Edit This will bring up a dialog box in which you can change

any of the input values You can then display the spreadsheet with the values from

the edited scenario

Page 38: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Scenario summary report

display a summary of the results from all of the scenarios you have created.

Page 39: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Scenario Summary Report

The Scenario Summary report shows you how your performance measure and your decision vary

for scenarios where multiple input variables are changing.

Page 40: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

What If vs If What

• Data Table and Scenario Analysis asked the question “WHAT IF …” ?

• We might also want to ask the question “IF … WHAT” ?• IF our profit is to be $100, WHAT must our sales be?

For this question, we can use Goal Seeking

• IF our profit is to be maximized, WHAT must be done?For this question, which is more complex, we can use Solver

Page 41: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Goal seeking

Use this when you want to find a specific result for a cell by adjusting the value of one other input cell.

Use Tools > Goal Seek…

Under Tools > Options… > Calculations you can change the maximum iterations, the precision, etc.

At the end you can either ignore or accept the solution Excel suggests.

Page 42: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example Car Payment

Page 43: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Tools > Goal Seek

Output cell address

Target level sought

Input to vary

If the monthly payment may not exceed 200 what should the duration of the loan be….

Page 44: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Result…

Page 45: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Optimization Analysis: Solver

Finds set of decision variables that achieves best possible value of an output

Answers questions such as: How should we allocate our budget to maximize profit? How much inventory should we stock of each type of

product, given constraints on shelf size and budget?

Page 46: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Excel Solver to solve a mathematical model which has been

entered into an Excel spreadsheet

This mathematical model can be either Linear Programming problem = there is a linear

relationship among all constraints and the objective

function

Integer Programming problem = decision variables

can only take integer values in a given range (these

integer values can also be boolean = 0 or 1 only)

Page 47: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

The Mathematical Model Decision Variables = variables assigned to a quantity

or response that must be determined in the problem Objective Function = equation which states the goal

of the model Maximize Minimize

Constraints = equations which state limitations of the problem

To solve the model, each constraint must be considered simultaneously in conjunction with the objective function

Page 48: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Tools > Solver

Page 49: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

The Solver Steps

Step 1: Read and Interpret the Problem Step 1.1: determine the decision variables Step 1.2: state the objective function Step 1.3: state any constraints

Step 2: Prepare the Spreadsheet Step 2.1: Enter the decision variables Step 2.2: Enter the constraints Step 2. 3: Enter the objective function

Step 3: Solve the model with the Solver Step 3.1: Set the Target Cell and choose Min or Max Step 3.2: Select Changing Cells Step 3.3: Add Constraints Step 3.4: Set Solver Options Step 3.5: Solve and review Results

Page 50: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Ex. Capital Budgeting

A company has six different opportunities to invest money. Each opportunity requires a certain investment over a period of 6 years or less. The Company wants to invest in those opportunities that maximize the combined Net Present Value (NPV). It also has an investment budget that has to be met for each year. In each year there is only a limited amount of money available. All amounts are give in millions of dollars. Interest rate is 5%.

Page 51: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 1: read and interpret the problem

Decision Variables Investment percentages in each opportunity

Objective Function Maximize combined NPV

Constraints Investment percentages < 1 Cash flows < investment budget (Year 1…6)

Page 52: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 2: Prepare the Spreadsheet The spreadsheet should have each part of the model clearly

entered

Page 53: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 3: solve the model

The Solver parameters can now be set according to the cell references with the appropriate model parts

Page 54: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Step 3 (continued)

Solver Options should also now be set

Page 55: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Results

Page 56: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Solver Reports

Answer Report = lists the target cell and the changing cells with their original and final values, constraints, and information about the constraints.

Sensitivity Report = shows how sensitive the solution is to small changes in the objective function formula or the constraints. For linear models, the report includes reduced costs, shadow prices, objective coefficient (with allowable increase and decrease), and constraint right-hand side ranges.

Limits Report = lists the target cell and the changing cells with their respective values, lower and upper limits, and target values. The lower limit is the smallest value that the changing cell can take while holding all other changing cells fixed and still satisfying the constraints. The upper limit is the greatest value.

Page 57: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Quick Review

Pivot tables and graphs

Data tables

Scenario management

Goal seek

Solver

Page 58: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Importing financial data from the web

Web queries can assist you in inserting refreshable data from the Web into your worksheets.

You can now navigate to any Web page while setting up a Web query, the same way as you would navigate to that page in your browser.

Once you are at the page, you can select one or more tables by clicking the icon images automatically added to the page by Excel.

Page 59: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Importing financial data from the web Data > Import External Data >New Web Query.

Page 60: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Basic steps Click the arrow next to the tables you want to import

( arrow checkmark)

Web queries are automatically saved with your workbook. If you want to save the query so that it can be run in other workbooks, click Save Query (.iqy extension.)

To set formatting and import options for how data is returned, click Options

Import Data

Choose location data

Page 61: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Result web query

Page 62: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Excel Advanced: Session 2

Visual Basic For Applications

Page 63: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Contents

1. Macro’s

2. Explore VBA-objects

3. VBA selection and repetition

4. VBA buttons and events

5. VBA form elements

Page 64: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

1.Macro’s

Page 65: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Macro’s

Visual Basic toolbar View – Toolbars – Visual Basic

Play Macro

Record Macro

Security Settings

Visual Basic Editor

Page 66: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Macro’s

Improve functionality Your first macro:

Open budget.xls Select D7:F8 Record Macro Name: CurrencyFormat Cell Properties

Valuta Decimals: 0

Stop record Macro

Name Macro

Page 67: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Run Macro’s

Select cells Run Macro Select CurrencyFormat Run

Page 68: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Edit Macro in VB Editor

Select run Macro Select Macro Edit

Page 69: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Macro’s in VB editor

Fixed syntax:Sub name_macro()

….

End Sub ‘ Remarks Between sub and end sub:

Body Macrocontains one or more statements

Page 70: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Sign your macro’s

!!! Vlerick computers only accept signed macro’s

How to sign your macro’s Create a signature Add your signature to the workbook

Page 71: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Create a signature

Programs > Microsoft Office Tools > Digital Certificate for VBA projects

Page 72: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Add your signature to the workbook

Microsoft VB EditorTools > Digital Signature

Page 73: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Exercise Macro

Create a macro that merges a selection of cells vertical aligns the text. Rotates the text 90°

Page 74: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Solution Macro

Sub VerticalMerge() ' ' VerticalMerge Macro ' Macro recorded 21/09/2004 by fgailly

With Selection .HorizontalAlignment = xlGeneral .VerticalAlignment = xlCenter .WrapText = False .Orientation = 90 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = True End WithEnd Sub

Page 75: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Simplify Solution

Sub VerticalMerge()'' VerticalMerge Macro' Macro recorded 21/09/2004 by fgailly' With Selection .VerticalAlignment = xlCenter .Orientation = 90 .MergeCells = True End WithEnd Sub

Page 76: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Methods in Macro’s

Until now:Record macro’s that change the properties of a selection

Next Step:Record methods in a macro.

Example: Macro to transpose formulas into values

Page 77: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Solution

Sub ConvertIntoValues()'' ConvertIntoValues Macro' Macro recorded 21/09/2004 by fgailly' Selection.Copy Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Application.CutCopyMode = FalseEnd Sub

Page 78: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Summary

2 kinds of statements: Statements that change properties:

With this you assign a new value to this property.Ex: Selection.VerticalAlignment = xlCenter

Methods:You don’t assign a new value. You are doing something. Methods can have argumentsEx: Selection.PasteSpecial _ Paste:=xlPasteValues, _

Operation:=xlNone, _

Page 79: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Execute Complex tasks with macro’s

Import File: Open file Wizard import text Move sheet to workbook Delete row

Page 80: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

ImportFile MacroSub ImportFile()

Workbooks.OpenText Filename:="C:\Excel VBA Oefenbestanden\Nov2002.txt", _ Origin:=xlMSDOS, StartRow:=4, DataType:=xlFixedWidth, FieldInfo:=Array( _ Array(0, 1), Array(8, 1), Array(20, 1), Array(27, 1), Array(41, 1), Array(49, 1)), _ TrailingMinusNumbers:=True ActiveWindow.WindowState = xlNormal With ActiveWindow .Top = -9.5 .Left = 3.25 End With Sheets("Nov2002").Select Sheets("Nov2002").Move Before:=Workbooks("hoofdstuk2.xls").Sheets(1) Rows("2:2").Select Selection.Delete Shift:=xlUpEnd Sub

Page 81: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Improve importfile macro

1. Users must be able to select the txt-file:Application.GetOpenFileName(“…, ….”)

2. Remove unnecessary statements

3. Macro’s must be used for all the months of the yearSheets(“nov2002”).Move ActiveSheet.Move

Page 82: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

1.Select File

myfile = Application.GetOpenFilename("txt-files,*.txt")

Workbooks.OpenText Filename:=myfile, _

Origin:=xlMSDOS, StartRow:=4, _ DataType:=xlFixedWidth, FieldInfo:=Array( _

Array(0, 1), Array(8, 1), Array(20, 1), _ Array(27, 1), Array(41, 1), Array(49, 1)), _

TrailingMinusNumbers:=True

Page 83: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

2. Remove unnecessary statements

Sub ImportFile()

myfile = Application.GetOpenFilename("txt-files,*.txt") Workbooks.OpenText Filename:=myfile, _ Origin:=xlMSDOS, StartRow:=4, DataType:=xlFixedWidth, FieldInfo:=Array( _ Array(0, 1), Array(8, 1), Array(20, 1), Array(27, 1), Array(41, 1), Array(49, 1)), _ TrailingMinusNumbers:=True ActiveWindow.WindowState = xlNormal With ActiveWindow .Top = -9.5 .Left = 3.25 End With Sheets("Nov2002").Select Sheets("Nov2002").Move Before:=Workbooks("hoofdstuk2.xls").Sheets(1) Rows("2:2").Select Selection.Delete Shift:=xlUpEnd Sub

Page 84: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

3.all the months of the year

Sub ImportFile()

myfile = Application.GetOpenFilename("txt-files,*.txt") Workbooks.OpenText Filename:=myfile, _ Origin:=xlMSDOS, StartRow:=4, DataType:=xlFixedWidth,

_ FieldInfo:=Array( _ Array(0, 1), Array(8, 1), Array(20, 1), Array(27, 1), _

Array(41, 1), Array(49, 1)), _ TrailingMinusNumbers:=True ActiveSheet.Move _

Before:=Workbooks("hoofdstuk2.xls").Sheets(1) Rows("2:2").Select Selection.Delete Shift:=xlUp

End Sub

Page 85: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Further exercises

Add the missing labels Add column with dates Add month to database Remove worksheet

You can try this at home and send your solution to [email protected]

Page 86: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Explore VBA-objects

Workbooks, Worksheets, Range, Cells

Page 87: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Objects in excel

Objects exists in collections Workbook object Workbook budget.xls instance of an object

Objects have properties Author: property of a workbook Height: property of a cell Name: property of a worksheet

Objects have methods Collection of objects have methods

Page 88: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Immediate Window

We will use the immediate window to explore the VBA objects.

View > immediate window

Page 89: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Workbooks

Add a workbook to the collection Workbooks.add

Count workbooks Workbooks.count

Close all workbooks Workbooks.close

Refer to a workbook Workbooks.Item(1) Workbooks(“Book1”)

Name of a workbook Workbooks.Item(1).name

Close a workbook Workbooks.Item(1).close ActiveWorkBook.close

Activate Workbook Workbooks(“Map14”).activate

Page 90: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Worksheets

Add a worksheet to the collection Worksheets.add.name = “Nieuw blad”

Delete a worksheet Worksheets.Item(1).delete

Rename worksheet Worksheets(1).name = “Test”

Activate worksheet Worksheet(“Test”).activate

Copy worksheets Worksheets(“Test”).Copy Worksheets(“Test”).Copy Before:=Worksheet(1)

Select worksheets One: Worksheets(2).select More than One: Worksheets(Array(1,3,4)).select

Page 91: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Range Point to a range with an address

Range("AA190").Select Range("A12:B34").Select

Special Range Object Cells Cells.Select Cells.Item(5).select Cells.Item(4,2).select

Special Range Object Colums / Rows Columns(3).Select Columns("D").Select Rows("3:14").select

Page 92: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

CurrentRegion, EntireColums, EntireRow

Point to a region based on the current selection ActiveCell.Currentregion.Select ActiveCell.EntireColumn.Select Selection.EntireRow.Select

Page 93: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

OffSet(m,n)

ActiveCell.offset(1,0).Select Go one row down

ActiveCell.Offset(2,2).Select Go two rows down Go two columns to the right

ActiveCell.Offset(-1,-1).Select Go one row up Go one column to the left

Page 94: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Add a value to range-object

Selection.value = 100 ActiveCell.Offset(-1).value = 0

Selection.Formula = 100 ActiveCell.Offset(-1).Formula = 100

Page 95: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

R1C1 A1 notation

A1 notation A: column 1: row

R1C1 notation R1: row 1 C1: column 1 More possibilities:

R[-2]C same columns, 2 rows higher R[1]C5column 5, 1 row lower

Page 96: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Add a formula to range

Activecell.Formula = "=A1 * B2“

Activecell.FormulaR1C1= "=R[-2]C - R[-1]C"

Page 97: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

VBA

Selection and repetition

Page 98: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Conditional Statements

If …….. Then….

Elseif …. Then….

Else

….

End if

Page 99: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 1

Sub GoLeft()ActiveCell.Offset(0, -1).Select

End Sub

!!! In cell A1: Error Resolution:

Sub GoLeft()If ActiveCell.Column <> 1 Then

ActiveCell.Offset(0, -1).SelectEnd IfEnd Sub

Page 100: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 2

Sub GoRight()If ActiveCell.Column < 5 Then

ActiveCell.Offset(0, 1).SelectElse

Cells(ActiveCell.Row + 1, 1).SelectEnd If

End Sub

Page 101: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Message Boxes

2 types: MsgBox “Text” simple messages MsgBox(“text”, Buttons, “Title”)

User has to respond (ex. Press YES)

Examples: Msgbox “Proceed with the macro” Msgbox(“Proceed with the Macro”, vbYesNo,

“Proceed”)

Page 102: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

InputBox

User has to respond by typing a text and pressing OK

Example:answer = InPutBox(“Give the month”)

Page 103: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 3

Sub TestInput()Dim myDate As StringmyDate = InputBox("Give the Date (mmm-jjjj)")If myDate <> "" Then

If IsDate(myDate) Then MsgBox "Continue Macro" Else MsgBox "Invalid Date" End If

End IfEnd Sub

Page 104: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 3 bisSub TestInput()

Dim myDate As StringmyDate = InputBox("Give the Date (mmm-jjjj)")If myDate <> "" Then

If IsDate(myDate) Then answer = MsgBox(“Continue?”, vbYesNo)

If answer = vbNo ThenExit Sub

End If Else MsgBox "Invalid Date" End If

End IfEnd Sub

Page 105: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Loops: For Each

For eachUsed to walk through a collection of objects

For Each In …….

Next

Page 106: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 1

Sub ProtectSheets()

Dim mySheet as WorksheetFor Each mySheet in Worksheets

mySheet.Select

mySheet. Protect “Password”, _

True, True, True

Next mySheet

End Sub

Page 107: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 2

Sub unprotectSheets()

Dim mySheet As Worksheet

For Each mySheet In Worksheets

mySheet.Select

mySheet.Unprotect "Password"

Next mySheet

End Sub

Page 108: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Loops: For

For-loopUsed to execute statements for a couple of times by using a counter

For i = 0 to n….

Next i

Page 109: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example

Sub ProtectSheets()

For i = 1 To Worksheets.Count

Worksheets(i).Protect "Password", _True, True, True

Next i

End Sub

Page 110: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Loops: Do Until / Do While

Do Until [condition]…

Loop

Do While [condition]….

Loop

Page 111: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 1Sub FilesEnhanced()

Dim myRow As IntegerDim myFile As String

myRow = 1myFile = Dir("C:\Documents and _

Settings\fregai\Bureaublad\*.doc")Do Until myFile = ""

Cells(myRow, 1) = myFile myRow = myRow + 1 myFile = Dir

LoopEnd Sub

Page 112: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

VBA

buttons and events

Page 113: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Using buttons in excel

Toolbars / control toolbox

Select Button Draw Button Every toolbox element

has properties: Name Caption

Page 114: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Using buttons in excel (2)

Attach macro to button: Create macro with special name:

Sub NameButton_click()….

End Sub !!! Name Button is very important Use Meaningful names

Page 115: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 1

Sub ZoomIn_click()

Dim MyZoom As Integer

MyZoom = ActiveWindow.Zoom + 10

If MyZoom <= 400 Then

ActiveWindow.Zoom = MyZoom

End If

End Sub

Page 116: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Using buttons in excel (3)

To test a button exit design-mode

Click eventCode will be executed when the event happens

Other Events: MouseMove ….

Page 117: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Worksheet & WorkBook events

Select Object & Select Event

Events: Worksheets:

SelectionChange Activate Change Deactivate

WorkBook: Activate Open

Page 118: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example 1

Private Sub Worksheet_SelectionChange(ByVal _ Target As Range)

If ActiveCell.Interior.Color = vbCyan Then

Selection.Interior.Color = vbYellow

Else

Selection.Interior.Color = vbCyan

End If

End Sub

Page 119: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

VBA

form-elements

Page 120: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Example

Create a loan calculator:

Formula: =PMT(C5/12;C6*12;C4)

Amount 200.000,00 €

Rate 4,00%

Years 20

Term -1.211,96 €

Page 121: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Improved Calculator

Limit number of years

Limit possible rates

Limit loan amounts

Protect Worksheet

Page 122: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Limit number of years

Control Toolbox > Spin Button Properties:

Max: 30 Min: 5 Linked Cell C6

Page 123: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Limit possible rates

Control Toolbox > Scroll Bar Properties:

Max: 2000 SmallChange: 25 LargeChange: 200 LinkedCell: H5

Formula C5: = H5/10000

Page 124: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Limit Loan amounts

Use a listbox First Create a list with possible values on an other

worksheet: Select List Give a RangeName AutoList

91 Mercury Sable 7500

88 Nissan Pulsar NX 3350

90 Toyato Camry 5950

88 Dodge Lancer ES 3299

87 BMW 325 4959

Page 125: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Limit Loan amounts (2)

Control Toolbox > List Box Properties:

LinkedCell: C2 ListFillRange: AutoList ColomnCount: 2 BoundColumn

Page 126: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Protect WorkSheet Create eventhandlers for Elements

1. List Box– Properties:

Name: lstAmount LinkedCell : “”

– Sub lstAmount_Change()Range(“C4”).Value = lstAmount.Value

End Sub2. Scroll Bar

– Properties Name: scrRate LinkedCell: “”

– Private Sub scrRate_Change()Range("C5").Value = scrRate.Value /

10000End Sub

3. ….

Page 127: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

Protect Worksheet (2)

VBA editor: In ThisWorkBook Sub Workbook_Open()

WorkSheets(“Lening”).Protect _UserInterfaceOnly:= True

End Sub

Page 128: Excel Advanced Ann Maes & Frederik Gailly Department of Management information Faculty of Economics and Business Administration.

The End

Thank You for your Attention