VBA

50
Computational Finance and Risk Management Financial Data Access with SQL, Excel & VBA Guy Yollin Instructor, Applied Mathematics University of Washington Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 1 / 50

description

HUong dan excel

Transcript of VBA

Computational Finance and Risk Management

Financial Data Accesswith SQL, Excel & VBA

Guy YollinInstructor, Applied Mathematics

University of Washington

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 1 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 2 / 50

Lecture references

John WalkenbachExcel 2010 Power Programming with VBASams, 2010

Chapter 7 - 11

J. Green, S. Bullen, R. Bovey, M. AlexanderExcel 2007 VBA Programmer’s ReferenceWiley, 2007

Chapter 1

Duane Birnbaum and Michael VineExcel VBA Programming for the Absolute Beginner, 3rd EditionThomson Course Technology, 2007

Chapter 1

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 3 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 4 / 50

VBA

VBAVBA (Visual Basic for Applications) is a scripting language built intoMicrosoft Office applications

MS Office applications that support VBA:ExcelAccessWordPowerpointOutlook

Almost anything you can do with an office application, you canautomate through VBA

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 5 / 50

Usefulness of VBA

Excel is a common tool for quantitative data analysis, review, and storage

VBA can enhance Excel in the following ways:

Automation of labor-intensive tasksFormatting tablesCreating graphsUpdating data from databases or the web

Advanced analyticsCustom worksheet function developmentAnalysis requiring sophisticated workflowsAnalysis requiring an interface to external software

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 6 / 50

Logistics of VBA programming

VBA Coding†:

The VBA code that you write (or record) is stored in a VBA module

VBA modules are stored in an Excel workbook

You use the Visual Basic Editor (VBE) to view and edit VBA code

You can use the Macro Recorder to record a sequence of user actionsand create a VBA procedure to reproduce them

The terms macro and procedure are synonymous in the VBA context

†J. Walkenbach, Excel 2010 Power Programming with VBAGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 7 / 50

Logistics of VBA programming

VBA Code†:

VBA Code is structured as proceduresA VBA Sub procedure is a series of statements than can be executedin a number of ways

macro button of the developer tabVisual Basic Editorshortcut keyquick access toolbaranother procedureform control embedded on a worksheet

A VBA Function procedure returns a single value (or an array) andcan be called from another VBA procedure or used in a worksheetformula

†J. Walkenbach, Excel 2010 Power Programming with VBAGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 8 / 50

First VBA program

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 9 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 10 / 50

The Developer ribbon

Make sure you can access the Developer ribbonGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 11 / 50

Macro recording example

Problem A common problem is that the column width is not properlyadjusted when CSV files are first opened

Solution Record a macro to adjust the column widthsplace the macro in the PERSONAL.XLSB file (this is aplace to store macros that can be shared across workbooks)create an button for the macro on the quick launch toolbar

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 12 / 50

Turn on macro recorder

Click Record Macro to begin the process

In the Record Macro dialog, provide a macro name and description, ashortcut key assignment (if desired), and a location to store the macro

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 13 / 50

Adjust column width

Perform Excel tasks

Click Stop Recording when finished

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 14 / 50

Add macro to the Quick Access Toolbar

Right click the Quick Access Toolbar and select customize

Select macros from the dropdown list, choose the desired macro,modify the button, and click OK

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 15 / 50

Launch macro from Quick Access Toolbar

Click the button on the Quick Access Toolbar to run macro

Macro can also be run via the assigned shortcut keyCtrl+Shift+C for the AutoAdjustColumns macro

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 16 / 50

The recorded macro

1 selects all cells in the worksheet2 select all columns and autofit the width3 selects cell A1Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 17 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 18 / 50

Typical table formating

Bold column namesFirst row shaded background

Border around table cellsColumn width adjusted

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 19 / 50

Macro Recorder workflow

The basic process for getting started with VBA with the aid of the MacroRecorder is as follows†:

1 Record the actions that you want to code2 Review the code and find the lines that perform those actions3 Delete the rest of the code4 Modify the recorded code5 Add variables, control structures, and other code that the Macro

Recorder cannot record

†Getting Started with VBA in Excel 2010http://msdn.microsoft.com/en-us/library/ee814737.aspx

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 20 / 50

Border code from macro recorder

S e l e c t i o n . Borde r s ( x lDiagonalDown ) . L i n e S t y l e = xlNoneS e l e c t i o n . Borde r s ( x lD iagona lUp ) . L i n e S t y l e = xlNoneWith S e l e c t i o n . Borde r s ( x l Edg eL e f t )

. L i n e S t y l e = x lCon t i nuou s

. Co l o r I n d e x = x lAutomat i c

. TintAndShade = 0

. Weight = x lTh inEnd WithWith S e l e c t i o n . Borde r s ( xlEdgeTop )

. L i n e S t y l e = x lCon t i nuou s

. Co l o r I n d e x = x lAutomat i c

. TintAndShade = 0

. Weight = x lTh inEnd WithWith S e l e c t i o n . Borde r s ( xlEdgeBottom )

. L i n e S t y l e = x lCon t i nuou s

. Co l o r I n d e x = x lAutomat i c

. TintAndShade = 0

. Weight = x lTh inEnd WithWith S e l e c t i o n . Borde r s ( x lEdgeR igh t )

. L i n e S t y l e = x lCon t i nuou s

. Co l o r I n d e x = x lAutomat i c

. TintAndShade = 0

. Weight = x lTh inEnd WithWith S e l e c t i o n . Borde r s ( x l I n s i d e V e r t i c a l )

. L i n e S t y l e = x lCon t i nuou s

. Co l o r I n d e x = x lAutomat i c

. TintAndShade = 0

. Weight = x lTh inEnd WithWith S e l e c t i o n . Borde r s ( x l I n s i d e H o r i z o n t a l )

. L i n e S t y l e = x lCon t i nuou s

. Co l o r I n d e x = x lAutomat i c

. TintAndShade = 0

. Weight = x lTh inEnd With. . .

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 21 / 50

Significant border code

' remove any d i a g o n a l l i n eS e l e c t i o n . Borde r s ( x lDiagonalDown ) . L i n e S t y l e = xlNoneS e l e c t i o n . Borde r s ( x lD iagona lUp ) . L i n e S t y l e = xlNone

' box o u t s i d e o f s e l e c t i o nS e l e c t i o n . Borde r s ( x l E d g e L e f t ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( xlEdgeTop ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( xlEdgeBottom ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( x lEdgeR igh t ) . L i n e S t y l e = x l C o n t i n u o u s

' box i n t e r i o r o f s e l e c t i o nS e l e c t i o n . Borde r s ( x l I n s i d e V e r t i c a l ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( x l I n s i d e H o r i z o n t a l ) . L i n e S t y l e = x l C o n t i n u o u s

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 22 / 50

Title bold/background from macro recorder

Sub TestMacro ( )'' TestMacro Macro''

With S e l e c t i o n . I n t e r i o r. Pa t t e rn = x l S o l i d. P a t t e r n C o l o r I n d e x = x lAutomat i c. ThemeColor = xlThemeColorDark1. TintAndShade = −0.14996795556505. PatternTintAndShade = 0

End WithS e l e c t i o n . Font . Bold = True

End Sub

Note, top row was already selected for the macro recording

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 23 / 50

Significant title bold/background code

Sub TestMacro ( )'' TestMacro Macro''

S e l e c t i o n . I n t e r i o r . Pa t t e rn = x l S o l i dS e l e c t i o n . TintAndShade = −0.14996795556505S e l e c t i o n . Font . Bold = True

End Sub

set interior pattern to solidset TintAndShade (-1=darkest, 1=lightest)set Bold property of Font object to True

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 24 / 50

Final table formatting procedureSub FormatTable ( )' s e l e c t the c u r r e n t r e g i o nA c t i v e C e l l . Cu r r en tReg ion . S e l e c t' draw bo rde r around a l l c e l l sS e l e c t i o n . Borde r s ( x lDiagonalDown ) . L i n e S t y l e = xlNoneS e l e c t i o n . Borde r s ( x lD iagona lUp ) . L i n e S t y l e = xlNoneS e l e c t i o n . Borde r s ( x l E d g e L e f t ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( xlEdgeTop ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( xlEdgeBottom ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( x lEdgeR igh t ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( x l I n s i d e V e r t i c a l ) . L i n e S t y l e = x l C o n t i n u o u sS e l e c t i o n . Borde r s ( x l I n s i d e H o r i z o n t a l ) . L i n e S t y l e = x l C o n t i n u o u s' s e l e c t the top row o f the c u r r e n t r e g i o nS e l e c t i o n . Rows ( 1 ) . S e l e c t' make column t i t l e s bo ld wi th a l i g h t g ray backgroundS e l e c t i o n . Font . Bold = TrueS e l e c t i o n . I n t e r i o r . Pa t t e rn = x l S o l i dS e l e c t i o n . I n t e r i o r . TintAndShade = −0.15' a d j u s t the column wid th sC a l l AutoAdjustColumnsEnd Sub

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 25 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 26 / 50

Object-oriented, event-driven paradigm

Excel VBA is based on an object-oriented, event-driven paradigm

Objects Object represents elements of an applicationa worksheet, a chart, a range

Properties Objects have properties that you can get and set; propertiesare attributes of an object that describe its characteristics

Range("A1").Font.Bold = TrueNote that a property can return an object

Methods Objects have methods or actions they can performRange("A1").ClearContents

Events Events are actions recognized by an object and can beresponded to by an event procedure

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 27 / 50

Object-oriented, event-driven paradigm

Object hierarchy Excel object classes are arranged in a hierarchyApplicationWorkbooks collectionWorkbookWorksheets collectionWorksheetRange

Object collections Objects of the same class are grouped together in ancollection object

WorkbooksWorksheetsChartsSheetsQueryTables

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 28 / 50

Simplified Excel object model

The Excel VBA object model largely emulates the user interfaceGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 29 / 50

Referencing items in the hierarchy

To reference items in the object hierarchy, a period (dot) is used as aseparator character

parent.child Application.Workbooks("Book1.xlsx")Workbooks("Book1.xlsx").Worksheets(1)

object.property Worksheets("Sheet1").Range("A1").Value

object.method Range("A1").ClearContents

If you omit a specific reference to an object, Excel uses theappropriate active object (note: it is the programmers responsibilityto make sure an appropriate object is active)To refer to a member in a collection, use the member’s name or itsindex number

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 30 / 50

Illustration of VBA object hierarchy

The Excel VBA object model largely emulates the user interfaceGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 31 / 50

Abbreviated references

Note the following line of code:Range ( "A1" ) = 42

Is interpreted as:A p p l i c a t i o n . Act iveWorkbook . A c t i v e S h e e t . Range ( "A1" ) . Value = 42

Because:The Value property is the default property of the Range objectActiveSheet is assumedActiveWorkbook is assumedApplication is assumed

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 32 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 33 / 50

Important Application object properties (∼300)

ActiveCell Returns a Range object that represents the active cell

ActiveSheet Returns an object that represents the active sheet (thesheet on top)

ActiveChart Returns a Chart object that represents the active chart

ActiveWorkbook Returns a Workbook object that represents theworkbook in the active window (the window on top)

ActiveWindow Returns a Window object that represents the activewindow (the window on top)

RangeSelection Returns a Range object that represents the selected cells

Selection Returns the selected object in the active window(Range object or chart object)

see Developer’s Guide to the Excel 2010 Application Objecthttp://msdn.microsoft.com/en-us/library/office/gg192737

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 34 / 50

Important properties and methods of the Range objectPropertiesValue Get/set cell values (default property for Range object)

Text Returns formatted text in a cell

Formula Get/Set formula in a cell

Address Returns text string of cell address

Font Returns a Font object

MethodsSelect Selects a range

Copy Copy a range

Clear deletes contents and formatting

ClearContents deletes contents but leaves formattingsee Developer’s Guide to the Excel 2010 Range Object

http://msdn.microsoft.com/en-us/library/office/gg192736Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 35 / 50

Other important properties

Cells Returns a Range object that represents the cells in the specifiedrange

Worksheets("Sheet2").Cells(2, 3)

Offset Returns a Range object that represents a range that’s offsetfrom the specified range

Range("A1").Offset(1, 2)

Both the Cells and Offset properties are useful in looping statementswhere the row and column inputs (offsets) could be based on loopcounters

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 36 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 37 / 50

Object BrowserFrom the VBE, you can press F2 to open the Object Browser

Search or browser for classes, methods, properties, and eventsGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 38 / 50

Developer ReferenceFrom the Object Browser, you can click the question mark to open theDeveloper Reference to the selected section

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 39 / 50

Developer Reference

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 40 / 50

Help on methods, properties, and events

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 41 / 50

The Visual Basic Editor (VBE)

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 42 / 50

Immediate window

From the VBE, you can press Ctrl+G to make the immediate windowvisible

The Immediate window is extremely useful for executing VBAstatements directly and for debugging code

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 43 / 50

Outline

1 Introduction to VBA

2 VBA macro recorder: simple example

3 VBA macro recorder: extending the simple example

4 The Excel VBA object model

5 The Application object, the Range object, the Cells property

6 The VBE, the Object Browser, the Developers Reference

7 The Colorful Stats project

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 44 / 50

The Colorful Stats project

The Colorful Stats project is an introductory VBA exercise developed inchapter 1 of Excel VBA Programming for the Absolute Beginner

Colorful Stats is implemented asan event procedure

Event procedures areself-contained blocks of codethat require some type ofstimulus in order to run. Thestimulus often comes directlyfrom the user (for example, amouse click), but may also resultfrom another piece of code†

†D. Birnbaum, Excel VBA Programming for the Absolute BeginnerGuy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 45 / 50

Add a control to a worksheet

Click the Insert Controls button on the developer ribbonSelect a control (in this case an ActiveX command button)Note the Design Mode button is now depressed

Click and drag on the worksheet to set the control’s size and location

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 46 / 50

Edit control properties

Click the Controls Property button (or double click on the control) toopen the Properties dialog

Edit the desired properties like Caption, Name, etc.Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 47 / 50

Edit event procedure

Click View Code (or double click the control) to open the VBESelect the type of event to respond to (e.g. click) and edit the codefor the event procedure

Exit Design Mode and test the application

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 48 / 50

Colorful Stats source codeP r i v a t e Sub cmdCa l cu l a t e_C l i ck ( )

'−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−'Add fo rmu l a s f o r summary s t a t s'−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−With Ac t i v eShe e t

' These f o rmu l a s a r e en t e r e d i n t o the new workshee t .. range ( "D2" ) . Formula = "=COUNT( " & ActiveWindow . S e l e c t i o n . Address & " ) ". range ( "D3" ) . Formula = "=MIN( " & ActiveWindow . S e l e c t i o n . Address & " ) ". range ( "D4" ) . Formula = "=MAX( " & ActiveWindow . S e l e c t i o n . Address & " ) ". range ( "D5" ) . Formula = "=SUM( " & ActiveWindow . S e l e c t i o n . Address & " ) ". range ( "D6" ) . Formula = "=AVERAGE( " & ActiveWindow . S e l e c t i o n . Address & " ) ". range ( "D7" ) . Formula = "=STDEV( " & ActiveWindow . S e l e c t i o n . Address & " ) "

'−−−−−−−−−−−−−−−−−−−−−−'Add l a b e l s and s t a t s'−−−−−−−−−−−−−−−−−−−−−−. r ange ( "C2" ) . Value = "Count : ". range ( "C3" ) . Value = "Min : ". range ( "C4" ) . Value = "Max : ". range ( "C5" ) . Value = "Sum : ". range ( "C6" ) . Value = " Average : ". range ( "C7" ) . Value = " Stan␣Dev : ". range ( "C2 :D7" ) . S e l e c t

End With

'−−−−−−−−−−−−−−−−−−−−−−−−−−−−−' Format the l a b e l s and s t a t s .'−−−−−−−−−−−−−−−−−−−−−−−−−−−−−With S e l e c t i o n

. Font . S i z e = 16

. Font . Bold = True

. Font . Co l o r = RGB(232 , 211 , 162) ' Husky Gold

. Font .Name = " A r i a l "

. Columns . AutoF i t

. I n t e r i o r . Co l o r = RGB(54 , 60 , 116) ' Husky Purp l e

. Borde r s . Weight = x lTh i c k

. Borde r s . Co lo r = RGB(216 , 217 , 218) ' Husky GrayEnd Withrange ( "A1" ) . S e l e c t

End Sub

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 49 / 50

Computational Finance and Risk Management

http://depts.washington.edu/compfin

Guy Yollin (Copyright © 2012) Data Access with SQL, Excel & VBA Introduction to VBA 50 / 50