50
Spreadsheets in Finance and Forecasting Presentation 10 Visual Basic

Spreadsheets in Finance and Forecasting

Embed Size (px)

DESCRIPTION

Spreadsheets in Finance and Forecasting. Presentation 10 Visual Basic. Objectives. After studying this week’s work you will be able to: Use the Visual Basic Editor to examine and interpret VB Code Modify Macros in order to extend their role - PowerPoint PPT Presentation

Citation preview

Page 1: Spreadsheets in Finance and Forecasting

Spreadsheets in Finance and Forecasting

Presentation 10Visual Basic

Page 2: Spreadsheets in Finance and Forecasting

Objectives After studying this week’s work you will

be able to: Use the Visual Basic Editor to examine and

interpret VB Code Modify Macros in order to extend their role Communicate with the user via input and

message boxes Allow the user to choose courses of actions

Page 3: Spreadsheets in Finance and Forecasting

Introduction

Page 4: Spreadsheets in Finance and Forecasting

VB Examples We will use a spreadsheet to examine the process

of creating Visual Basic code via a macro. The example is a simple situation where we have

new data to be used to update a total.

Today's Sales Total so far this month:

Fruit and Veg £135.56 Fruit and Veg £5,082.95Baked Goods £476.89 Baked Goods £7,890.66Groceries £1,249.98 Groceries £23,911.85Stationery £56.76 Stationery £1,688.92Miscellaneous £198.06 Miscellaneous £4,511.61

Page 5: Spreadsheets in Finance and Forecasting

VB Examples One way of doing this is to incorporate the

calculation into the spreadsheet formulae. Another way is to write a macro which does this

(and undoes it) at the press of a button.

Today's Sales Total so far this month:

Fruit and Veg £135.56 Fruit and Veg £5,082.95Baked Goods £476.89 Baked Goods £7,890.66Groceries £1,249.98 Groceries £23,911.85Stationery £56.76 Stationery £1,688.92Miscellaneous £198.06 Miscellaneous £4,511.61

Page 6: Spreadsheets in Finance and Forecasting

What you should know Before you start this

work, you should have configured Excel with the VB toolbar.

You also need to remember the methods introduced last week.

Page 7: Spreadsheets in Finance and Forecasting

Section 1

UnderstandingVB Code

Page 8: Spreadsheets in Finance and Forecasting

VB Examples Open the VB Examples Spreadsheet, and

carry out the task described there

Action Point

Page 9: Spreadsheets in Finance and Forecasting

Excel Macros Excel Macros are recorded as

routines in Visual Basic (VB) Code When we “run” macros, what we are

doing is running short Visual Basic programs.

During the rest of this presentation we will be working with this VB Code.

Page 10: Spreadsheets in Finance and Forecasting

The Visual Basic Editor

Click on: Tools – Macro- Visual Basic Editor

The Folders The Visual Basic Code

Action Point

Page 11: Spreadsheets in Finance and Forecasting

Visual Basic Code -FeaturesTitle of the macro Comments are

prefaced with a single quote mark, and appear in green

End of macro

Visual Basic Commands

Page 12: Spreadsheets in Finance and Forecasting

Understanding the Code VB code is highly complex and would take you a long

time to learn to write. However if you know what the code is doing, you can

work out what each part does.

2. Write =J4+E4 in cell L4

3. Autofill L4:L8

4. Copy L4:L8

6. Delete L4:L8

5. Paste L4:L8 over to J4:J8

Page 13: Spreadsheets in Finance and Forecasting

Understanding the Code We will now examine the code apart bit-by bit. Click the buttons to see what each section does

J4 + L4

Autofill

Copy

Paste

Delete

Next Slide

Page 14: Spreadsheets in Finance and Forecasting

Write “=J4+E4” in cell L4 This code comprises two lines:

Range("L4").Select

ActiveCell.FormulaR1C1 = "=RC[-2]+RC[-7]"

The first line is simply a command to select cell L4, which then becomes the active cell.

Page 15: Spreadsheets in Finance and Forecasting

Write “=J4+L4” in cell L4

Range("L4").Select

ActiveCell.FormulaR1C1 = "=RC[-2]+RC[-7]"

The second line puts a formula in this active cell.

This cell is now regarded (for the moment) as Row 1 Column 1

In the formula, RC[-2] means “same Row”, but 2 Columns to the left

Return

Page 16: Spreadsheets in Finance and Forecasting

Autofill L4:L8 This takes two lines:

Range("L4").Select

Selection.AutoFill Destination:=Range("L4:L8"), Type:=xlFillDefault

The first line simply selects cell L4 The second line (all three parts of it!)

auto fills it down to L8 Return

Page 17: Spreadsheets in Finance and Forecasting

Copy cells L4:L8 This takes two lines:

Range("L4:L8").Select

Selection.Copy

The first line selects the range of cells from L4 to L8

The second line is an instruction to copy this selection.

Return

Page 18: Spreadsheets in Finance and Forecasting

Paste J4:J8 over to L4:L8 This takes two lines:

Range("J4:J8").Select

Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _

False, Transpose:=False

The first line selects J4:J8, the range of cells to be copied.

Page 19: Spreadsheets in Finance and Forecasting

Paste J4:J8 over to L4:L8

Range("J4:J8").Select

Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _

False, Transpose:=False

The second line is the Paste Special option, which pastes values only.

Note that lots of other things are included in this that you might not have been aware of. Return

Page 20: Spreadsheets in Finance and Forecasting

Delete L4:L8 This takes three lines of code

Range("L4:L8").Select Application.CutCopyMode = FalseSelection.ClearContents

The first line selects cells L4 to L8 The second line establishes that we

are not going to cut or copy the cells. The third line clears the contents.

Return

Page 21: Spreadsheets in Finance and Forecasting

Working in Visual Basic As you can see, VB is not

a simple language, and not something that you can immediately use.

However, the usual way that people work is to record macros and use the code as a basis for what they want to do.

Page 22: Spreadsheets in Finance and Forecasting

Section 2

Modifying VB Code

Page 23: Spreadsheets in Finance and Forecasting

Your first Original Macro! Return to Sheet 1 of the VB Examples

spreadsheet. You are going to write a macro which

will subtract “Today’s Sales” from the “Total so far this month”.

Today's Sales Total so far this month:

Fruit and Veg £135.56 Fruit and Veg £5,218.51Baked Goods £476.89 Baked Goods £8,367.55Groceries £1,249.98 Groceries £25,161.83Stationery £56.76 Stationery £1,745.68Miscellaneous £198.06 Miscellaneous £4,709.67

Page 24: Spreadsheets in Finance and Forecasting

Step 1: Copy and Rename Switch to VB Editor mode, and copy the entire

“increaseTotal” macro

Underneath the original, paste a second version, but change the title to “decreaseTotal”

Action Point

Page 25: Spreadsheets in Finance and Forecasting

Your first Original Macro!

Today's Sales

Fruit and Veg £135.56Baked Goods £476.89Groceries £1,249.98Stationery £56.76Miscellaneous £198.06

Now examine the macro

You only need to change one symbol on one line

That is the line which puts the formula into cell L4

ActiveCell.FormulaR1C1 = "=RC[-2]+RC[-7]"

Page 26: Spreadsheets in Finance and Forecasting

Your first Original Macro!

Today's Sales

Fruit and Veg £135.56Baked Goods £476.89Groceries £1,249.98Stationery £56.76Miscellaneous £198.06

Make the change to the macro and assign it to the second button on the sheet. Check that it works.

The line should read:

ActiveCell.FormulaR1C1 = "=RC[-2]- RC[-7]"

Instead of writing “=J4+L4”,

we need to have this say “=J4-E4”

Page 27: Spreadsheets in Finance and Forecasting

Section 3

Communicating with the User

Page 28: Spreadsheets in Finance and Forecasting

Amending Macros It is often useful to

send a message to the user to say that a macro has been completed.

There is a simple piece of coding which allows you to do this

Page 29: Spreadsheets in Finance and Forecasting

Adding a Message Box In the increaseTotal

macro, just before the End Sub line, add the following:

MsgBox “Task completed”

Action Point

Page 30: Spreadsheets in Finance and Forecasting

Adding a Message BoxThe line: MsgBox “Task completed”

Generates this box The user needs to press

the button to continue. The message box is a

useful way to communicate with a user

Page 31: Spreadsheets in Finance and Forecasting

Disabling the Message Box Add a single quotation mark,

and change the line to: ‘ MsgBox “Task completed” Now click off the line; note

that this turns the text green. If you now run the macro, the

message box will not appear. This is because VB treats the

line as a comment, not as a piece of code. Action

Point

Page 32: Spreadsheets in Finance and Forecasting

Section 4

Giving the user Choice

Page 33: Spreadsheets in Finance and Forecasting

Giving the User Choice We will now write a

completely new macro which will allow the user to choose whether to increase or decrease the “total so far”

In doing this you will see how macros can be developed.

Page 34: Spreadsheets in Finance and Forecasting

Recording a New Macro

Record a macro called makeSelection

This macro will consist of two button presses: Increase Total Decrease Total

Increase Total

Decrease Total

Make Selection

Action Point

Page 35: Spreadsheets in Finance and Forecasting

The New Macro

Sub makeSelection()'' makeSelection Macro' Macro recorded 20/03/2002 by User

Application.Run "'VBExamples.xls'!increaseTotal"Application.Run "'VBExamples.xls'!decreaseTotal"End Sub

The macro simply consists of a title, an end, some comments in green, and two lines of code.

Increase Total button

Decrease Total button

Page 36: Spreadsheets in Finance and Forecasting

Adding an Input Box

Choice = InputBox(“increase or decrease?”)

Application.Run "'VBExamples.xls'!increaseTotal"Application.Run "'VB Examples.xls'!decreaseTotal"

After the green comments, but before the lines of VB code, insert the following:

This will put an input box on the screen which will ask the user for a reply.

Action Point

Page 37: Spreadsheets in Finance and Forecasting

Adding choice

Choice = InputBox(“increase or decrease?”)If choice = “inc” ThenApplication.Run "'VBExamples.xls'!increaseTotal"End IfIf choice = “dec” Then Application.Run "'VBExamples.xls'!decreaseTotal“End If

We will assume that the user will type in either “inc” or “dec”

We now add lines which will allow the user to choose which action is carried out.

1

2

Action Point

Page 38: Spreadsheets in Finance and Forecasting

Assigning the Macro

Increase Total

Decrease Total

Make Selection

Assign the Macro to the third button on the VB Examples Sheet.

Run the macro. When the input

box appears, type in either inc or dec

Action Point

Page 39: Spreadsheets in Finance and Forecasting

Finishingthe Macro The macro carries

out the task, but does not tell you that it has done it.

Add code to the macro so that the correct one of these message boxes appears

Action Point

Page 40: Spreadsheets in Finance and Forecasting

makeSelection MacroSub makeSelection()'' makeSelection Macro' Macro recorded 20/03/2002 by User' choice = InputBox("Do you want to Increase or Decrease?") If choice = "inc" Then Application.Run "'VBExamples.xls'!increaseTotal" MsgBox "Total Increased" End If If choice = "dec" Then Application.Run "'VBExamples.xls'!decreaseTotal" MsgBox "Total Decreased" End IfEnd Sub The best place to put the message

boxes is inside the “IF” commands

Page 41: Spreadsheets in Finance and Forecasting

What have we learned? The macro we have just

written is not all that useful, since we could just have pressed the buttons.

However, suppose that we wanted to update one item selectively.

With the commands, we could do this.

Page 42: Spreadsheets in Finance and Forecasting

Section 5

Using Selections

Page 43: Spreadsheets in Finance and Forecasting

Selective Updating of Items

Today's Sales

1 Fruit and Veg £135.562 Baked Goods £476.893 Groceries £1,249.984 Stationery £56.765 Miscellaneous £198.06

Firstly, add numbers 1-5 to each of the type of item

This will allow us to use a number rather than the name

Action Point

Page 44: Spreadsheets in Finance and Forecasting

Recording the initial macro Record a new

macro called selectItem.

This should: Put the formula

=L4+E4 in cell L4 Copy L4 and Paste

Values into K4 Delete L4

Action Point

Page 45: Spreadsheets in Finance and Forecasting

Examine the initial macro Record a new

macro called selectItem.

This should: Put the formula

=L4+E4 in cell L4 Copy L4 and Paste

Values into K4 Delete L4

Sub selectItem()'' selectItem Macro' Macro recorded 28/03/2004 by User'Range("L4").SelectActiveCell.FormulaR1C1 = "=RC[-2]+RC[-7]"Range("L4").SelectSelection.CopyRange("J4").SelectSelection.PasteSpecial Paste:=xlValuesOperation:=xlNone, SkipBlanks:= _ False, Transpose:=False Range("L4").Select Application.CutCopyMode = False Selection.ClearContentsEnd Sub

Action Point

Page 46: Spreadsheets in Finance and Forecasting

Adding New Lines (1) At the beginning of

the macro (after the comments) add these five lines of code:

The first (all one line) asks the user which line is to be updated.

These four lines identify which cells will be modified.

Item = InputBox("Which item do you wish to update: 1,2,3,4,or 5")

If Item = 1 Thencell1 = "L4"cell2 = "J4"End If

Action Point

Page 47: Spreadsheets in Finance and Forecasting

Adding New Lines (2) Now add these eight

lines:

These identify the cells which will be updated if the user selects item 2 or 3

Now add the other eight lines needed if the user wants to update items 4 or 5

If Item = 2 Thencell1 = "L5"cell2 = "J5"End If

If Item = 3 Thencell1 = "L6"cell2 = "J6"End If

Action Point

Page 48: Spreadsheets in Finance and Forecasting

Modifying the code Modify the code

underneath as follows: Wherever “L4”

occurs, replace it with cell1

Wherever “J4” occurs, replace it with cell2

Range(cell1).Select ActiveCell.FormulaR1C1 = "=RC[-

2]+RC[-7]" Range(cell1).Select Selection.Copy Range(cell2).Select Selection.PasteSpecial

Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _

False, Transpose:=False Range(cell1).Select Application.CutCopyMode =

False Selection.ClearContents

Action Point

Page 49: Spreadsheets in Finance and Forecasting

Finishing off Finally, add a line just

before the end:MsgBox “Item " & Item &

" updated“

This will add a message box to say which item has been updated.

Now, reassign the “Make Selection” button to the selectLine macro and test it out.

Action Point

Page 50: Spreadsheets in Finance and Forecasting

What Next? There are two separate

Activity Sheets which follow up this work: Formative Activity 8

creates macros which draw charts for selected lines of data

Summative Activity C explores how to update and interrogate a database