Introduction to Visual Basic for Applications programming in Excel Resources FAQ : http://msdn2.microsoft.com/en-us/isv/bb190540.aspx Reference : http://msdn2.microsoft.com/en-us/isv/bb190540.aspx Books Excel online help Excel programming Two ways to access the Excel programming environment: Using the menus Alt F11 Development environment Editor Project explorer Property window Watch (debug) Add a function to Excel Right click on “Microsoft Excel objects” : Select “Module” 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. Structure of a function Function delimiters Argument listname Function Argument type type Argument Function name Function body: Attribution acts like return value Call from Excel 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. Subroutines Sub’s do not return results unlike functions. Sub’s 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. Default values Function and Sub parameters may be optional. If a parameter is optional then all following parameters should also be optional. Sub ajoutEspace(ByRef str As String, Optional nb As Integer = 5) If an optional parameter is of type Variant then we may Dim prefix As String Sub ajoutEspace(ByRef str As String, Optional vnb As Variant) testprefix it’ s=absence byString using the Is Missing test. Space(nb) Dim prefix As str = prefix strAs Integer Dim&nb Debug.Print str If IsMissing(vnb) Then End Sub nb = 5 Else nb = CInt(vnb) End If prefix = Space(nb) str = prefix & str Debug.Print str End Sub Named parameters Whan calling a functions parameters may be referenced by their name. 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 ajoutEspace str:=res, nb:=10 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. 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. 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. Numerical types Integers: Byte Integer, integer 2 bytes Long, integer 4 bytes Decimal : Currency Floating point reals: Single, 4 bytes Double, 8 bytes 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. Arrays An array is declared by following the name of a variable with parentheses and, eventually, a size. Elements of an array are accessed using Dim t(1 To 10) Asindexes. Integer Sub arrTest(j As Integer) The global Option allows to change the starting index Dim t(1 To 10) As Integer for arrays, Default is Integer 1. Dim i As i=1 While i <= 10 t(i) = j + I i=i+1 Wend End Sub Function calls A function is called by using its name and replacing the parameter list by a parenthesised list of expressions of same size. A function call may replace any expression of the same type as the function. Exemple : X=surfCercle(2.0)+4 Calling a Sub There are two ways of calling a Sub: • Call followed by sub name with arguments between() Function HelloWorld() As String • Nme of Sub (without the keyword Call) folowed by Dim res Asseparated String arguments byString , , Function HelloWorld() As res = "Hello World" Dim res As String Call ajoutEspace(res) res = "Hello World" HelloWorld = res ajoutEspace End Functionres HelloWorld = res End Function Sub ajoutEspace(ByRef str As String) str = " " & str Sub str As String) End ajoutEspace(ByRef Sub str = " " & str End Sub Sub, Function : parameters Two ways to pass a parameter to a function or a Sub: By value, the name of the parameter is preceded by the keyword ByVal. By reference the name of the parameter is reseded by the keyword ByRef. This is the default parameter passing method. Global variables A variable declared outside a function or Sub body is global. Two types of visibilities are possible: Public, visible on all modules, Private, visible only on the current module. Flow control Conditionals: If Function Signe(x As Double) As Byte If x > 0 Then Iif Function Signe = 1sPlus(x As Double) As Double sPlus x=<IIf(x > 0, x, 0) ElseIf 0 Then End Function Signe = -1 Else Signe = 0 End If End Function Loops While For For Sub arrTest(j As Integer) Dim t(1 To 10) As Integer SubDim arrTest(j As Integer) i As Integer Dimused t(1 To 10) As Integer Each, with collections. Dim i = 1i As Integer While i <= 10 Fort(i) i = =1 To j + 10 i t(i) i ==i j++1 i Next i Wend End EndSub Sub Cell manipulation Sheets and cells in Excel are represented by variables of type defined on an Excel library, they can be manipulated directly from VBA. A variable exists corresponding to each sheet : Object usage Un object is a variable with a type defined by a class on an external library. Like any other variable un object is declared using the keyword Dim. Once declared an object is not initialized. A non initialized object is Nothing. In order to initialize an object the keyword Set in must be used in conjunction with the instruction New that allocates the memory needed by the object. Objects and classes A class is a type that does not belong to the VBA basic types. Classes are defined on libraries. A variable whose type is a class is an Object. An Objet contains members that may be: properties, Methods (functions or subs) Two objects of same type may have properties with different values. Accessing cells One of the members of the worksheet class is the method Cells. There are several versions of the method Cells, among those: A version with two integer arguments represnting the line and column of the cell. A version with a single String argument represnting the cell as in “A1”. The Cells method returns an object of type Range that can be used to manipulate the cell contents. Range class members Value, property, represents the contents of the cell. Text, property, represents the text that is displayed on the cell. Formula, property, represents the formula stored on the cell. ClearContents, method, erases the cell contents. ClearComments, method, removes the cell comment. 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 Result is an object of type Next i Excel.Worksheet End Sub Excel -> library Worksheet -> class Cells method Value from property the Worksheet of the Range class class with 2 arguments (there is another method with same name and 1 argument) returns an object of type Excel.Range 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). Private Sub btnGo_Click() Cell contents change Cell displaySquare Private Sub Target As Range) selection change. EndWorksheet_Change(ByVal Sub If Target.Cells.Count > 1 Or IsEmpty(Target) Then Exit Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) End 4).Value If calc.Cells(2, = "selection is now " & Target.Address End Sub If Target.Address = "$A$1" Then calc.Cells(1, 4).Value = "A1 Changed" End If End Sub Events Class name. On certain cases Object name Event name 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 <label>, jumps to <label> (line marked by <label>:) when an error occurs. If an error occurs the Err variable is initialized. 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. Errors(example) Modifies the error handling 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 Label err_label: MsgBox Err.Description Error handling End Sub 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 Creating a class Example : Share Option Explicit Public nom As String Public cours As Currency Member variable 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 Public members Property: write Example: share Public Property Get TypeContrat() As String If isCall Then TypeContrat = "Call" Else TypeContrat = "Put" End If End Property Property: read 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 Class usage Sub test() Dim FT As New Act Dim CallFT As New Opt Dim price As Double Declaration/allocation 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 Method usage Method call 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. Creating a form Form and toolbox Form design Code of a form Event for the click button. Access to a property of another control