VBA For Excel Lesson 1
VBA For Excel Lesson 1
-----------------------------------------------------------------------------------------------
VBA for Excel Lesson 1: The Visual Basic Editor in Excel (VBE)
The first thing that you need to do is to make sure that the security level of Excel
is set at either "Low" or "Medium" so that you can use the macros (VBA
procedures) that you develop. See how to do this in lessons 10 on Excel VBA
Security.
The VBE is integrated into Excel and you can open it from the Excel menu bar
"Tools/Macro/Visual Basic Editor".
Open Excel and on your keyboard click on the "ALT" key (left of the space bar),
hold and click on the "F11" key (the F11 key is at the top of your keyboard). Here
is the Visual Basic Editor. Click again and you are back to Excel. Nothing to
install it has been there all the time nobody has cared to tell you so.
The Visual Basic Editor (VBE from now on) is the friendly programming
environment within Excel.
When you want somebody to do some work for you you open your Email
program and you send him a message in a language that he understands
(English, Spanish, French...). When you want Excel to do some work for you you
open the Visual Basic Editor and you write the instructions in a language that
Excel understands VBA ( Visual Basic for Application).
You will develop, test and modify VBA procedures (macros) in the Excel Visual
Basic Editor (VBE). It is a very user friendly development environment. The VBA
procedures developed in the Excel Visual Basic Editor become part of the
workbook in which they are developed and when the workbook is saved the VBA
components (macros, modules, userforms. etc.) are saved at the same time.
When you send the workbook to the "Recycling bin" the VBA procedures are
gone.
When you work with the VBE there always should be 3 windows that are
showing. The Project window (1), the Code window (2) and the Properties
window (3) like below.
You might not see the 3 windows on your screen. We will fix that right now and it
can be a little tricky. But once you have set them they will stay in their position
always. So the following exercise is a ONE TIME only exercise bear with me.
If there are any widow open under the tool bars close them. On the menu bar of
the VBE choose "View" and select "Properties Window". The window can appear
minimized, it can be full width at the top of the screen or many other ways. You
want it from top to bottom on the right of the screen. To do so click on its blue line
at the top, hold and drag it to the bottom right corner. It is now minimized. Click
again on its blue header, hold and drag it full left (it will even disappear) toward
the vertical middle of the screen. It is now in the following position:
Then go back to the menu bar and select "Project Explorer". From wherever it is
click on its blue header, hold and drag it all the way down in the bottom right
corner. It is now free.
Reduce the size of the "Project Explorer" to about the width of the "Properties
Window" and one third the height by using the double arrows that appear when
you move the mouse over the border of the "Project Explorer". Click again on its
blue header, hold and bring the top left corner of the "Project Explorer" over the
top left corner of the "Properties Window". Then let go.
You now have the "Project Explorer" over the "Properties Windows" in the left
part of your screen. The "Code Window" appears when you double click on a
sheet name in the "Project Explorer". You will see later that the "Code Window"
also appears when you double click on a userform name or a module name.
You can resize the 3 windows by placing the cursor over the borders (*) and
dragging them right, left, up or down.
You can use "ALT/F11" to navigate from Excel to the VBE and back.
The Project window shows you all the workbooks that are open. If you have not
downloaded the tutorial just open a new workbook and you will see the following:
If you click on the minus (-) signs in the Project window you see the objects that
are part of the different workbooks (projects). There are Sheets (usually three in
a new workbook) and there is always the ThisWorKbook object in which you
store the procedures that you want to start automatically when the workbook is
opened.
If you go to Excel and add a sheet (right click on the tab and select Inserte) you
will see when you come back to the Visual Basic Editor that there are now 4
sheets in the project window.
You will earn in VBA lesson 14 how to add sheets using VBA:
Sheets.Add
NOTE: If you have a workbook called "FUNCRES.XLA" at the top of the list it is
because you have activated the "Analysis Toolpack " add-in to have more
functions in Excel. If you double click on the name of the workbook you will be
asked to supply a password (the password is not available except to Microsoft's
people). Other people develop workbooks and they protect their macros. If you
double click on a workbook name and you are required to submit a password it is
because the developer has decided not to make his macros visible.
If you have downloaded the VBA tutorial and opened the Excel file "excel-
visual-basic-editor.xls" plus a new workbook you will see this:
If you click on the minus (-) signs in the Project window you see the objects that
are part of the different workbooks (projects). There are Sheets in a workbook,
there is always the ThisWorKbook object (in which you store the procedures that
you want to start automatically when the workbook is opened) and, there can be
Forms (VBA lessons 24 to 33) and Modules (files in which you write and
regroup your VBA procedures (macros) one or many per module).
In the picture above you can see that the project "Book1.xls" comprises 3 sheets
and ThisWorkbook. "excel-visual-basic-editor.xls" has 6 sheets, one userform,
two modules plus the "ThisWorkbook" object. If in the project window you double
click on a sheet name, on ThisWorkbook or on Module1 you will see two things
happening. In the "Property window" you see the properties of the selected
objects and in the "Code window" you see the VBA procedures (macros) stored
in the object. In "Book1" you will notice that there are no macros anywhere so the
code window will be blank except for "Option Explicit" that you have discovered
in lesson 1.
If you double click on a userform name the form appears over the code window
and when you double click on the form or one of its controls (command buttons,
text boxes, combo boxes, list boxes and others) the code for the object
appears in the code window
VBA for Excel Lesson 3: The Properties Window in the Visual Basic Editor
of Excel
The Properties window shows you the properties of the object that is selected in
the Project Window (single click). For example in a new workbook if you single
click on "Sheet1" in the Project Window you see the properties of sheet1 in the
Properties Window.
As you can see a worksheet has 12 properties that you can set in this window
but that you can also modify programmatically. For example if you go to Excel
and change the name on the tab of "Sheet1" (right click on the tab and select
Rename) to "Introduction" you will see when you come back to the Visual Basic
Editor that the property "Name" (the one without the parentheses) has changed
to "Introduction
You can also change the name of a sheet that appears on its tab in Excel directly
into the Properties Widow. For example select Sheet2 in the project window and
change the property "Name" (the one without the parentheses) to "Switchboard".
GO to Excel and notice that you now have a sheet named "Switchboard".
You will earn in VBA lesson 14 how to modify the name of a sheet using VBA:
Activesheet.Name = "Introduction"
If you click on "ThisWorkbook" in the Project Window or you will see that this
object has 30 properties. If you have downloaded the VBA tutorial and opened
the Excel file "excel-visual-basic-editor.xls" you will see that a modue has only
one property (and a very important one, that a useform has 35 properties and a
list box 37.
The "(Name)" property is present for every objects but a lot of properties are very
specific to other objects like the "RowSource" property of the list box.
VBA for Excel Lesson 4: The Code Window in the Visual Basic Editor of
Excel
90% of the VBA work is done in the Code Window writing VBA sentences, testing
your VBA procedures (macros) and modifying them when needed.
Sub proFirst()
Range("A1").Value = 34
Range("A2").Value = 66
Range("A3").Formula = "=A1+A2"
Range("A1").Select
End Sub
Now go to Excel and on the menu bar go to "Tool/Macros" select "proFirst" and
click on run.
NOTE: You cannot change the font or its color in the code window. You
input appears in black, comments appear in green, reserved words in blue
and when you make a mistake the color of the font turns to red.
NOTE: For a lot of users the wheel of the mouse doesn't work in the code
window. To correct this frustrating situation download and install the free
fixer offered as part of the downloadable tutorial.
The code widow shows the procedures that are part of the element of the project
on which you have double clicked in the Project Window (module, sheet,
userform, control or ThisWorkbook).
In your new workbook double click on "Sheet2" in the project window and this is
what the Code Window looks like:
In the Code Window there is a main window in which appears the code and at
the top there are two drop-down lists.
In the left DDList Select "Worksheet". Immediately the first and final lines of a
macro appear in the code window (Private Sub
Worksheet_SelectionChange(ByVal Target As Range)). If you wanted to develop
a macro that would run automatically when any value in any cell is changed you
would write it between these two lines. Click on the small arrow of the DDLIst on
the right and you will see this:
These are all the events that could automatically trigger a macro that you would
write. A macro could start as the sheet is selected (Activate), as the sheet is
calculated (Calculate), etc. You will learn more on events in VBA lesson 9
In the left DDList Select "Workbook". Immediately the first and final lines of a
macro appear in the code window (Private Sub Workbook_Open()). If you
wanted to develop a macro that would run automatically when workbook
opens you would write it between these two lines. Click on the small arrow of the
DDLIst on the right and you will see this:
These are 28 events that could automatically trigger a macro that you would
write. A macro could start when the workbook is opened (Open), before the
workbook is printed (BeforePrint), etc. You will learn more on events in VBA
lesson 9
If you have downloaded the VBA tutorial and opened the Excel file "excel-
visual-basic-editor.xls" double click on a module in the Project Window. Now the
DDList on the right shows you all the macros that have been developed in the
module. Select one and you are taken to the first line of the selected macro. To
see the events related to a userform or any of the controls double click on its
name in the Project Widow and then double click anywhere on the userform. In
the right DDList you will see all the events.
If you right click in the left margin of the code window a shortcut menu is shown.
See how to use these menu items in the downloadable tutorial and see
everything that can happen in this left margin
Now that you have discovered the Visual Basic Editor (VBE) and its 3 windows
you can build your VBA procedures (macros).
Most macros are developed in the code window of modules. Below "Option
Explicit" at the top of the window you build a macro by writing:
sub proTest()
(don't use a capital "S" before "sub" than click on "Enter" and you get this:
Sub proTest()
End Sub
The VBE adds the line "End Sub" and capitalises the "S" of "Sub". The VBE
capitalises letters when the word is written correctly. This is one interesting
feature that you should never forget about. Make it an habit to never use capital
letters in the code and let the VBE tell you that there is something wrong by not
capitalising letters.
Two exceptions to the manual capitalisation are when you declare variables or
when you name macros like above. You will see why in later lessons.
Now what is left is to write a procedure within the two lines of code above. For
example your VBA procedure could look like this:
Sub proTest()
Sheets("Sheet1").Select
Range("C1").Select
Range("A1").Select
End Sub
The procedure above will go down column "C" and assemble first names of
column "A" and last names of column "B" with a space in between. It will perform
this task all the way down until there are no more first names in column "A".
VBA for Excel Lesson 6: Testing Macros in the Visual Basic Editor for
Excel
Close every program on your computer. Open Excel and a workbook with a
macro in it If you have downloaded the tutorial use "excel-visual-basic-
editor.xls"). Open the Visual Basic Editor. On the Window status bar at the
bottom of your screen you can see that Excel is open and also the VBE. Right
click on the status bar in the empty space where I have added the orange stars:
The Excel workbook occupies half of the screen and the VBE occupies the other
half. Excel can be in the left half of the screen or the right half. Make the Code
window wider in the VBE so that you can see most of the code (see lesson 1).
Click anywhere within the macro and press the F8 key at the top of your
keyboard. The fist line of code turns to yellow and a small arrow appears in the
margin. We are in the execution process.
NOTE: While you are running the macro step by step you can stop the
execution at anytime by clicking on the stop button in the toolbar.
The line that is highlighted in yellow is the line that will be executed next time
you click on F8.
One of the tools that makes the programming environment in Excel unique is the
Excel Macro Recorder.
In this section you will work with the Macro Recorder and you will run the macro
that you have recorded.
With the Excel macro recorder you cannot develop a macro that will
damage Excel or your computer. The bolder you are in your trials the more
you will learn.
Even after more than 15 years of programming I still use the macro recorder
daily. Not to learn anymore but to write code (VBA words and sentences) for me.
For example why would I write the following sentence when the Macro Recorder
will do it for me without any typos:
To reproduce the sentence above in your own workbook open a new workbook
go to "Tools/Macros/Record New Macros...". In the window that appears click on
"OK". Select a cell , click on "Edit/Copy" and then on "Edit/Paste Special/Values",
click on "OK" and finally click on the "Esc" key.
You will use often the few lines of code above when you want to copy/paste cells
without carrying the format or the formulas, when you want to add while pasting
or when you want to paste in columns what you have copied in rows.....
You record a single version of this piece of code and you change manually the
components like:
xlPasteFormulas instead of xlPasteValues
xlPasteFormats instead of xlPasteValues
xlAdd instead of xlNone
xlMultiply instead of xlNone
Transpose:=True instead of Transpose:=False
The Excel macro recorder is the best teacher that you can have and will remain
the best assistant for the rest of your VBA developer's life.
The Excel Macro Recorder has tendencies to overdo it sometimes. We will see
how to modify a recorded macro in the next lesson.
You have started using the Macro Recorder to write code for you and noticed
that sometimes the MR overdoes it. For example when I develop tables and
reports I will often select a set of cells and use the icon to add small
borders around all cells:
Range("D4:F10").Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
You notice that this is a series of "With/End With" statements (4 for the edges
and 2 for the insides. You can copy this code anytime you need it but make sure
that you are not generating an error. For example if you use this piece of code on
a single row of cells make sure that you remove the section about
"xlInsideHorizontal" and if you use this code on a single column of cells make
sure that you remove the section about "xlInsideVertical".
You can remove the lines of code about the "xlDiagonal..." and any of the
statement that you don't really need. Formatting is time consuming so slim down
your code.
When does the VBA procedure (macro) start? When an EVENT happens. The
event is what triggers the VBA Excel procedure.
95% of the VBA procedures that you develop are triggered by a click on a
button located on a worksheet.
I prefer using text boxes rather than VBA command buttons because they are
much easier to maintain and allow much more creativity in the design. You can
use the font that you like and the background color that fits your needs. If you are
a little creative you can add 3D effects, special borders and the likes.
I always keep the Excel drawing toolbar visible at the bottom of my screen
You create text boxes by a left click on the icon , let the button go, then go to
the worksheet left click, hold and stretch the text box. When the border of the
active text box is made of diagonal lines you can work the text inside the text
box. If you click again on the border it becomes a set of dots and you then can
work the text box itself. Right click on the border in any of the two states and you
will see that the menus are different.
First you develop a macro in a module in the VBE. Then you click ob the text
box and when the border becomes a set of dots right click on it and select
"Assign a macro" . Select a macro from the list that is offered to you. A simple
macro to call a userform would look like this:
Sub proUserFormWeighing()
frmWeighing.Show
End Sub
You can assign a VBA macro to a text box and also to a WordArt, a picture or
any other shape from the "Drawing" toolbar.
Once a button (image, word art or text box) has been assigned a macro or an
hyperlink you need to select it with a right click to modify it.
Download one of these buttons (right click on it in your browser and choose
"Save image as"). Save it on your desktop:
Insert the image that you have imported on the first sheet "Insert/Picture/From
File/Desktop/..........gif" . Once the image has been added to the sheet, right click
on the image, select "Assign Macro" and select a macro from the list. Click "OK" .
You can "borrow" all kinds of buttons from the Internet or create your own from
the "Design" toolbar and use them as triggers for your VBA procedures.
In Excel you can run an Excel VBA macro by going to the menu
"Tool/Macro/Macros.." then select the macro from the list and click "Run" .
Open many workbooks with macros in them. When you go to the menu
"Tool/Macro/Macros.." you will notice that you have access to all the macros
from all the open workbooks. This means that you can store ALL your useful
Excel macros in a single workbook (call it myMacros.xls) and have access to
them while the workbook is opened. Let's say for example that you have
designed a macro that multiplies the content of a cell by 2. If "myMacros.xls" is
open you can call this Excel macro from any cell in any other workbook that is
open. No need to copy your essential macros in all your workbooks just open
myMacros.xls and put them to work.
Other Events
VBA for Excel Lesson 10: VBA Security and Protection in Excel
Sometimes you send a workbook with macros to a colleague. If he can't get them
to work it is probably because his security setting is at "High" . Just tell him how
to change his level by going to the menu bar "Tools/Macros/Security" and follow
the instruction.
Each time you open a workbook that contains macros the following dialog
window will appear.
Adopt the same attitude as you have with documents attached to Emails. If you
know the origin of the file you may enable the macros if not click on "Disable
Macros" and you are fully protected. You can look at the workbook but the VBA
procedures (macros) are not operational. You can go to the Visual Basic Editor to
take a look at the macros. If nothing looks suspicious close the workbook and re-
open it enabling the macros.
As an Excel-VBA Developer you might want to protect your code so that nobody
else may modify it. In the VBE editor go to "Tools/VBAProject
Properties/Protection". Check the box and submit a password. Make sure that
you save the password somewhere that you will remember because cracking
Excel VBA passwords is expensive.
Excel Macros
(Vocabulary)
In the first section you have discovered the Visual Basic Editor and the Macro
Recorder. You have learned how to talk with Excel and how to test your VBA
procedures.
In this section you will discover the programming language itself. You will acquire
vocabulary. There are thousand of words used in VBA. Which ones should you
learn? It all depends on what you want to talk about (workbooks, worksheets,
cells, ranges, message boxes....).
You can do most of what you need to do with a very simple vocabulary of 50
words and both the Macro Recorder and the help files of the Visual Basic Editor
will be helpful in discovering new words.
VBA Lesson 11: Coding Tips
- Always write your code in lower case letters. If the spelling is right, VBE will
capitalize the necessary letters. If it doesn't capitalize any letters.... check your
spelling.
- If you want to enter the name Peter in a cell you will write:
Range("A1").Value= "Peter"
But if you want the name "Peter" (between quotes) you need to double the
quotes write:
Range("A1").Value= ""Peter""
This tip applies to message boxes and userforms.
Add comment to your VBA procedures to make them easier to understand. Any
line of code that starts with an apostrophe is considered a comment and the font
will be green in the code window like in:
' In this section we do this and this
You can also add a comment at the end of any line of code by adding a space at
the end of the line then a comment preceded by an apostrophe like in:
Range("A1").Value= ""Peter"" ' Entering a first name between quotes
- All VBA procedures (macros) start with Sub with a set of parentheses at the end
Sub proWhateverName()
I always use the prefix "pro" at the beginning of a procedure and I use upper
case letters at the beginning of a new word in the name of the procedure like in
proWhateverName above or like in proAddData
- A VBA procedure always end with End Sub but you can always exit a
procedure at any point with:
Exit Sub
- All VBA sentences must be on a single line. When you need to write long
sentences of code and you want to force a line break to make it easier to read
you must add a space and an underscore at the end of each line. Here is an
example of a single sentence broken into 3 lines:
In Excel a chart will not show the data of hidden rows (records) and columns
(fields). Knowing this fact you can develop a very simple macro that hides and
unhides rows and columns making your charts dynamic.
VBA Lesson 12: VBA for Excel for the Application
ScreenUpdating
When you don't want to see your screen follow the actions of your VBA
procedure (macro), you start and end your code with the following sentences:
Application.ScreenUpdating = False
Then at the end:
Application.ScreenUpdating = True
DisplayAlerts
When you don't want Excel to ask you things like "A file already exists....." or "Do
you wan to save this file..." you will use the following line of code at the beginning
of your VBA procedure.
Application.DisplayAlerts = False
Then at the end:
Application.DisplayAlerts = True
You can also use the DisplayAlerts method anywhere within your macro. If for
example you don't want to see a specific alert but you want to see the other ones
use the False just before one line and the True just after.
NOTE: If you use the False argument of DIsplayAlerts Excel will never save any
workbook that you close. So if you want to save a workbook before closing it you
will need:
Activeworkbook.Save
CutCopyMode
After each Copy/Paste or Copy/PasteSpecial operation, you should empty the
clipboard with the following line of code to make sure that the computer memory
doesn't overload.
ActiveSheet.Paste
Application.CutCopyMode=False
ThisWorkbook
ThisWorkbook is the workbook within which your VBA procedure runs. So if you
write:
ThisWorkbook.Save
The workbook within which your VBA procedure ( macro) runs will be saved.
If you want to close the workbook within which your VBA procedure ( macro) runs
without saving it you will write these two lines of code:
ThisWorkbook.Saved=True
ThisWorkbook.Close
When you work with two workbooks you will move from on to the other with:
ThisWorkbook.Activate
Windows("theOtherWorkbookName.xls").Activate
Killing a Workbook
When you have saved a workbook on your disk and you want to remove it from
the hard disk you can use the KILL function:
Kill " C:\myFile.xls"
Note: You cannot kill any workbook that is opened including ThisWorkbook
Colleagues send you their individual database in an Excel workbook and you
want to create a single larger database with all the data. The number of small
databases can vary from month to month and your VBA procedure must be able
to cope with this fact. The procedure must open all the workbooks in a certain
directory and assemble the databases. There is a "FiIeSearch" method to do
such a thing but it will dissapear in Excel 2007. So here is how t do it with "Dir"
which will work now and in Excel 2007. vba-example-conso-databases.xls one
of the 25 Excel Spreadsheets
Colleagues send you their individual table of results in an Excel workbook and
you want to create a single table with all the data. With the same approach as
above using "Dir" and the "PasteSpecial" method here is an example: vba-
example-conso-tables.xls one of the 25 Excel Spreadsheets
Sheets
You cannot select a sheet that is hidden so you will need to write:
Sheets("Balance").Visible= True
Sheets("Balance").Select
and then if you want to hide the sheet again:
Sheets("Balance").Visible= False
The name of a sheet must not have more than 31 characters and cannot include
certain special characters like ? : \ / [ ] . If you don't respect these rules your
procedure will crash. The following lines of code will generate an error message:
Sheets("Sheet1").Name= "Balance and Introduction to Numbers" because
there are more than 31 characters including the spaces
Sheets("Sheet1").Name= "Balance: Introduction" because of the special
character :
Sheets("Sheet1").Name= "" because the name cannot be blank
You cannot go directly from a sheet to a cell on another sheet. For example if the
active sheet is "Balance" and you want tot go to cell A1 of a sheet named
"Results" you cannot write:
Sheets("Results").Range("A1").Select
You must take two steps:
Sheets("Results").Select
Range("A1").Select
Activate, Add, Copy, Delete, False, Paste, Select, Sheets, True, Visible,
Worksheets, xlHidden, xlVeryHidden, xlVisible
VBA Lesson 15: Moving around the Worksheet in VBA for Excel
A lot of VBA beginners start their career using Cells. For example:
Cells(1,1).Select is the same thing as Range("A1").Select and
Cells(11,31).Select is the same as Range("AE11").Select.
I strongly recommend that you use Range instead of Cells to work with cells and
groups of cells. It makes your sentences much clearer and you are not forced to
remember that column AE is column 31.
The only time that you will use Cells is when you want to select all the cells of a
worksheet like in:
Cells.Select
To select all cells and then to empty all cells of values or formulas you will use:
Cells.ClearContents
To select a set of contiguous cells you will use the colon and write:
Range("A1:G5").Select
To select a set of non contiguous cells you will use the comma and write:
Range("A1,A5,B4").Select
To select a set of non contiguous cells and a range you will use both the colon
and the comma:
Range("A1,A5,B4:B8").Select
Offset
The Offset property is the one that you will use the most with Range to move
around the sheet. It is the very important property that allows you to move right,
left, up and down.
As you notice the first argument between the parentheses for Offset is the
number of rows and the second one is the number of columns. So to move from
A1 to G6 you will need:
Range("A1").Offset(5,6).Select
Here is a piece of code that you will use very often. It selects a cell and 4 more to
the right to be copied/pasted somewhere else:
Range(ActiveCell,ActiveCell.Offset(0,4)).Select
Notice the comma after the first ActiveCell and the double closing parentheses
before the Select.
In VBA for Excel the message box (MsgBox) is the primary tool to interact with
the user. You can use it to inform, alert or ask the user (with a Yes/No message
box) if he is sure that he wants a certain critical procedure to run (deleting
things).
The code in VBA for Excel to generate the following basic message box is:
MsgBox "Thank you"
If you want part of your message to be between quotes you need to double the
quotes as in:
The line of code would be:
MsgBox "The result is in cell ""A1"""
If you don't want to show the cell's address but its value as in:
Input Boxes
To really get the most out of VBA working with databases you must master these
functionalities in Excel. Visit the website on Excel and study the sections on
databases and database functionalities.
When you work in an Excel database you must first make sure that all filters are
off. To this end you will start your procedure with these two "If" statements. First
select any cell within the database.
Range("A3").Select
If ActiveSheet.AutoFilterMode = True Then
Selection.AutoFilter
End If
Knowing that a database in a set of connected rows and columns you can select
it all with:
Range("A3").Select
Selection.CurrentRegion.Select
Once this is done, you can count the number of rows (records) and the number
of columns (fields) and store these values in variables or in other cells for future
reference with the following code:
varNbRows=Selection.Rows.Count
varNbColumns=Selection.Columns.Count
Range("A1").Value=Selection.Rows.Count
Range("B1").Value=Selection.Columns.Count
In fact the number of records is the number of rows minus one (the title row) and
here is the code:
varNbRecords=Selection.Rows.Count - 1
I never write the code for filtering a set of data I use the macro recorder and then
modify the code.
After you have written a macro and VBE has helped you correct most the
errors...after you have tested you macro there might still be error messages
generated and you or the user will end up seeing this window:
This window is no problem if you or close colleagues are the only users of the
workbook. But in other rare cases where you distribute your workbooks to many
users you will probably prefer to have a more useful error message.
A VBA procedure usually runs from Sub to End Sub. In a VBA procedure that
includes an error handler it will run from Sub to Exit Sub but if there is an error
happening during the execution it will jump to a special address where the error
handler resides.
So to add error handling capabilities to any of your VBA procedures you follow
these steps:
1- Add an Exit Sub right before End Sub
2- Between these two lines add an address ending with a colon (addJump: for
example)
3- Make room between the address line and End Sub to enter your code
handling the error.
4- At the beginning of your code enter On Error GoTo addJump
5- As in the example below the error handler can be a message box giving your
coordinates to the user: MsgBox "An error has occurred, call Peter at 1 613-
749-4695 "
Example 1:
Sub proTestErrorHandler()
addJump:
Copy/Paste the examples in a module of your own and run them. As the
workbook xxxxxx can't be found you will see a message box saying An error has
occurred, call.......... .
A variable is an object that you create and in which you can store text, dates,
numbers or almost anything else. Why should you use variable? The first good
reason is to make your code dynamic, to avoid hard coding some values.
You are dynamically coding when you enter the name of the file in a cell (A1) of
your excel sheet and you write.
varWorkbook=Range("A1").Value
Workbooks.Open varWorkbook
At this point you or the user can change the value in cell A1 and open any
workbook.
You will create variables to count the number of rows, store the result in a
variable and then do something as many time as there are rows. In a new
workbook enter values in cells A1 to A10 then Copy/Paste the following
procedure in a module and try it (Go to "Tools/Macro/Macros" select "proTest"
and click on "Run"):
Sub proTest()
Dim varCounter
Dim varNbRows
Range("A1").select
varNbRows=Selection.CurrentRegion.Rows.Count
End Sub
Enter numbers in cells A1 to A:1000 or A1 to whatever row and try it again
I use variables in 99% of my procedures and you will do the same to reduce the
number of hard coded values. Maintenance becomes so much simpler.
A lot of visitors ask me how they can delete the entire lines when a certain cell is
empty. First enter xxx where you want the loop to stop. Select the cell at the top
of the column and run this macro.
Sub proDelete()
Range("A1").Select
End Sub
Exiting a Loop
If in the loop above you want the loop to stop when it finds the value 99 you
can add this line of code within the loop:
If Selection.Value = 99 Then Exit Do
Discover More in the Downloadable Lesson including:
Learn more about "Do/Loop" "Until" or "While", more about using counters in
"For/Next" loops and more abour "ElseIf" and "If/Not", more about...
When the number of conditions is important you will move away from the "IF"
statement and use the "Select/Case" statement. See how in "vba-example-
select-case.xls" one of the 25 Excel Spreadsheets
Let's say that you need to go down a certain number of cells withinin a certain
number of columns to perform a certain operation. You need to nest two
"FOR/NEXT" loops. See how it is done in "vba-example-nested-for-next.xls"
one of the 25 Excel Spreadsheets
A lot of visitors ask me how they can delete the entire lines when a certain cell is
empty. First enter xxx where you want the loop to stop. Select the cell at the top
of the column and run this macro.
Sub proDelete()
Range("A1").Select
End Sub
Exiting a Loop
If in the loop above you want the loop to stop when it finds the value 99 you
can add this line of code within the loop:
If Selection.Value = 99 Then Exit Do
Discover More in the Downloadable Lesson including:
Learn more about "Do/Loop" "Until" or "While", more about using counters in
"For/Next" loops and more abour "ElseIf" and "If/Not", more about...
When the number of conditions is important you will move away from the "IF"
statement and use the "Select/Case" statement. See how in "vba-example-
select-case.xls" one of the 25 Excel Spreadsheets
Let's say that you need to go down a certain number of cells withinin a certain
number of columns to perform a certain operation. You need to nest two
"FOR/NEXT" loops. See how it is done in "vba-example-nested-for-next.xls"
one of the 25 Excel Spreadsheets
VBA Lesson 22: External Data and SQL in VBA for Excel
SQL is the language used to extract data from a database through a query. Do
you need to learn SQL....the answer is NO.
Here is a basic piece of code to connect to an Access database and extract data
using SQL. Detailed explanations follow the code and you can download the
database for FREE to test the procedure:
Sub proSQLQuery1()
Dim varConnection
Dim varSQL
Range("A1).CurrentRegion.ClearContents
With ActiveSheet.QueryTables.Add(Connection:=varConnection,
Destination:=Range("A1"))
.CommandText = varSQL
.Name = "Query-39008"
.Refresh BackgroundQuery:=False
End With
End Sub
In the first two lines I create two variables. I will later store the connection to the
database in varConnection and I will store the SQL sentence in varSQL.
For the varSQL the best way is to make friends with your Database Manager
(DBA) who will write them for you. If he is a good friend he will even develop a
stored procedure (that runs more rapidly because it runs on the main server). If
you don't have a DBA or cannot make friends with him/her you can use the
macro recorder again. You can also use Access as SQL writer.
The 5 lines starting with With and ending with End With are the lines that you
will use in ALL your procedures just changing the "Name" of the query.
Click here to download (FOR FREE) the small Access database. Save it on
your "C" drive. Copy/Paste the VBA procedure above in the visual Basic Editor of
a new workbook and try it. Make sure that the line starting with "varSQL=" is on a
single line without any break.
I have been using this very procedure for all the projects where I have to get data
from an outside source. I modify the connection, I modify the SQL sentence, I
modify the name and that is it.
With Excel 2007 I add two extra lines not to have to enable the links when I open
the workbook and to remove the new "Table" functionalities that I don't use for
now and that give me problems with my SUMPRODUCT functions. Don't forget
to change the name of the ListObjects.
ActiveSheet.ListObjects("Query-39008").Unlink
ActiveSheet.ListObjects("Query-39008").Unlist
Learn about Date, Day, Hour, Minute, Month, MonthName, Now, Round, Second,
Time, Trim, Year and other important functions like "Kill"....
If you try to copy/paste an SQL sentence from Access or any Query Analyser the
result is a mess
Ses how easy it gets when you use NotePad to prepare the copy/paste step in
"vba-sql-1.xls" one of the 25 Excel Spreadsheets
Dynamic Criteria
In the procedure above the criteria for the month "January" and for the product
"Skates" are hard coded. You would like to use a drop-down list in the Excel
workbook to select a criteria and execute the query with the selected value.
Excel Functions
Some of the functions that you find in Excel are available through macros in this
form:
Range ("C1").Value=
Application.WorksheetFunction.Sum(Range("A1:A32"))
this sentence sums the values of cell A1 to A32 and stores the total in cell C1.
VBA Functions
Here are two VBA functions that you will use within your Excel macros:
LCase, UCase
The "IF" statements are case sensitive. When you test a string of characters and
you don't know if the user will enter upper case or lower case letters, use the
LCase or UCase functions within your "IF" statement so that however the user
enters his answer the statement will work.
If LCase(Selection.Value)= "yes" then...
or
If UCase(Selection.Value)= "YES" then...
You can create new functions in Excel. For example the function created by the
code below will simply multiply the value of a refered cell by 2.
Function fctDouble(varInput)
fctDouble = varInput * 2
End Function
Once this code is in a module in your workbook you access the new function the
same way that you access the other functions in Excel by clicking on the icon
function on the tool bar or from the menu bar "Insert/Functions".
Add the above new function to a new workbook. Enter 6 in cell A1 and insert the
new function in cell B1 (in the dialog box select the "User Defined" category and
select the new function ("fctDouble") and enter A1 as varInput. The result is 12.
Learn about Date, Day, Hour, Minute, Month, MonthName, Now, Round, Second,
Time, Trim, Year and other important functions like "Kill"....
VBA Lesson 23: Working with other Programs in VBA for Excel
API
To delete a file from a disk you can also use the Kill function that is not an API.
Within Excel you can open another program and even act within it using VBA.
For example here is a short macro that opens Word, then a new document to
copy/paste the content of 2 cells from Excel to word and save the word document
in the same directory as the workbook in which the macro runs:
Sub proWord()
Dim varDoc As Object
varDoc.Visible = True
Sheets("Sheet1").Range("A1:b1").Copy
varDoc.documents.Add
varDoc.Selection.Paste
varDoc.activedocument.SaveAs ThisWorkbook.Path & "/" &
"testWord.doc"
varDoc.documents.Close
varDoc.Quit
End Sub
Notice that you use VBA for Word within the object varDoc. If you don't know
VBA for Word remember that there is also a Macro Recorder in Word. The object
varDoc can be visible or you can work within it without bringing it on screen with:
varDoc.Visible = False
So from Excel you can work with Windows (API's) and with Word, Access,
Project, NotePad, Power Point, etc.
When the message box or the input box are not sufficient anymore to
communicate with the user you need to start developing userforms.
The form or userForm is also known as a GUI (Graphical User Interface). The
form is used to require values, parameters and information from the user to feed
the VBA procedure. Different basic controls can be added to the userform they
are called: Label, TextBox, ComboBox, ListBox, CheckBox, OptionButton,
Frame, CommandButton, SpinButton and Image . You can find all kinds of
other controls on the Internet but the problem is that if you send your workbook to
other people and the new control is not installed on their computer it wont work.
This problem might even occur with the calendar. To learn more about all the
controls see lessons 26 to 33.
Tab Order
Once you have added the controls here is an important feature. The user can
use the mouse to move from one control to the other but he should also be able
to move from one control to the other by entering a value in one and clicking
"Enter"or "Tab" and the focus will be set on the next control where he is
supposed to enter a value not on a label. More importantly when the user enters
a value in the final control you ant the focus to be on the right command button
(Submit) and not on another one like "Close Form".
To make sure that the user moves from one control to the next one in a set order
you need to set the tab order. To do so, right click on the form itself and select
the "Tab Order" item. Follow the instructions. The first control in the list will be the
one that is active (flashing cursor within) when the form is activated. Bring the
controls that are not to be used by the user (labels) at the end of the list. For the
controls that are not to be used you can also set the "TabStop" property of the
individual control to "False" in the properties window.
Managing Controls
You can move the controls by clicking on them holding and moving them around.
You can resize them by selecting them and using the different handles around
them. You can copy or cut them by right clicking on them and choosing the right
menu item.
Once you have added your controls you might want to align a few of them or
resize a few so that they are all the same size. To do so you first need to select
many controls at the same time. To do so left click on the form near one of the
controls that you want to select. Hold and drag drawing a frame that includes
many controls.
When you let go of the button all the controls that are touched by the frame are
selected.
Right click on any of the selected controls and this contextual menu appears:
You can then align the controls (7th menu item) or make them the same size (8th
menu item).
Discover the userform properties and the VBA code to work with it in lesson 25
so that among other things when you activate the userform all the list boxes and
combo boxes get initialized.
As you have seen in lesson 1 on the Visual Basic Editor you double click on the
userform's name in the Project window and its properties appear in the
Properties window:
In the Properties window of the VBE you MUST change the name "(Name)" of
the form, its caption (the name in the blue band at the top of the UserForm) and
you can also modify the default setting of any of the 32 other properties of the
form.
When you name a form always use the prefix "frm" like in "frmDatabase" and be
as descriptive as you can be so that your code will be easy to read. Always use
one or more upper case letters in the name. When you write "frmdatabase.show"
in lower case letters Excel will capitalize some letters "frmDatabase.Show" letting
you know that the name is spelled correctly.
The caption is what your users will se at the top of the userform. Be as
informative as possible and complete the information with a label if necessary.
Else than the Name and Caption there are just a few properties that you might
want to modify. You can select a different color for the background with the
property "BackColor" .
By default the userform appears in the center of the screen. If you want it to show
somewhere else set the "Start" property to "0-Manual" and use the "Top" and
"Left" properties to set a new position.
The Code
The first thing to do is to create code to call your userform. Here is a basic line of
code doing so:
frmCity.Show
See lesson 9 on Events to learn how to assign macros to a text box or other
button that you place on the sheet.
The "Hide" sentence is usually part of the code of a command button on the
form. A user clicks on a "GO" , "SEND, "SUBMIT" or "CANCEL" button and part
of what must happen is that the userform disappears from the screen.
In the toolbox the label has this icon . The label is a passive control meaning
that the user never really acts on it. It is there to inform the user and to label
other controls like text boxes, combo boxes or list boxes.
Properties
The other interesting properties of the label are:
- TabStop: To make the control invisible for the "Tab" and "Enter" keys (see Tab
Order) set this property to "False" .
- WordWrap: If you want to write more than one line of text in a label set this
property to "True" .
Code
There is not much coding developed for the labels although there are 8 events
related to the label. For example there is an event named "MouseMove" . If you
develop code within this event it is executed when the mouse moves over the
label. If the code is the following:
MsgBox "Don't forget to..."
a message box will appear when the user moves the mouse over the label.
You can stack many labels one over the other and make their "Visible" property
to "False" . You can then make any of the label visible from an event related to
another control. For example if a user chooses a certain value in a combo box a
certain label appears.
The text box is the simplest control to require an entry from the user. The user
types something in it and this value can then be used in your VBA procedure.
You will usually add a label to accompany the text box.
For most controls including the VBA for Excel text box there are general
properties that allow you to set the font, the color of the font, the color of the
background, the type of background, the type of border and other design
features. Using the 3 windows in the Visual Basic Editor you will see the
following properties in the "Property" window when the text box is selected.
Properties
Code
The most important thing to remember is that a text box is what its name says it
carries text. So if you want to send a numerical value from a text box to a cell you
must use the "Value" thing:
Range("A1").Value=tbxInput.Value
In the toolbox the command button has this icon . The command button is a
very active control and there is always VBA code behind it.
The command buttons are usually placed at the bottom of the form and serve to
complete the transaction for which the form has been created. The caption of
these buttons are usually "Go" , "Run" , "Submit" , "Cancel" , etc.
Properties
Code
Name your command button before developing your code. VBA uses the name
of the command button when it creates lines of code related to events. So if you
don't name your command button VBA will create the private sub::
Private Sub CommandButton1_Click()
as if you name the command Button "cmbSubmit" for example the private sub
will start with:
Private Sub cmbSubmit_Click()
If you name your command buttons after private subs have been created they
won't work anymore.
A very simple VBA procedure for the command button would look like this:
The content of the combo box "cbxInput" is entered in cell "F1" of the sheet
"Code" and the form (frmPassport) is closed.
The difference between a combo box and a list box is that the combo box is a
drop-down list and the user can submit a single value from the drop-down list.
The list box shows a certain number of values with or without a scroll bar and the
user can select one or more values.
When you double click on the combo box in the Visual Basic Editor you will see
all its properties in the Properties window .
No programming is needed to submit the list of values that will be offered to the
user within the combo box. Look for the RowSource property.
The values that should appear in the drop-down list of the combo box are
submitted in the RowSource property. For example if the value of the
RowSource property is Balance!A1:A12 The values residing in cell A1 to A12 of
the sheet named Balance will be offered as choices to the user who clicks on the
small arrow of the combo box.
The rules to submit the RowSource property is the name of the sheet where the
list resides followed by an exclamation point (!), the address of the first cell, a
colon and the address of the last cell.
You want the second combo box to offer a choice of values that differs based on
the choice made in the first combo box. We call it cascading combo boxes. In
"vba-tutorial-combo-box.xls" (one of the 25 spreadsheets) you will discover
how to develop such pairs of combo boxes.
The difference between a combo box and a list box is that the combo box is a
drop-down list and the user can submit a single value from the drop-down list.
The list box shows a certain number of values with or without a scroll bar and the
user can select one or more values.
No programming is needed to submit the list of values that will be offered to the
user within the combo box. Look for the RowSource property.
The values that should appear in the drop-down list of the combo box are
submitted in the RowSource property. For example if the value of the
RowSource property is Balance!A1:A12 The values residing in cell A1 to A12 of
the sheet named Balance will be offered as choices to the user who clicks on the
small arrow of the combo box.
The rules to submit the RowSource property is the name of the sheet where the
list resides followed by an exclamation point (!), the address of the first cell, a
colon and the address of the last cell.
In the toolbox the option button has this icon , the check box has this one
and, the frame this one .
You don't need to add a label to accompany the check box or the option button
because they come with their own.
The check boxes and the option buttons are both used to offer the user a choice.
The main difference between check boxes and option buttons is that if you have
5 of each on a form a user can check all 5 check boxes but can only select one
of the option buttons.
If you want to create two sets of option buttons read below on frames and option
buttons. If you don't want to use frames to create groups of option buttons you
will need to use the "GroupName" property of the option buttons. All option
buttons with the same GroupName work together.
Properties
Frames
Frames are also a passive control. Frames are used to improve the layout of the
userform. You can use them around a group of controls that have something in
common.
Frames become more important to manage option buttons. If you have two sets
of option buttons on a userform and you don't place them within a frame they all
work together and you can choose only one. If you put each set within a frame
you can choose one in each set.
When you move a frame all its controls move with it.
Spin Button
You can ask a user to enter a value directly in a text box but you can make things
a little fancier by using a text box and a spin button.
The spin button is not really used by itself. Because the spin button doesn't show
its value it is usually used with a text box. The text box shows a number and by
clicking on the arrows of the spin button the value in the text box is increased (or
decreased) by 1, or 5 or 10...by whatever value that is set within the properties of
the spin button.
Properties
Spin Button
You can ask a user to enter a value directly in a text box but you can make things
a little fancier by using a text box and a spin button.
The spin button is not really used by itself. Because the spin button doesn't show
its value it is usually used with a text box. The text box shows a number and by
clicking on the arrows of the spin button the value in the text box is increased (or
decreased) by 1, or 5 or 10...by whatever value that is set within the properties of
the spin button.
Properties
Image Control
There is a control in the toolbox called "Image". Within this control you can show
all kinds of pictures. You set an image control on a userform and you submit a
picture in the property "Picture". The picture becomes part of the control and
userform.
The first thing that you want to do is to fit the picture in the image control to make
the size of the control adapt to the size of the picture.
When you are in the Visual Basic Editor and you single click on an image control
a frame appears around it with 8 stretchers (picture below). If you double click on
the middle stretcher (when a two tips arrow shows) of the right side or on the
middle one at the bottom or on the bottom right corner stretcher the image
control will adapt to the size of the image. Double clicking anywhere else will take
you to the VBA code and will not adapt the control size to the picture size.
PictureSizeMode Property
See how you can do that with all the step by step programming instructions in
"vba-form-image-control.xls" (one of the 25 spreadsheets). Coupled with a
combo box you can develop an interesting selector using pictures to make the
choices easy (image below).