Professional Documents
Culture Documents
1 –Introduction to VBA
3 –Variables
8 –Handling strings
2
1 – Introduction to vba
3
Introduction
EXCEL VBA (Visual Basic for Application) is a programming language allowing you to use
Macros allow in particular to automate repetitive tasks performed under EXCEL. They can also be used to create
dialog boxes in order to make an application developed under EXCEL more user-interactive.
VBA allows users to build GUI : Graphical user interface / Graphical interactive application .
VBA has elements to interact with users : Dialogue boxes , buttons , Forms
4
2 –VBA Selectors and properties
Selectors
Example of objects :
6
Selectors
To select a range between 2 rows : Range("2:5").Select // we select the range between 2 & 5
Range("A7") . Value : value is one of the cell A7 properties ( it’s the value that the user see )
9
Properties
Sub MacroSelection()
Range("A1:B6").Select
Selection.Font.Bold = True
Selection.Value = "Bonjour“
End Sub
10
Properties
Sub hide_sheet()
End Sub
11
Properties
Sheets(“Sheet3").Tab.Color = RGB(255, 0, 0)
12
3 –Variables
Variables
A variable stores a value that can be modified during the execution of a program.
Dim VariableName
where VariableName is a series of characters formed with letters, numbers and the underscore _. The first
character must be a letter.
MacroTestVariable : Macro name
Sub MacroTestVariable()
Valeur is the name of the variable
Dim is the keyword to declare a variable
Dim valeur
valeur = Range("A1").value
If valleur >= 18 And valleur <= 20 Then Range("B1").value = "OK"
End Sub
14
Variables
A variable stores a value that can be modified during the execution of a program.
Most programming languages require determining the type of data that can be stored in a variable when
declared. In VBA, It is not mandatory.
By default, an untyped variable is of type Variant, which allows you to store any type of data.
15
Variables
Some examples :
16
Variables
Tab_1 (0)=16
Tab_1 (9)=80 Variable Type : Integer
Variable length : We
could store 10 in the
table , indexing starts
from 0 to 9
Dim Tab_2(7, 8)
A table of 2 dimensions : You could declare an
array without specifying the type - You could
declare an array with the dimensions you want (
3 etc ) 17
Variables
19
Data structure
A user defined type (or data structure) lets you create a single data type that can represent more than one
built-in data type.
20
Data structure
A user defined type (or data structure) lets you create a single data type that can represent more than one
built-in data type.
End Structure
21
4 –Conditions and Loops
Conditions
Conditions are very useful in programming, they will help us to perform actions according to precise criteria
(same principle as the IS function).
23
Conditions
Conditions are very useful in programming, they will help us to perform actions according to precise criteria
(same principle as the IS function).
24
Conditions
Examples :
Sub example_1 ()
Dim result As String
result = InputBox( “ Text ? ", "Title", "write the name “ ) // we ask user for his name
If result <> "" Then
MsgBox result // we display the name of the user if result isn’t empty
End If
End Sub
25
Conditions
Sub procedure_1()
'Variables
Dim mark As Integer, str_1 As String
mark = Range("A2")
‘ Comments based on the mark value
If mark >= 7 Then
str_1 = "Excellent !"
ElseIf mark > 5 And mark < 7 Then
str_1 = "You could pass"
Else
str_1 = "Your result is very weak , plz revise your homework "
End If
Range("B2") .Value = str_1
End Sub
26
Conditions
Sub procedure_1()
Dim mark As Integer, str_1 As String
mark = Range("A2")
End Select
Range("B2") .Value = str_1
End Sub
27
Loops
Looping is one of the most powerful programming techniques. A loop in Excel VBA enables you to loop
through a range of cells with just a few codes lines.
You could also use nested loops : A loop Inside another loop .
28
Loops
With While loop as long as the condition is true, the instructions are executed in the loop (be careful not to
create an infinite loop).
Iterator is the loop variable , the
Sub while_Loop() Sub while_Loop() loop end when iterator is equal to
Dim iterator 5>4
iterator=1 - You could exit the loop any time
Cells(1, 2) = 1 While iterator <=4 you want by exit while instruction
Cells(2, 2) = 2 cells(iterator , 2 ) .Value = iterator
Cells(3, 2) = 3 wend
Cells(4, 2) = 4 End sub
End sub
29
Loops
The do while loop works the same way as While Wend (as long as the condition is true, the loop is executed):
Dim j As Integer
j=1
Do While j < 9
Cells(j, 3).Value = 13
j=j+1
Loop
30
Loops
Rather than repeating the loop as long as the condition is true, it is possible to exit the loop when the
condition is true by replacing While Loop with do Until Loop :
31
5 – Functions and procedures
32
Functions and procedures
If you want Excel VBA to perform a task that returns a result, you can use a function. Place a function into a
module (In the Visual Basic Editor, click Insert, Module). For example, the function with name Product.
The difference between a function and a sub in Excel VBA is that a function can return a value while a sub
cannot. Functions and subs become very useful as program size increases.
Now we will call our functions and procedure to execute / automate a wanted task
34
Private vs public
The terms Public and Private are used in relation to Modules. The basic concept is that Public variables, subs
or functions can be seen and used by all modules in the workbook while Private variables, subs and functions
can only be used by code within the same module.
An object is a grouping of data and procedures(i.e. Functions and Subs). The procedures are used to
perform some task related to the data.
In general, use this code when writing codes to perform actions on objects in external Excel workbooks in the
current workbook : Workbooks(workbook_name).Sheets( Sheet_name ).Range(a range of cells)
37
Events
An event is an action recognized by an object. The recognition of an event by an object makes it possible to
trigger the execution of a procedure when this event occurs. A mouse click or a keystroke at keyboard are
examples of events that can be interpreted by code VBA.
We can execute code during certain events in the workbook (opening, closing, etc.).
For an object to respond to an event, VBA code must be written in the procedure associated with the event in
question.
38
Events
39
List of workbook Events
40
List of worksheet Events
41
7–Building graphical user interface :
Forms , buttons , dialogue boxes
UserForms
User Forms are graphical objects used to create custom dialog boxes. You can add controls to it in order
to set up a User Interface adapted to your project. It will thus be possible to make entries from this
preformatted medium or to visualize very diverse information (Texts, digital data, pictures, videos ...)
A Userform (also called dynamic form), allows for simple and user-friendly user interfaces for entering,
modifying or viewing data.
43
UserForms
44
Controls
A GUI is made up of controls. These controls can be used in a Form. The following table shows some
of the most commonly used GUI controls in VBA.
Controls also have a whole range of properties and events that differ from one control to another, we will
see here only some of the many possibilities related to these controls.
45
Controls
Control Description
CheckBox Used for true or false values. Multiple check boxes can have true value at the
same time.
ComboBox Used to present a drop down list to the users
CommandButton Used to execute code
Label Used to display static text to the user : ex firstName- lastName
ListBox Allows selection from a list of items , it’s used to present a simple list to the
users – it’s also user to visualize data ( tables ) present in a sheet
Textbox Allows text entry
46
Main properties and methods
The most commonly properties that are available to all controls are : Enabled , visible , SetFocus.
Don’t forget the syntax to get the value of a property of an object : variable_name = Object.Property
Examples :
Value
To Show/Hide control : listbox1.visible =true // listbox1.visible=false
Events Description
Click Occurs when the left mouse button is clicked when over the userform.
DblClick Occurs when the left mouse button is double clicked when over the userform.
Desactivate Occurs when the userform loses focus because a subform is displayed.
Initialize Occurs when the userform is loaded into memory, this is before the userform is
displayed.
KeyDown Occurs when any key is pressed while the userform is displayed.
KeyUp Occurs when any key is released while the userform is displayed.
Layout Occurs when the size of a userform is changed at run-time.
KeyPress Occurs when an ANSI key is pressed while the userform is displayed.
MouseDown Occurs when a mouse button is pressed
48
Controls events
Events Description
MouseMove Occurs when the mouse pointer is moved over the userform at run time.
QueryClose Occurs before a userform is closed or unloaded.
RemoveControl Occurs when a control is removed from the userform at run-time.
Resize Occurs when a userform is resized ( in terms of dimensions )
Scroll Occurs when the userform is scrolled ?
Terminate Occurs when a userform is removed from memory as part of the clean up task
Zoom Occurs when the userform is zoomed
Activate Occurs when the userform is displayed or reactivated. This event will only fire:
if the userform is visible.
AddControl Occurs when a control is added to the userform at run-time.
BeforeDragOver Occurs when a drag and drop operation is in progress while the mouse pointer
is over the userform.
BeforeDropOrPaste Occurs when the left mouse button is released and data is dropped and pasted 49
Dialog boxes
The dialog boxes allow you to interact with the user. We let's stick to the simpler ones here :
The syntax for InputBox is : InputBox("Some text – request to user", "Title of the box" , "an example of value" )
The syntax for MsgBox is : MsgBox prompt, [ buttons, ] [ title, ] [ helpfile, context ]
Dim x
‘ input
x = InputBox("How old are you ?", "Entering the user age" , "30 ")
‘ display
MsgBox (" Your age is " & x )
50
MsgBox
The syntax for MsgBox is : MsgBox prompt, [ buttons, ] [ title, ] [ helpfile, context ]
Prompt : A string expression used for displaying as a message. The maximum length of characters is 1024, which depends
on the width of the characters.
[buttons] : You can use this argument to specify buttons, icon style, button’s identity and modality of the message box.
[title] You can use this argument to specify a title text for your dialog box.
[helpfile] This argument will help you to specify a help file for the user. The user can access that help file using the help
button. If you specify a help file, this mandatory to specify a context number.
[context] A numeric expression that uses to assign a help topic from the help menu.
51
MsgBox buttons
Here you have some possible values for the [buttons] argument of the MsgBox function :
Example :
Sub Option_one()
MsgBox Prompt:="Do you want to continue", Buttons:=vbOKCancel , Title:="any title you want "
End Sub
53
MsgBox return values
You could store the returned value of MsgBox in a variable of type variant
Example :
Dim X as Integer
X=0
If MsgBox("Do you wish to continue? ", vbYesNo) = vbYes Then ‘’we display a msg & we test if the user had clicked in yes
X=1
MsgBox ( " x is equal now to " & X ) ‘’ display : x is equal now to 1
Else
X=0
MsgBox ( " x is equal now to " & X ) ‘’ display : x is equal now to 0
End if 54
Textbox properties and methods
Textbox : allows users entry of data , the main property is textbox1 .text Property of the
field
To set the textbox value : textbox1 .text = " Peter "
Range(" B2 ") . Value = str_1 ‘’ we store the entered value in the range B2 of the activesheet
End sub
Sub CommandButton1_click()
test_1 ‘’ we call the function to be excecuted if the event button1_click occurs
End sub 55
Label properties and methods
Label : allows users to display labels & static text, the main property is Label1 .caption
To set the label value : Label1 .caption= " Last Name : " Property of the
field
To retrieve the actual label value : Dim str_1 = Label .Caption
Field name : could
Example : be label2 , label3 ,
etc
Sub test_1()
Label1.caption= " Last Name : " ‘’ we set the label1 value to be Last Name :
Dim str_2 = Userform1 . Label1 . Caption ‘’ we store the label value in a variable
Range(" A2 ") . Value = str_2 ‘’ we store variable str_2 value in the range A2 of the activesheet
End sub 56
ListBox properties and methods
Next j
58
Exercice
The userform1 display a paire of values ( country , capital ) using a Listbox1 , it contains a command_button1
If the user click in this button , the userform2 will display : ( Use instructions : userform2 .show / userform2 .hide )
Userform2 should be used to Modify the selected row in Userform1 .Listbox1 , it contains a CommandButton for
Display the userfom while opening the workbook : use the procedure of the event workbook_open()
59
8 – Handling strings
60
Handling a string
Trim : removes spaces from the left and right of a given string
Left (string , n ) : Return n chars starting from the left of the string
Right (string , n ) : Return n chars starting from the right of the string
To concatenate two strings : "aaa" & " bbb " ‘’ return "aaabbb" 61
Handling a string
Sub string_examples()
End sub 62
9 – Usefull Built-in functions
63
Some Usefull functions
To convert a string to a number : Cint( string_var ) ‘’ Cint( "33" ) gives 33 where "33" is a string
To convert a number to a string : Str( number_var ) ‘’ Str( 44 ) gives "44" where 44 is a number
To test if a variable is a numeric nmber : IsNumeric ( Variable_name ) "44" : is a string because you have doub
quottes " "
To test if a variant type variable is empty : IsEmpty(Variable_name)
64
Return true or false values
Some Usefull functions
To count the number of populated cells in a range : Worksheets("Sheet1").Range ("B2: D18") . Count
https://www.excel-pratique.com/fr/vba
https://www.excel-easy.com/
http://eric.univ-lyon2.fr/~ricco/cours/cours_excel.html
https://www.guru99.com/creating-your-first-visual-basic-for-
applications-vba-in-excel.html
https://excelmacromastery.com/vba-articles/
https://excel-malin.com/cours-vba-excel-gratuit-en-ligne/
Cours excel VBA - Juliette Dibie
Cours excel VBA - Ricco Rakotomalala
https://docs.microsoft.com/en-us/office/vba/api/overview/excel
Others
66
Visual Basic Course – VBA Excel