Académique Documents
Professionnel Documents
Culture Documents
Recording a Marco
See the Recorded Syntax
Run the Recorded Marco
2. In the Insert menu on top of the Visual Basic Editor, select Module to open the Module
window (code window).
Sub showMessage()
MsgBox "Hello World!"
End Sub
4. Click the Run button, , press [F5], or go to Run..Run Sub/UserForm to run the program
Recording a Macro
Macrosoft Excel has a build-in macro recorder that translates your actions into VBA macro
commands. After you recorded the macro, you will be able to see the layout and syntax. Before
you record or write a macro, plan the steps and commands you want the macro to perform.
Every actions that you take during the recording of the macro will be recorded - including the
correction that you made.
In this example, we will record a macro that sets the cell background color to light yellow. To
record the macro, follow the steps below:
2. In the Record Macro dailog box, type "SetBackgroundColor" in the Macro Name textbox to set
the macro name. Leave all other option by default then click the Ok button. This will start the
macro recording.
3. In the Background Color Panel, select the Ligth Yellow color box. This action will set the
background of the current cell (A1) in light yellow color.
4. To stop the macro recording, click the Stop button (the navy blue rectangle) on the Macro
Recorder toolbar.
Now you have recorded a macro that set cell background to light yellow.
The recorded macro is ready for use. Before we run the marco, let's look into the syntax.
1. To load the Visual Basic Editor, press [Alt] and [F11] at the same time. (Remember from our
prior lesson?) The Visual Basic Editor comes up.
2. Expand the Modules folder in the Project Explorer by clicking on the plus (+) sign.
3. Double click the Module1 folder to see the sub routine (marco).
As the figure shows, the name of the sub routine is "SetBackgroundColor". The color index for
the light yellow is 36. The background pattern is soild.
In our prior example, we created the "Hello World!" marco. We ran the macro within the Visual
Basic Editor. This time we will run the recorded macro in the worksheet.
2. Run the recorded macro by select Tools...Macro...Macros... or press [Alt] and [F8] at the same
time.
3. The Macro dailog box displayed. Since there is only one macro in the module, by default the
only macro, SetBackgroundColor is selected. Click the Run botton to run the macro.
A module is a container for procedures as shown in our prior examples. A procedure is a unit of
code enclosed either between the Sub and End Sub statement or between the Function and
End Function statements.
The following sub procedure (or sub routine) print the current date and time on cell C1:
Sub ShowTime()
Range("C1") = Now()
End Sub
Function sumNo(x, y)
sumNo = x + y
End Function
Procedures in Visual Basic can have either private or public scope. A procedure with private
scope is only accessible to the other procedures in the same module; a procedure with public
scope is accessible to all procedures in in every module in the workbook in which the procedure
is declared, and in all workbooks that contain a reference to that workbook. By default,
procedures has public scope.
Sub z(a)
MsgBox a
End Sub
Sub x()
Call z("ABC")
End Sub
Sub y()
z "ABC"
End Sub
Sub z procedure takes an argument (a) and display the argument value ("ABC") in a message
box. Running either Sub x or Sub y will yield the same result.
Sub ShowSum()
msgbox sumNo(3,5)
End Sub
Function sumNo(x, y)
sumNo = x + y
End Function
The ShowSum sub procedure calls the sumNo function and returns an "8" in a message box.
If there are procedures with duplicate names in different modules, you must need to include a
module qualifier before the procedure name when calling the procedure.
For example:
Module1.ShowSum
If you pass an argument by reference when calling a procedure, the procedure access to the
actual variable in memory. As a result, the variable's value can be changed by the procedure.
Passing by reference is the default in VBA. If you do not explicitly specify to pass an argurment
by value, VBA will pass it by reference. The following two statements yield the same outcome.
Here is an example to show the by reference behavior. The sub procedure, TestPassing 1 calls
AddNo1 by reference and display "60" (50 + 10) on the message box.
Sub TestPassing1()
Dim y As Integer
y = 50
AddNo1 y
MsgBox y
End Sub
The following example shows the by value behavior. The sub procedure, TestPassing 2 calls
AddNo2 by value and display "50" on the message box.
Sub TestPassing2()
Dim y As Integer
y = 50
AddNo2 y
MsgBox y
End Sub
Table of Contents
Lesson 1: Visual Basic Editor (VBE) in Excel
The Visual Basic Editor is the user friendly program that you will use to talk with
Excel. In it you can create your VBA procedures (macros) and userforms. You
will then be able to modify and test these components easily step by step in the
VBE.
The Project Window lists all your open projects with their sheets, modules and
forms. In the Project Window you will add modules and create forms. When you
select one of the components its properties will show in the Properties Window
and the VBA code that you have created for the selected component will appear
in the Code Window.
The Properties Window shows you the properties of the object that is selected in
the Project Window (sheet, module) or the properties of the control (command
button, text box, list box, etc...) that is selected on the forms. You will use this
window often when you start developing forms (userforms).
All the action happens in the Code Window. In this large window you or the
Macro Recorder will write macros. You will also test and fine tune all your macros
in the Code Window.
In this lesson you will learn how to create a new VBA procedure. You will
organize sets of sentences to tell Excel what to do. You can key them in or
copy/paste them from recorded macros, from one of your old macros or from the
Internet where you will find millions of free macros.
When you develop macros in Excel you spend 20% of your time analyzing the
project, 15% writing your VBA procedures and 65% testing and fine tuning them.
Split your screen, use the F8* key and you can see what your procedure does in
Excel step by step. Back up, correct and re-test.
The Macro Recorder is the best teacher and it will be a great assistant (writing
code for you) even when you become an expert at programming in VBA. In this
lesson you will learn about the Macro Recorder and you will try it. You will also
run and test the macro that you have recorded.
The macro recorder is a great assistant and teacher but it sometimes writes
sentences that need to be simplified. In this lesson we modify a recorded macro
and make it better.
You cannot harm your computer with macros so be bold in experimenting with
macros you will learn more and faster. In this lesson you will learn how to protect
you code, your sheets and your workbooks.
Once you have developed your macros you need to trigger them so that they
start. The trigger is called an event. The most frequently used event is the click
on a button. In this lesson you will learn how to add a button to your sheet and
how to connect it to your macro. You will also learn how to start a macro by
opening a workbook (also called spreadsheet or Excel file), by closing a
workbook and even by changing the value of a cell.
Assembling VBA words into sentences is called coding. Here are interesting tips
to make things easier when you start coding.
VBA tells you immediately when the code that you have written is wrong. When
the logic is wrong or when the user gives a wrong answer these errors need to
be handled. In this lesson you will learn the necessary vocabulary to deal with
errors.
The Application is EXCEL itself. Add 15 new VBA words to your vocabulary like
Application.Quit, Application.ScreenUpdating = False,
Application.CutCopyMode=False and others .
Some people call them spreadsheets or Excel files VBA calls them workbooks.
Here are other VBA words to add to your vocabulary. You will learn to work with
ThisWorkbook (the workbook in which runs the macro) with many workbooks and
even with all the workbooks in a directory.
There can be 256 sheets in a single workbook. In this lesson you will discover
the vocabulary to move from one to the other, to copy/paste from one to the
other, to add and delete worksheets and even go from the first to the last sheet of
a workbook to do something on all of them. You will also learn how to copy the
sheets into another workbooks or to transform a single sheet into a workbook.
In this lesson you will improve your VBA vocabulary with 40 some words to work
within the worksheet. You will learn how to select a cell or a group of cells and
how to count the rows and columns. You will learn how to change the value of a
cell or insert a formula in it. The 5 VBA words that you will use the most moving
around the sheets are Range, Select, Offset, Activecell and CurrentRegion. What
you can do with these 5 words and tens of other important words is covered in
this lesson.
You will use message boxes or input boxes to communicate with the user.
Through these pop-ups the user can supply bits of data or say " Yes, No, Ok,
Cancel" and other short answers during the execution of a macro.
Excel offers you the most powerful database tools (sorting, filtering, etc...). With
VBA these tools become even more powerful. You will learn how to use them
with the data that you extract from large centralized databases (SAP, Oracle,
EssBase, Access, etc..), from accounting and sales programs and with financial
data that you can download from the Internet.
The variable is the concept that will launch your creativity and allow you to
develop real programs in Excel. It will empower you to develop sophisticated
programs and work extremely rapidly with very large sets of data. Before learning
about variables you develop macros after you develop programs.
They are the KILL, the IF_THEN_ELSE_END IF, the SELECT-CASE, the
DO_LOOP, the FOR_NEXT....
Lesson 21: Working with Functions
There are Excel functions and VBA functions. Three topics are covered in this
lesson. You can use existing Excel functions within VBA or you can create brand
new Excel functions with VBA and you can use VBA functions.
When you connect to outside sources of data (large databases, text files, other
Excel workbooks, Access, etc.) the computer is using SQL (Structured Query
Language) a specialized language to work with data. You can use Excel's
functionalities to connect and extract data but you can also use directly the SQL
language top extract data. It is the fastest way to access any external data.
Lesson 23: Working with Windows and other Microsoft Programs FROM
Excel
With VBA for Excel you can develop VBA procedures (macros) to work within
Excel while calling other Microsoft programs like Access, Notepad, Word,
Project and even Windows.
You have used message boxes and input boxes to communicate with the user
while the macro was running. When these tools are no longer sufficient you
need to develop useforms.
In this lesson you will learn how to set the properties of the userform and you will
develop code within the two important events that are " On Activate" and " On
Close" .
The command button is the control where most of the code resides and
everything happens when you " CLICK " on it.
Labels are just labels. You use them to describe functions and to share
information with the user.
The combo box is the ultimate control. It is a drop-down list and you will learn
how to develop sets of combo boxes where the choices offered in the second
combo box depend on the choice made in the first one. They are called
cascading combo boxes.
You will develop list boxes when you want to allow the user the possibility of
multiple choices.
Lesson 31: Properties and VBA code for Check Boxes, Option Buttons and
Frames
You can test different values increasing them step by step until you find the right
one and you do it with a spin button.