Excel programming Two ways to access the Excel programming environment: Using the menus Alt F11
Development environment Project explorer Editor Watch (debug) Property window
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 Function name Function type Argument name Argument type Argument list Function body: Attribution acts like return value
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 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.
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
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
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.
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.
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 <= 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() Nme of Sub (without the keyword Call) folowed by arguments separated by,, Function HelloWorld() As String Dim res As String res = "Hello World" Call ajoutEspace(res) HelloWorld = res End Function Sub ajoutEspace(ByRef str As String) str = " " & str End Sub Function HelloWorld() As String Dim res As String res = "Hello World" ajoutEspace res HelloWorld = res End Function Sub ajoutEspace(ByRef str As String) 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 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
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 <= 10 t(i) = j + i i = i + 1 Wend End Sub Sub arrTest(j As Integer) Dim t(1 To 10) As Integer Dim i As Integer For i = 1 To 10 t(i) = j + i Next i End 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 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
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
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, jumps to (line marked by :) 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) 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
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
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 Property: write Public members
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 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
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.
Your consent to our cookies if you continue to use this website.