introduction to visual basic for applications programming in excel

47
VBA programming Introduction to Visual Basic for Applications programming in Excel

Upload: wyatt-armstrong

Post on 28-Mar-2015

256 views

Category:

Documents


3 download

TRANSCRIPT

  • Slide 1

Introduction to Visual Basic for Applications programming in Excel Slide 2 Resources FAQ : http://msdn2.microsoft.com/en-us/isv/bb190540.aspx http://msdn2.microsoft.com/en-us/isv/bb190540.aspx Reference : http://msdn2.microsoft.com/en-us/isv/bb190540.aspx http://msdn2.microsoft.com/en-us/isv/bb190540.aspx Books Excel online help Slide 3 Excel programming Two ways to access the Excel programming environment: Using the menus Alt F11 Slide 4 Development environment Project explorer Editor Watch (debug) Property window Slide 5 Add a function to Excel Right click on Microsoft Excel objects : Select Module Slide 6 Generalities about VBA VBA is compiled on the fly (at the moment of execution). Case insensitive, the VBA editor changes the text case to agree with syntax of existing objects. A function can be called MyFunction but if you type myfunction the editor will change m and f to upper case. Comments are from the sign to end of line. When typing code you may consider using the edit toolbar. Slide 7 Structure of a function Function delimiters Function name Function type Argument name Argument type Argument list Function body: Attribution acts like return value Slide 8 Call from Excel Slide 9 Requirements for a function to be called from Excel Cannot change the structure of a sheet. Cannot change the propeties of a cell. If the function calls another function that on should respect the same restrictions. If a function is to be called even if the arguments have not changed then the Application.Volatile property should be called. Must return a type that Excel knows how to handle. Slide 10 Subroutines Subs do not return results unlike functions. Subs cannot be directely called from Excel as they do not return results. If a Sub is called from a function that is called from Excel then is should respect the same restrictions as functions callable from Excel. Slide 11 Function and Sub parameters may be optional. If a parameter is optional then all following parameters should also be optional. If an optional parameter is of type Variant then we may test it s absence by using the Is Missing test. Default values Sub ajoutEspace(ByRef str As String, Optional nb As Integer = 5) Dim prefix As String prefix = Space(nb) str = prefix & str Debug.Print str End Sub Sub ajoutEspace(ByRef str As String, Optional vnb As Variant) Dim prefix As String Dim nb As Integer If IsMissing(vnb) Then nb = 5 Else nb = CInt(vnb) End If prefix = Space(nb) str = prefix & str Debug.Print str End Sub Slide 12 Named parameters Whan calling a functions parameters may be referenced by their name. ajoutEspace str:=res, nb:=10 Sub ajoutEspace(ByRef str As String, Optional nb As Integer = 5) Dim prefix As String prefix = Space(nb) str = prefix & str Debug.Print str End Sub Slide 13 Variable declaration A variable is declared suing the Dim keyword Function surfCercle(x As Double) As Double Dim pi As Double pi = 3.1415279 surfCercle = x * x * pi End Function Variable declaration may be omited. On taht case the undeclared variables are Variant. The Option Explicit instruction on top of a module makes the variable declaration mandatory. Slide 14 Types String : character strings. Numerical types: integers, floating point reals (simple or double precision) and fixed point reals (decimal). Dates : dates are represented as the number of days since January 1 1900. Arays: collections of variables of same type, indexed by integers. The programmer as the choice of the indexes, default is 1 to N. Variant : type that can store data of any other type. Objets : types that are not part of the language base types and are defined on libraries. Slide 15 Strings A character string is declared as String as in the following example Dim message As String Lots of functions allow string manipulations : Len, returns the size InStr, looks inside for contents Replace, modifies a String Etc. Slide 16 Numerical types Integers: Byte Integer, integer 2 bytes Long, integer 4 bytes Decimal : Currency Floating point reals: Single, 4 bytes Double, 8 bytes Slide 17 Booleans and dates Boolean, represents a logical condition (true or false). Date, represents a date as the number of days since January 1 1900. There is a one day difference with Java GregorianCalendar dates. Slide 18 An array is declared by following the name of a variable with parentheses and, eventually, a size. Elements of an array are accessed using indexes. The global Option allows to change the starting index for arrays, Default is 1. Arrays Dim t(1 To 10) As Integer Sub arrTest(j As Integer) Dim t(1 To 10) As Integer Dim i As Integer i = 1 While i Flow control Conditionals: If Iif Function Signe(x As Double) As Byte If x > 0 Then Signe = 1 ElseIf x < 0 Then Signe = -1 Else Signe = 0 End If End Function Function sPlus(x As Double) As Double sPlus = IIf(x > 0, x, 0) End Function Slide 24 Loops While For For Each, used with collections. Sub arrTest(j As Integer) Dim t(1 To 10) As Integer Dim i As Integer i = 1 While i Example Option Explicit Sub displaySquare() Dim i As Integer For i = 1 To 100 result.Cells(i, 1).Value = i * i result.Cells(i, 1).Interior.ColorIndex = i Mod 32 Next i End Sub Result is an object of type Excel.Worksheet Excel -> library Worksheet -> class Cells method from the Worksheet class with 2 arguments (there is another method with same name and 1 argument) returns an object of type Excel.Range Value property of the Range class Slide 31 Events Events are special subroutines that are executed automatically. Event execution is triggered by external actions.. Some examples: Button click (with mouse or enter key). Cell contents change Cell selection change. Private Sub btnGo_Click() displaySquare End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub End If If Target.Address = "$A$1" Then calc.Cells(1, 4).Value = "A1 Changed" End If End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) calc.Cells(2, 4).Value = "selection is now " & Target.Address End Sub Slide 32 Events Class name. On certain cases Object name Event name Slide 33 Errors The default behavior of a program when an error occurs is to stop it and display a message box. A different behavior can be specified using the following instructions: On Error Goto 0, restarts the default behavior. On Error Resume Next, ignores the errors and moves to the next instruction. On Error Goto, jumps to (line marked by :) when an error occurs. If an error occurs the Err variable is initialized. Slide 34 Errors (next) The Err variable contains several members, the most important: Number, contains the unique error code. Description, contains the error description. Raise, generates an error (useful to signal an error to another part of the program). Clear, cleans the next error. Slide 35 Errors(example) Sub ajoutEspace(ByRef str As String, Optional vnb As Variant) Dim prefix As String Dim nb As Integer On Error GoTo err_label If IsMissing(vnb) Then nb = 5 Else nb = CInt(vnb) End If prefix = Space(nb) str = prefix & str Exit Sub err_label: MsgBox Err.Description End Sub Modifies the error handling Label Error handling Slide 36 Class modules A class module is useful to define its own classes. A class may contain 3 kinds of members: Member variables Methods Properties 2 different visibilities for members: Private Public Slide 37 Creating a class Slide 38 Example : Share Option Explicit Public nom As String Public cours As Currency Member variable Slide 39 Example: share Option Explicit Private isCall As Boolean Public strike As Currency Public maturity As Date Public sousjacent As Act Public Property Let TypeContrat(tp As String) If LCase(tp) = "call" Then isCall = True Else isCall = False End If End Property Private member Property: write Public members Slide 40 Example: share Public Property Get TypeContrat() As String If isCall Then TypeContrat = "Call" Else TypeContrat = "Put" End If End Property Property: read Slide 41 Example : Stock shares Public Function GetPrice(r As Double, vol As Double) As Double Dim td As Date Dim days2exp As Long td = Date days2exp = maturity - td If isCall Then GetPrice = Call_Eur(sousjacent.cours, strike, days2exp, r, vol) Else GetPrice = Put_Eur(sousjacent.cours, strike, days2exp, r, vol) End If End Function Member function Slide 42 Class usage Sub test() Dim FT As New Act Dim CallFT As New Opt Dim price As Double FT.nom = "Fance Telecom" FT.cours = 15.3 CallFT.TypeContrat = "Call" Set CallFT.sousjacent = FT CallFT.strike = 15 CallFT.maturity = "20/12/2012" price = CallFT.GetPrice(0.01, 0.2) Debug.Print price End Sub Declaration/allocation Method usage Method call Slide 43 Forms Forms are graphical objects that can be displayed on Excel. Forms are used to interact with the user. A form is composed from a canvas to which we add graphical components. The Excel toolbox provides different controls (buttons, text boxes, labels, list boxes, etc.). Each control provides events that are used to interact with the user. To each form a module is associated. Slide 44 Creating a form Slide 45 Form and toolbox Slide 46 Form design Slide 47 Code of a form Event for the click button. Access to a property of another control