24
Week 1

Visual Basic for Applications in Microsoft Excel (1)sbbf565/Week01/Week01.pdf · Open week1.xls Highlight range ... You can return to Excel in various ways: click the View Microsoft

Embed Size (px)

Citation preview

Week 1

Kate Watson• E-mail: [email protected]

Checked at least every other day. Queries and

general comments welcome

Course notes and exercises: • http://www.staff.city.ac.uk/~sbbf565/

Mondays, 6.30-8.30, room L3A

Tuesdays, 6.30-8.30, room A3.08

* Recording and running macros * Assigning macros to menus, toolbars and buttons * The Visual Basic editor * Input boxes and Message boxes * Object-oriented concepts: objects, properties, methods and events * Excel objects * Variables and constants * If statements * Looping * Conversion functions * User-defined functions * User forms and dialog boxes * Error-handling and debugging * Workbook and Worksheet events

By the end of the course, you will be able to:

* Record and run macros * Use the Visual Basic environment to edit programs * Write Visual Basic code, using variables, loops and if statements * Understand Excel VBA functions and write their own functions * Understand and apply object-oriented concepts * Be acquainted with the most important Excel VBA objects and properties * Understand events in Excel * Debug (i.e. correct) errors

There are many basic VBA textbooks, some of which are listed below it is best to purchase a book written for your version of Excel.

Excel VBA in easy steps, Ed Robinson, Computer Step, 2004. Very cheap and very clear for the basics

Microsoft Excel 200? Visual Basic for Applications Step by Step , Reed Jacobson, Microsoft Press,2001. A very accessible introduction which brings you a long way.

Microsoft Excel 2007 Power Programming with VBA, John Walkenbach - a little bit advanced, but you will have to buy it at some stage - probably for after the course

Financial Modelling, Simon Beninga, MIT Press - contains some computer programming, though not a programming book. Very good examples of setting up financial models

Ensure you bring your student card with you – you may be asked to present it and it can be used to register with the library

Computer Reception E211, Drysdale building, x3747 For login problems; printer/computer faults

The Workstation rooms are generally open between 8.30am and 8.30pm. Changing your password You can change your password from a web browser like Internet Explorer. From the Start menu, choose Internet Explorer, then type the following in the Address field: https://uss2.city.ac.uk/csd/tools/passwd/

You can save work to My Documents, but you won‟t be able to access the files externally

Excel Notes

Recording Macros

Input Boxes

Message Boxes

Saving options in

Excel 2007

• If you wish to use your

files with an earlier

version save as the 97-

2003 Workbook type.

• If you are using 2007,

save files with Macros

as Macro-Enabled

Naming Ranges Highlight cells you wish to

name, right click and select name ranges

Manage names through the Defined Names box in the formulas tab

VBA and MacrosMacros can be recorded and run from the View ribbon using the Macro tab Select “show developer tab” from Excel options Record Macros and access VBA through Developer Tab Access VBA / Macros in earlier versions using the Tools menu or the VBA

toolbar.

A macro is a sequence of mouse- or key-strokes saved under one command. They allow users to automate time-consuming or difficult tasks, so that the user can work more efficiently and with fewer errors. A macro could be used, for example, to format and print a spreadsheet, or to copy and paste blocks of text. Once created or recorded, they can be run with one command.

When you record the macro, you perform a task in Excel while the recorder stores your actions in a Visual Basic Module.

Absolute and relative references in macros – the importance of selecting a block of text before recording the macro

• If you start recording, then select cells while the recorder is on, the act of selection is also recorded. This means that the macro always runs using this original selection, regardless of what is actually selected at run time.

This is because the macro recorder uses absolute referencing by default. However, using relative references can also give unexpected results, so leave this option for now. More on this topic in coming weeks.

For the moment, always select a cell/cells before starting the macro recorder!

Record a Macro to apply a currency format to selected cells

Open week1.xls Highlight range C6:E9 Click the record Macro button

The Record Macro window appears. Name the macro CurFormat

Give the Macro the shortcut Ctrl+Shift+i

Choose OK. The macro is now recording.

Now format the selected cells asKr. Icelandic as you usually would

To stop recording click the View ribbon, click Macro and click Stop Recording from the menu.

It‟s easy for beginners to forget to stop recording – if so the macro will include lots of unintended actions and you will probably crash Excel and lose your work.

Select C15:D17 Click View Macros

The Macro window appears. select the CurFormat macro and click the Run button. The formatting will be applied to the new selection.

Select another range of numeric cells, and test your macro by using the shortcut key you defined.

At the bottom left of the Excel

window there is a scarcely

noticeable icon near the word

„Ready‟. This button is record

macro.

To stop recording you will

find the Stop recording

button in the same place.

Record a Macro for the “Borders”

From the View Macros

window, select the Macro

you wish to shortcut and

select Options

Add/edit the Shortcut key

description and choose

OK

Close the Macro dialog

box

Editing a macro You can look at the VBA source code for a macro. From the View Macros window, select Edit This opens the Visual Basic Editor as a separate window and brings you to the macro source code,

which you can edit. Fortunately the VB Editor hasn‟t changed appearance from the previous version You can return to Excel in various ways: click the View Microsoft Excel button, use the taskbar at the

bottom, but best of all is keyboard shortcut Alt + F11

The recorded macro is in a text window called a module. The macro is enclosed in between the line beginning Sub and the line End Sub. The green lines that start with a single quote are comments, they are not code, and they don‟t have to be there. Therefore the macro code contains only one line.

Open the VBA editor (through the developer ribbon or by pressing Alt+F11

Either select an existing Module or add a new module.

Type the key word Sub, followed by a space, then the name of the macro (remember no spaces in the macro name)

Press return and the line End Sub appears automatically

You can now type your code (more on this later)

Running a macro from VB editor• While the cursor is within a macro subroutine, press F5 (or click Run)

• This runs macro and is very convenient for testing

Stepping through a macro• You can step through a macro to trace the consequence of each line of code

• Position the Excel and Visual Basic window so each takes up half of the screen.

• Put you cursor on a line of macro code then press F8

• A yellow highlight appears, the yellow line is the next line to be executed

• Keep pressing F8 to step through the code and observe the Excel window to see the effect

Sub MacroName ()

End Sub

„ Comments can be added to give

information about the code. Comments

start with an apostrophe VBA will display

them as green text, but will not read them

as code

MsgBox - the basic function

sub HelloWorld()

MsgBox "Hello World"

End Sub

MsgBox - with more options

sub HelloWorld2()

MsgBox "Hello World", vbOKCancel, "Greeting Box"

End Sub

sub HelloWorld2()

MsgBox "Hello World", vbOKinformation, "Greeting Box"

End Sub

sub HelloWorld2()

MsgBox "Hello World",, "Greeting Box”

End Sub

An Input box prompts the user to enter some information, which can then be manipulated by your Visual Basic program. A very simple example, would be a box that asks the user to type in their name, so that the program could greet the user.

The Syntax for InputBox is as follows:• InputBox Prompt, [Title, Default, XPos, YPos,HelpFile, Context]

Sub NameBox()

InputBox "Please enter your name"

End Sub

Sub NameBox2()

InputBox "Please enter your name","City University",,5000,3000

End Sub

Sub StatusBox()

InputBox"Please enter your status at City University: Student, Staff or Visiting","Status","Student"

End Sub

Macros Revisited • Refining Macros

The VBA Editor

The Object Model

Working with Ranges

You can easily hide the contents of a cell from the worksheet, though it will be visible on the formula bar if the cell is selected.

The method is as follows: select a cell that contains a number or

formula that evaluates to a number; bring up Format Cells choose Custom from the Category list

box Type a semicolon (;) and click OK -

the number will be hidden on the sheet.

Now record a macro to do the above, with the keyboard shortcut of Ctrl + H

Test the macro to ensure it works.

Given a cell containing a date, you can format it to display the day of the week.

In the illustration on the left, the entries in column B contain a formula to display the date immediately to the left, i.e., the formula in B2 is =A2.

In a worksheet replicate some of the above and then record a macro that formats the cells in column B so that they display the day of week. Use the same commands as in the previous exercise, this time typing dddd as the custom format.

Use some of the spare dates to test the macro.