1 / 128

# Excel Advanced - PowerPoint PPT Presentation

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

Ann Maes & Frederik Gailly

Department of Management information

• Pivot tables and graphs

• Data tables

• Scenario management

• Goal seek

• Solver

• Importing Financial data from the Web

• Macro’s

• Explore VBA-objects

• VBA selection and repetition

• VBA buttons and events

• VBA form elements

• 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

Sales per category, per channel

and per year, per trimester?

• 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

• The data is in a Microsoft Excel list

• We will create a Pivot Table

• Step 3

• The location will be as a new worksheet

• Must now organize Layout

Field buttons

• 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 field: creates a filter for your table

Data field: what information do you want to summarize?

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

• 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

• 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.

• 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

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

• Ex: Commission

• 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

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

“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

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

One or more formula

List of values for input variable

Data Table Matrix with values

• 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

• 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)

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

List of values for other input variable

Formula or reference to formula

List of values for input variable

Data Table Matrix with values

• 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

• 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.

• 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

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

The Scenario Summary report shows you how your performance measure and your decision varyfor scenarios where multiple input variables are changing.

• 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

• 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.

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

Target level sought

Input to vary

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

• 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?

• 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 objectivefunction

• Integer Programming problem = decisionvariables can only take integer values in a given range (these integer values can also be boolean = 0 or 1 only)

• 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 objectivefunction

• 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.4: Set SolverOptions

• Step 3.5: Solve and review Results

• 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%.

• Decision Variables

• Investment percentages in each opportunity

• Objective Function

• Maximize combined NPV

• Constraints

• Investment percentages < 1

• Cash flows < investment budget (Year 1…6)

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

Step 3: solve the model

Step 3 (continued) entered

• SolverOptions should also now be set

Results entered

Solver Reports entered

• 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.

Quick Review entered

• Pivot tables and graphs

• Data tables

• Scenario management

• Goal seek

• Solver

• 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.

Data entered > Import External Data >New Web Query.

Importing financial data from the web

Basic steps entered

• 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

### Excel Advanced: Session 2 entered

Visual Basic For Applications

Contents entered

• Macro’s

• Explore VBA-objects

• VBA selection and repetition

• VBA buttons and events

• VBA form elements

### 1.Macro’s entered

Macro’s entered

• Visual Basic toolbar

• View – Toolbars – Visual Basic

Play Macro

Record Macro

Security Settings

Visual Basic Editor

Macro’s entered

• Improve functionality

• Yourfirst macro:

• Open budget.xls

• Select D7:F8

• Record Macro

• Name: CurrencyFormat

• Cell Properties

• Valuta

• Decimals: 0

• Stop record Macro

Name Macro

Run Macro’s entered

• Select cells

• Run Macro

• Select CurrencyFormat

• Run

Edit Macro in VB Editor entered

• Select run Macro

• Select Macro

• Edit

Macro’s in VB enterededitor

• Fixed syntax:

Sub name_macro()

….

End Sub

• ‘  Remarks

• Between sub and end sub:Body Macrocontains one or more statements

• !!! Vlerick computers only accept signed macro’s

• How to sign your macro’s

• Create a signature

Create a signature entered

• Programs > Microsoft Office Tools > Digital Certificate for VBA projects

• Microsoft VB EditorTools > Digital Signature

Exercise entered Macro

• Create a macro that

• merges a selection of cells

• vertical aligns the text.

• Rotates the text 90°

Solution Macro entered

Sub VerticalMerge()

'

' VerticalMerge Macro

' Macro recorded 21/09/2004 by fgailly

With Selection

.HorizontalAlignment = xlGeneral

.VerticalAlignment = xlCenter

.WrapText = False

.Orientation = 90

.IndentLevel = 0

.ShrinkToFit = False

.MergeCells = True

End With

End Sub

Simplify Solution entered

Sub VerticalMerge()

'

' VerticalMerge Macro

' Macro recorded 21/09/2004 by fgailly

'

With Selection

.VerticalAlignment = xlCenter

.Orientation = 90

.MergeCells = True

End With

End Sub

Methods in Macro’s entered

• 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

Solution entered

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 = False

End Sub

Summary entered

• 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, _

• Import File:

• Open file

• Wizard import text

• Move sheet to workbook

• Delete row

ImportFile Macro entered

Sub 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:=xlUp

End Sub

Improve importfile macro entered

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

• Remove unnecessary statements

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

1.Select File entered

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

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:=xlUp

End Sub

3.all the months of the year entered

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

Further exercises entered

• Remove worksheet

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

### Explore VBA-objects entered

Workbooks, Worksheets, Range, Cells

Objects in excel entered

• 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

Immediate Window entered

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

• View > immediate window

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

Workbooks

Worksheets entered

• Add a worksheet to the collection

• 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

Range entered

• 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

• Point to a region based on the current selection

• ActiveCell.Currentregion.Select

• ActiveCell.EntireColumn.Select

• Selection.EntireRow.Select

OffSet(m,n) entered

• 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

Add a value to range-object entered

• Selection.value = 100

• ActiveCell.Offset(-1).value = 0

• Selection.Formula = 100

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

R1C1 entered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]C5column 5, 1 row lower

Add a formula to range entered

• Activecell.Formula = "=A1 * B2“

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

### VBA entered

Selection and repetition

Conditional Statements entered

If …….. Then ….Elseif …. Then ….Else

….

End if

Example 1 entered

• Sub GoLeft() ActiveCell.Offset(0, -1).SelectEnd Sub

• !!! In cell A1: Error

• Resolution:Sub GoLeft()If ActiveCell.Column <> 1 Then ActiveCell.Offset(0, -1).SelectEnd IfEnd Sub

Example entered 2

Sub GoRight() If ActiveCell.Column < 5 Then ActiveCell.Offset(0, 1).Select Else Cells(ActiveCell.Row + 1, 1).Select End IfEnd Sub

Message Boxes entered

• 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”)

InputBox entered

• User has to respond by typing a text and pressing OK

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

Example 3 entered

Sub TestInput()

Dim myDate As String

myDate = InputBox("Give the Date (mmm-jjjj)")

If myDate <> "" Then

If IsDate(myDate) Then

MsgBox "Continue Macro"

Else

MsgBox "Invalid Date"

End If

End If

End Sub

Example 3 bis entered

Sub TestInput()

Dim myDate As String

myDate = InputBox("Give the Date (mmm-jjjj)")

If myDate <> "" Then

If IsDate(myDate) Then

Exit Sub

End If

Else

MsgBox "Invalid Date"

End If

End If

End Sub

Loops: For Each entered

• For eachUsed to walk through a collection of objects

• For Each In … ….Next

Example 1 entered

Sub ProtectSheets()

Dim mySheet as Worksheet For Each mySheet in Worksheets

mySheet.Select

True, True, True

Next mySheet

End Sub

Example 2 entered

Sub unprotectSheets()

Dim mySheet As Worksheet

For Each mySheet In Worksheets

mySheet.Select

Next mySheet

End Sub

Loops: For entered

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

• For i = 0 to n ….Next i

Example entered

Sub ProtectSheets()

For i = 1 To Worksheets.Count

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

Next i

End Sub

Loops: Do Until / Do While entered

• Do Until [condition] …Loop

• Do While [condition] ….Loop

Example 1 entered

Sub FilesEnhanced()

Dim myRow As Integer

Dim myFile As String

myRow = 1

myFile = Dir("C:\Documents and _ Settings\fregai\Bureaublad\*.doc")

Do Until myFile = ""

Cells(myRow, 1) = myFile

myRow = myRow + 1

myFile = Dir

Loop

End Sub

### VBA entered

buttons and events

Using buttons in excel entered

• Toolbars / control toolbox

• Select Button

• Draw Button

• Every toolbox element has properties:

• Name

• Caption

Using buttons in excel (2) entered

• Attach macro to button:

• Create macro with special name:Sub NameButton_click() ….End Sub

• !!! Name Button is very important

• Use Meaningful names

Example 1 entered

Sub ZoomIn_click()

Dim MyZoom As Integer

MyZoom = ActiveWindow.Zoom + 10

If MyZoom <= 400 Then

ActiveWindow.Zoom = MyZoom

End If

End Sub

Using buttons in excel (3) entered

• To test a button  exit design-mode

• Click  eventCode will be executed when the event happens

• Other Events:

• MouseMove

• ….

Worksheet & WorkBook events entered

• Select Object & Select Event

• Events:

• Worksheets:

• SelectionChange

• Activate

• Change

• Deactivate

• WorkBook:

• Activate

• Open

Example 1 entered

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

### VBA entered

form-elements

Example entered

• Create a loan calculator:

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

Improved Calculator entered

• Limit number of years

• Limit possible rates

• Limit loan amounts

• Protect Worksheet

Limit number of years entered

• Control Toolbox > Spin Button

• Properties:

• Max: 30

• Min: 5

Limit possible rates entered

• Control Toolbox > Scroll Bar

• Properties:

• Max: 2000

• SmallChange: 25

• LargeChange: 200

• Formula C5: = H5/10000

Limit Loan amounts entered

• Use a listbox

• First  Create a list with possible values on an other worksheet:

• Select List

• Give a RangeName  AutoList

Limit Loan amounts (2) entered

• Control Toolbox > List Box

• Properties:

• ListFillRange: AutoList

• ColomnCount: 2

• BoundColumn

Protect WorkSheet entered

• Create eventhandlers for Elements

• List Box

• Properties:

• Name: lstAmount

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

• Scroll Bar

• Properties

• Name: scrRate

• Private Sub scrRate_Change() Range("C5").Value = scrRate.Value / 10000End Sub

• ….

Protect Worksheet (2) entered

VBA editor: In ThisWorkBook

• Sub Workbook_Open() WorkSheets(“Lening”).Protect _ UserInterfaceOnly:= TrueEnd Sub

The End entered

Thank You