Professional Documents
Culture Documents
1|Page
HYPER EXCEL & VBA
Introduction
VBA (Visual Basic for Application) is a language related to Visual Basic that can only run through
a host application (Excel, in our case).
Using VBA, we can do almost anything imaginable With Excel ……
But before we get started, let’s begin by making sure that the tools we need are visible.
If you are using Excel version 2007 (or a higher version), click on File > Options > Customize the
Ribbon and then check “Developer”.
If the version of Excel that you are using is lower than 2007, add the “Control Toolbox” and
“Formula” toolbars.
2|Page
HYPER EXCEL & VBA
To work with VBA code, we’ll need an editor, which is installed by default. You can open it by
pressing the shortcut key combination “Alt+F11”.
We’ll come back to this. What’s important for now is just to remember the “Alt+F11” shortcut…
First Macro
The macro recorder makes it very easy to automate certain tasks.
To give just one example, we will automate the following actions:
• delete the contents of columns A and C
• move the contents of column B to column A
• move the contents of column D to column C
To do this, click on “Record Macro” and then “OK”, carry on the actions described above without
interruption (because everything you do will be recorded) and then click on “Stop Recording”.
For versions of Excel lower than 2007: Tools > Macros > Record New Macro.
Excel has recorded your actions and translated them into VBA code.
To view your macro, open the editor (Alt+F11) and click on “Module1”:
This code represents the recorded actions.
Let’s take a moment to look at the code that Excel has generated:
Sub Macro1()
'
' Macro1 Macro
'
'
Columns("A:A").Select
Selection.ClearContents
Columns("C:C").Select
Selection.ClearContents
Columns("B:B").Select
Selection.Cut Destination:=Columns("A:A")
Columns("D:D").Select
Selection.Cut Destination:=Columns("C:C")
Columns(“C:C”).Select
End Sub
3|Page
HYPER EXCEL & VBA
Sub and End Sub mark the beginning and end of the macro, and “Macro1” is the name of this
macro:
Sub Macro()
End Sub
Let’s edit the name of the macro to make it more descriptive, changing “Macro1” to
“column_handling” (the name of the macro cannot any spaces):
Sub column_handling()
The text in green (text proceeded by an apostrophe) is comment, and will be ignored when the code
is executed:
'
' Macro1 Macro
'
'
This kind of commentary can be very useful for finding things when there is a lot of code, or when
you want to prevent the execution of lines of code without deleting them.
Sub column_handling()
'
' My first commentary!
'
'
Columns("A:A").Select
Selection.ClearContents
Columns("C:C").Select
Selection.ClearContents
Columns("B:B").Select
Selection.Cut Destination:=Columns("A:A")
Columns("D:D").Select
Selection.Cut Destination:=Columns("C:C")
Columns(“C:C”).Select
End Sub
Insert your button and then just select the macro that you created:
When you click on the button, your macro will be executed:
Selections
We’ll begin by creating a macro that selects the cell that we specify.
First open the editor and add a module:
5|Page
HYPER EXCEL & VBA
You can test this macro by clicking on your formula button, and you will see that cell A8 is now
selected.
We will now edit the macro so that it selects cell A8 on the second worksheet:
Sub Example()
'Activating of Sheet 2
Sheets("Sheet2").Activate
'Selecting of Cell A8
Range("A8").Select
End Sub
Excel will now activate Sheet 2 and then select cell A8.
Note: the comments (text in green) will help you understand the macros in this course correctly.
This method of selecting cells allows for more dynamic selections. It will be quite useful further
along.
Here is little example:
Sub Example()
'Random selection of a cell from row 1 to 10 and column 1
Cells(Int(Rnd * 10) + 1, 1).Select
'Translation:
'Cells([random_number_between_1_and_10], 1).Select
End Sub
7|Page
HYPER EXCEL & VBA
In this case, the row number is: Int(Rnd*10)+1, or in other words: a number between 1 and 10
(there’s no reason you should learn this code at this point).
Moving a selection
Sub Example()
'Selecting a cell (described in relation to the cell that is currently active)
ActiveCell.Offset(2, 1).Select
End Sub
Moving the selection box two rows down and one column to the right:
Selecting rows
It is possible to select entire rows using the Range or Rows commands (the Rows command is of
course specific to rows).
Sub example()
'Selecting rows 2 to 6
Range("2:6").Select
End Sub
Sub example()
'Selecting rows 2 to 6
Rows("2:6").Select
End Sub
8|Page
HYPER EXCEL & VBA
Selecting columns
As with rows, it is possible to select entire columns using the Range or Columns commands (the
Columns command is of course specific to columns).
Sub Example()
'Selecing columns B to G
Range("B:G").Select
End Sub
Sub Example()
'Selecing columns B to G
Columns("B:G").Select
End Sub
Properties
In this exercise, we will write VBA cod that modifies the content and appearance of cells and
worksheets.
First open the editor, add a module, copy the macro below into it, and link it to a formula button
(refer back to the previous page if needed).
Sub properties()
'Incomeplete Macro
Range ("A8")
End Sub
In this first example, click on “Value” and them on the Tab key to validate your choice.
Sub properties()
'Incomeplete Macro
Range("A8").Value
End Sub
In this case, the property, Value, represents the contents of the cell.
Next, we will assign the value 48 to cell A8:
Sub properties()
'A8=48
Range("A8").Value = 48
'Translation:
'The value of cell A8 is equal to 48
End Sub
In this case, we’re going to modify cell A8 on the worksheet, the cell from which the procedure is
actually launched (using a formula button). If you create a second button like this on worksheet 2,
it will modify cell A8 on that sheet (sheet 2).
To make it modify cell A8 on sheet 2 when you click the button on sheet 1, you have to add the
following before Range: Sheets(“Name_of_the_sheet”) or Sheets(Number_of_the_sheet).
Sub properties()
'A8 on Sheet2=Sample text
Sheets("Sheet2").Range("A8").Value = "Sample text"
'Or:
'Sheets(2).Range("A8").Value="Sample text"
End Sub
Just the same, if we want to modify cell A8 on sheet 2 of another open workbook, we have to add
the following before Sheets and Range: Workbooks(“Name_of_the_file”).
Sub properties()
'A8 on Sheet 2 of workbook 2 = Sample text
Workbooks("Book2.xlsx").Sheets("Sheet2").Range("A8").Value = "Sample text"
End Sub
Although we used Value in these examples, you don’t really need to use it, because if nothing else
is specified, it will be the value of the cell that is modified.
For example, these two lines would have the same effect:
Range(“A8”).Value = 48
Range(“A8”) = 48
10 | P a g e
HYPER EXCEL & VBA
Sub Properties()
'Erase the contents of column A
Range("A:A").ClearContents
End Sub
Text Formatting
When you open Font., the list of properties that can be applied to text formatting will appear:
We’ll explain in detail how to edit the colors on the next page……..
To remove the “bold” formatting from text, all you have to do is replace “Yes” with “No”, or in
other words, “True” with “False”:
Sub Properties()
'Remove "bold" formatting from cells A1 through A8
Range("A1:A8").Font.Bold = False
End Sub
Add borders
Sub Properties()
'Add a border to cells A1 to A8
Range("A1:A8").Borders.Value = 1
'Value = 0 => no border
End Sub
12 | P a g e
HYPER EXCEL & VBA
So we will tell A7 to take its value from A1, which would look like this:
Sub Properties()
'A7=A1
Range("A7") = Range("A1")
'Or:
'Range("A7").Value=Range("A1").Value
End Sub
If we only wanted to copy the text size from the other cell, the code would look like this:
Sub Properties()
Range("A7").Font.Size = Range("A1").Font.Size
End Sub
Anything on the left side of the = takes on the value of what is on the right side of the = .
Change the value of a cell based on its own value
Now we’re going to create a click counter.
Each time we click, the value of A1 will be incremented by 1:
Sub Properties()
'Click counter in A1
Range("A1") = Range("A1") + 1
End Sub
13 | P a g e
HYPER EXCEL & VBA
Excel execute the code line by line, so these commentaries should help you understand the code
itself:
'For example: before the code is executed, A1 has the value 0
Sub properties()
'The button has been clicked, so the procedure is starting
'For the moment, A1 still has the value 0
'DURING the execution of the line immediately below, A1 still has the value 0
Range("A1") = Range("A1") + 1 'And now the calculation is: New_value_of_A1 = 0+1
'A1 has the value 1 only AFTER the execution of the line of code
End Sub
With
This code makes it possible to set different properties of the active cell:
Sub properties()
ActiveCell.Borders.Weight = 3
ActiveCell.Font.Bold = True
ActiveCell.Font.Size = 18
ActiveCell.Font.Italic = True
ActiveCell.Font.Name = "Arial"
End Sub
Sub properties()
'Beginning of instructions using command: WITH
With ActiveCell
.Borders.Weight = 3
.Font.Bold = True
.Font.Size = 18
.Font.Italic = True
.Font.Name = "Arial"
'End of instructions using command: END WITH
End With
End Sub
14 | P a g e
HYPER EXCEL & VBA
Sub properties()
With ActiveCell
.Borders.Weight = 3
With .Font
.Bold = True
.Size = 18
.Italic = True
.Name = "Arial"
End With
End With
End Sub
Colors
Let’s start by assigning a color to the text in A1.
After adding Font., we get this result:
There are two different ways that we can set the color: ColorIndex, which has 56 color, or Color
which makes it possible to use any color at all.
ColorIndex
Here you can see the 56 colors that are available through ColorIndex:
15 | P a g e
HYPER EXCEL & VBA
To set the color of our text to one of these 56, we should write:
Sub example()
'Text color for A1:green(Color num,10)
Range("A1").Font.ColorIndex = 10
End Sub
For versions of Excel lower than 2007: using ColorIndex is preferable to using Color.
Color
Here is a similar example in which we use Color:
Sub example()
'Text color for A1:RGB(50,200,100)
Range("A1").Font.Color = RGB(50, 200, 100)
End Sub
In this case, the color is: RGB(50,200,100).
RGB stands for Red-Green-Blue, and the numerical values go from 0 to 255 for each color.
A few examples of colors so that you can understand this better:
• RGB(0,0,0): black
• RGB(255,255,255): white
• RGB(255,0,0): red
• RGB(0,255,0): green
• RGB(0,0,255): blue
Choose the color that you want and just copy the three values into the
RGB(red_value,green_value,blue_value).
So to change our text color in purple, we should use the following code:
Sub example()
'Text color for A1:RGB(192,32,255)
Range("A1").Font.Color = RGB(192, 32, 255)
End Sub
16 | P a g e
HYPER EXCEL & VBA
For versions of Excel lower than 2007: the number of colors is limited (the closest available color
to the RGB values will be used).
To apply this effect to many cells at once, we can use the Selection command:
Sub Example()
'Border weight
Selection.Borders.Weight = 4
'Border color: red
Selection.Borders.Color = RGB(255, 0, 0)
End Sub
17 | P a g e
HYPER EXCEL & VBA
Result
Result:
18 | P a g e
HYPER EXCEL & VBA
Variables
Variables make it possible to store all sorts of information.
Here’s the first example:
'Display the value of the variable in a dialog box
Sub variable()
'Declaring the variable
Dim my_variable As Integer
'Assigning a value to the variable
my_variable = 12
'Displaying the value of my_variable in a MsgBox
MsgBox my_variable
End Sub
This first line of code delcares the variables (this is generally placed at the beginning of the
procedure).
Dim my_variable As Integer
• Dim: declares the variable
• my_variable: the name chosen for this variable (no spaces allowed)
• As: declares the variable’s type
• Integer: variable type
Declaring these variables is not absolutely necessary, but it is recommended. It makes it easier to
find them, can help resolve problem, etc. In short, it’s a good idea to get in the habit of declaring
variables correctly.
A variable’s type indicates the nature of its contents (text, numbers, date, etc.).
And then a value is given to the variable:
my_variable=12
Finally, the value of the variable is displayed in a dialog box:
MsgBox my_variable
MsgBox “value” is the simplest way to display a value in a dialog box.
We’ll go into more detail about dialog boxes in later lessons..
The code will have this result:
19 | P a g e
HYPER EXCEL & VBA
If you don’t understand what the point of using these variables is yet, don’t worry, the examples
introduced in the following lessons will prove their usefulness….
The type of variables
'Example : text
Dim varText As String
varText = "Hper Excel"
20 | P a g e
HYPER EXCEL & VBA
'Example : date
Dim varDate As Date
varDate = "04/08/2017"
'Example : True/False
Dim varBoolean As Boolean
varBoolean = True
The symbols in the table above can be used to shorten our variable declarations.
For reasons of readability, we will not be using these in the lessons, but here is an example anyway:
Dim example As Integer
Dim example%
These two lines are identical.
Comment: it is possible to force the declaration of variables by putting Option Explicit right at the
beginning of a module (this way an error message will be displayed if you have forgotten to declare
variables).
Practice Exercise
We will now create, step by step, a macro that retrieves a last name form cell A2, a first name from
cell B2, an age from cell C2 and displays them in a dialog box.
We’ll begin by declaring the variables (all on the same line, separated by commas):
Sub varaibles()
'Declaring variables
Dim name As String, age As Integer
End Sub
Then we assign values to the variables using Cells:
Sub varaibles()
'Declaring variables
Dim name As String, age As Integer
'Variable values
name = Cells(2, 1)
age = Cells(2, 2)
End Sub
21 | P a g e
HYPER EXCEL & VBA
Finally, we’ll display the results in a dialog box, using the & operator to join the values (as in
Excel).
Sub varaibles()
'Declaring variables
Dim name As String, age As Integer
'Variable values
name = Cells(2, 1)
age = Cells(2, 2)
'Dialog box
MsgBox name & "," & age & " years old"
End Sub
The results:
The next step is to display in a dialog box the row from the table that is indicated by the number in
cell F5.
This is the goal:
Take a moment to try to solve this problem yourself before looking at the solution below…
The solution:
Sub varaibles()
'Declaring variables
Dim name As String, age As Integer, row_number As Integer
'Variable values
row_number = Range("F5") + 1
name = Cells(row_number, 1)
age = Cells(row_number, 2)
'Dialog box
MsgBox name & "," & age & " years old"
End Sub
22 | P a g e
HYPER EXCEL & VBA
Adding a variable:
'Declaring variables
Dim name As String, age As Integer, row_number As Integer
The variable row_number will now take the value of cell F5, to which we have added 1 (so that
we don’t get data from the first row, which contains the table’s titles), so that row_number will
have the row number of the cells that we are interested in as its value:
row_number = Range(“F5”)+1
All that’s left to do is to replace the row number in the Cells command with our variable:
row_number = Range("F5") + 1
name = Cells(row_number, 1)
age = Cells(row_number, 2)
Now our macro displays the row that we’re interested in from the table.
By the way, please note that we can reduce this procedure a single line of code:
Sub varaibles()
MsgBox Cells(Range("F5") + 1, 1) & "," & Cells(Range("F5") + 1, 2) & " years old"
End Sub
Although the code will work perfectly, it is much less readable than the previous version and more
difficult to rework (to make sure that our code is easy to understand, we won’t be abbreviating it in
this way in these lessons).
23 | P a g e
HYPER EXCEL & VBA
Variables (Continued)
Arrays
While variables only allow us to store one value each, arrays make it possible to store many values
and they work almost exactly the same way.
Here are some examples of declarations:
'Sample variable declaration
Dim var1 As String
There is only one number in parentheses in this declaration, which means that it is a one dimensional
array. This number sets the size of the array, array1(4) is an array in which the cells are numbered
from 0 to 4, which means that it is an array with 5 cells:
Constants
Like variables, constants can be used to store values, but the difference is that they can’t be modified
(thus their name).
For example, we could add a constant to avoid having to repeat a number like 6.87236476641:
Sub const_example()
Cells(1, 1) = Cells(1, 2) * 6.87236476641
Cells(2, 1) = Cells(2, 2) * 6.87236476641
Cells(3, 1) = Cells(3, 2) * 6.87236476641
Cells(4, 1) = Cells(4, 2) * 6.87236476641
Cells(5, 1) = Cells(5, 2) * 6.87236476641
End Sub
This makes the code much easier to read (important pasts in particular) and makes it much easier
to change the value of the constant, should you need to:
Sub const_example()
'Declaration of a constant + assignment of value
Const ANNUAL_RATE As Double = 6.87236476641
Sub procedure2()
'=>var1 cannont be used here
End Sub
In order to use a variable in any of the procedure within a module, all you have to do is declare it at
beginning of the module. And if you declare a variable this way, its value will be maintained until
the workbook is closed.
25 | P a g e
HYPER EXCEL & VBA
Sub procedure2()
'=>var1 can also be used here
End Sub
If you want to be able to use a variable in any module, on the same principle as the previous
example, all you have to do is replace Dim with Global:
Global var1 As Integer
To maintain the value of a variable after the execution of the procedure in which it appears, replace
Dim with Static:
Sub procedure1()
Static var1 As Integer
End Sub
To maintain the values of all the variables in a procedure, add Static before Sub:
Static Sub procedure1()
Dim var1 As Integer
End Sub
Sub variables()
'Declaration
Dim idm As Hyper
'Example of use
MsgBox idm.fri_name & " " & idm.lst_name
End Sub
26 | P a g e
HYPER EXCEL & VBA
Conditions
Conditions are very useful in programming because they allow us to execute actions based on
specific criteria (it’s the same principle as the IF function).
The most important conditional function is IF, and now we’ll take a look at how it works:
IF [CONDITION HERE] Then ‘=> IF condition is validated, THEN
‘Instructions if true
Else ‘=> OTHERWISE
‘Instructions if false
End IF
Let’s move right on to practice and return to the example that we used in the lesson on variables.
The purpose of this procedure was to display a dialog box containing the data from the row whose
number is indicated in cell F5:
Sub varaibles()
'Declaring variables
Dim name As String, age As Integer, row_number As Integer
'Variable values
row_number = Range("F5") + 1
name = Cells(row_number, 1)
age = Cells(row_number, 2)
'Dialog box
MsgBox name & "," & age & " years old"
End Sub
Let’s begin by adding a condition that will verify that the value of cell F5 is numerical before the
code is executed.
We’ll use the function IsNumeric to text this condition:
27 | P a g e
HYPER EXCEL & VBA
Sub varaibles()
'execute the instructions that follow THEN
If IsNumeric(Range(“F5”)) Then
'Declaring variables
Dim name As String, age As Integer, row_number As Integer
'Variable values
row_number = Range("F5") + 1
name = Cells(row_number, 1)
age = Cells(row_number, 2)
'Dialog box
MsgBox name & "," & age & " years old"
End IF
End Sub
We also need to add instructions to execute in case the conditions are not met:
Sub varaibles()
'Declaring variables
Dim name As String, age As Integer, row_number As Integer
'Variable values
row_number = Range("F5") + 1
name = Cells(row_number, 1)
age = Cells(row_number, 2)
'Dialog box
MsgBox name & "," & age & " years old"
End If
End Sub
28 | P a g e
HYPER EXCEL & VBA
Working with our array, which contains 16 rows of data, our next step will be to test whether the
variable row_number: “greater than or equal to 2” and “less than or equal to 17”.
But first, have a look at this list of comparison operators:
= is equal to
<> is different than
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
Now let’s add the conditions that we mentioned above, using AND along with the comparison
operators listed above:
Sub varaibles()
End Sub
29 | P a g e
HYPER EXCEL & VBA
If we wanted to make our macro a bit more practical, we could replace 17 with a variable that
contained the number of rows.
This would let us add or remove lines from our array without having to change this limit each time.
In order to do this, we have to create a variable nb_row and add this function:
We want this function to count the number of non-empty cells in the first column and then replace
17 with nb_rows:
Sub varaibles()
row_number = Range("F5") + 1
nb_rows = WorksheetFunction.CountA(Range("A:A")) 'NBVAL Function
If row_number >= 2 And row_number <= nb_rows Then 'IF CORRECT NUMBER
name = Cells(row_number, 1)
age = Cells(row_number, 2)
MsgBox name & "," & age & " years old"
Else 'IF NUMBER IS INCORECT
MsgBox "Your entry " & Range("F5") & " is not a valid number!"
Range("F5").ClearContents
End If
End Sub
ElseIf
ElseIF makes it possible to add more conditions after the IF command:
If [CONDITION1] Then ‘>= IF condition 1 is true, THEN
‘Instructions 1
Elseif [CONDITION2] Then ‘>= IF condition 1 is false, but condition 2 is true, THEN
‘Instructions 2
Else ‘=> OTHERWISE
‘Instructions 3
End If
If condition 1 is true, Instructions 1 will be executed, and we will leave the If command (which
begins with If and ends with End If). If condition 1 is false, we continue to condition 2. If this
30 | P a g e
HYPER EXCEL & VBA
condition is true, Instructions 2 will be executed, and if it is false,then Instructions 3 (under Else)
will be executed).
Here is an example, with a score between 1 and 6 in cell A1 (without decimals in this case) and a
score_comment in cell B1 based on the score:
Sub scores_comment()
'Variables
Dim note As Integer, score_comment As String
note = Range("A1")
'Comments in B1
Range("B1") = score_comment
End Sub
Select
There is an alternative to using If with lots of Elseif instructions: the Select command, which is
better suited to these sorts of situations:
Here is an example of the same macro written with Select:
31 | P a g e
HYPER EXCEL & VBA
Sub scores_comment()
'Variables
Dim note As Integer, score_comment As String
note = Range("A1")
'Comments in B1
Range("B1") = score_comment
End Sub
Please note that we could also have used other comparison operators, for example:
Case Is >= 6 ‘if the value is>=6
Examples with different values:
Case Is = 6,7 ‘if the values is = 6 or 7
Case Is <> 6,7 ‘if the value is different than 6 or 7
Case 6 To 10 ‘if the value is =any number between 6 and 10
Conditions (continued)
IsNumeric returns TRUE if the value is numerical and FALSE if this is not the case:
32 | P a g e