Upload
others
View
105
Download
1
Embed Size (px)
Citation preview
VBA Starter Training Course
Visual Basics for Applications for Beginners Page | 2
2 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Copyright © 2013 Trevor Easton Online PC Learning
Author Trevor Easton
All rights reserved. No part of the contents of this book may be reproduced or
transmitted in any form or by any means without the written permission of Trevor
Easton.
For support related to this book, email Online PC Learning Support at
The example companies, organizations, products, domain names, email
addresses, logos, people, places, and events depicted herein are fictitious. No
association with any real company, organization, product, domain name, email
address, logo, person, place, or event is intended or should be inferred.
This book expresses the author’s views and opinions. The information contained
in this book is provided without any express, statutory, or implied warranties.
Trevor Easton nor Online PC Learning will be held liable for any damages caused
or alleged to be caused either directly or indirectly by this book.
Visual Basics for Applications for Beginners Page | 3
3 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Visual Basics for Applications for Beginners
Foreword 9
Why I have written this information 9
How to use this e-book 9
Companion Excel Workbook Resource 11
Resource Workbook Contents 11
Chapter 1: What can you do with VBA? 13
OVERVIEW 13
Run a simple test 14
Reduce staff costs 15
The benefits 15
Chapter 2: Understanding the Visual Basic Editor 17
OVERVIEW 17
Basic VBE Components 17
VBE Project Explorer 18
Saving the Workbook 20
The Properties Window 21
Understanding Modules 22
Procedures Window 23
Chapter 3: What is the VBA object based language 27
OVERVIEW 27
Let’s go Camping 27
Understanding Objects 27
Object Properties 28
Is there Method in your Methods 29
What are Events? 30
Chapter 4: Recording your first macro 33
OVERVIEW 33
Where Do I Start? 33
What can I record? 34
The Developer Tab 34
Allowing Macros in your Workbooks 34
Record our first macro 36
Run the macro from the VBA editor 37
Visual Basics for Applications for Beginners Page | 4
4 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Test your new skills at recording macros 39
Chapter 5: Working with VBA (learning to speak the language) 41
OVERVIEW 41
Adding a Module 41
Adding a Userform 43
Code Keywords 44
Entering code 45
Relative and absolute references 48
Line-continuous character 48
Stepping through the code 48
Chapter 6: How to use Variables in VBA 53
OVERVIEW 53
Naming a variable 54
Why use variables? 55
Declaring variables 55
What is a data type? 56
What is the scope of a variable? 57
Chapter 7: IF Statement and Decision Modelling 59
OVERVIEW 59
Decision Modelling 59
If – Then Constructs (True) 60
Single If-Then 61
Multiple If-Then constructs 61
If–Then End If 62
Multiple If - Then - End If 62
If – Else (True, False) 63
If – Then - ElseIf – Else 65
Nested If - Then - Else 66
If – And –Then 66
If – Or – Then 67
If – Not – Then 68
IIf Function 68
Chapter 8: Select Case Constructs 71
OVERVIEW 71
Benefits of the Select Case function 72
Visual Basics for Applications for Beginners Page | 5
5 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Syntax 72
Select Case - (Single condition) 74
Select Case - (Multiple conditions) 74
Select Case – Else 75
Multiple Conditions (Comma separator) 75
Multiple Conditions Between (To) 76
Combining Multiple Conditions (To + Separator) 76
Using Operators with Select Case 77
Select case and Text Conditions 77
Option Compare Text 78
Combining Numbers and Text Conditions 79
Combining Select Case (Magic combinations) 79
Chapter 9: Excel VBA Message Boxes 81
OVERVIEW 81
Let your applications speak for themselves 81
Microsoft Excel’s use for message boxes 81
Simple VBA message box 82
Constants available to the message box function 87
How it all works behind the scenes 89
Multiple lined Message Boxes 89
Message Boxes Examples 90
Chapter 10: Understanding the Input box construct 95
OVERVIEW 95
Why use an Input Box 96
Input Function 97
Input Method 97
Type argument 98
A Simple Input Box 98
VBA Examples 99
Create a User Login 99
Collect employee age 102
BMI Calculator 104
Working with Ranges (Input Method for Objects) 106
Chapter 11: Understanding VBA loops by Examples 107
OVERVIEW 107
Do Loop 108
Visual Basics for Applications for Beginners Page | 6
6 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Do Until Loop 109
Do While Loop 110
For Loop 111
For Each Loop 115
Nesting Loops 117
Chapter 12: Basic Error Handling 121
OVERVIEW 121
Why Use Error Handling? 121
How to Configure Error Settings 122
How to Reset Errors 122
Three Types of VBA Errors 123
When to use error handling 125
What is the VBA Debug? 125
Understanding the On Error Statement 126
VBA Resume Statement Explained 131
Chapter 13: Build your First Userform Database 135
What is a Userform? 135
Userform Project 136
Insert a Userform 138
Userform Properties 138
Toolbox 139
Adding Controls 140
Writing the VBA Code 145
Writing our code 146
Set up the Database Worksheet 150
Test the userform with data 151
Setting up The Interface 151
Running the advanced filter 152
Chapter 14: Developing your first Application 155
How do we develop bullet proof Excel Applications? 155
Where do I start? 155
Great Idea – Bad Design 156
I’m going to share with you my recipe for success. 156
In the line of fire 156
Visual Basics for Applications for Beginners Page | 7
7 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
In Conclusion 162
Appendix - Macros in this eBook 163
Message Box Macros 163
Variable Scope 163
If Function Macros 164
Select Case Macros 168
Message Box Macros 172
Input Box Macros 175
Loops Macros 180
My Tax Receipt Macros 192
VBA for Beginners: Features Page | 8
8 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
VBA for Beginners: Features
190 Pages: Step by Step Training
Written In language the beginner can understand
This learning guide has been written for the VBA beginner. I have tried to break all of the learning down to the basic building blocks required to understand Visual Basic for Applications.
More than 130 full colour illustrations
To add to an easy learning experience I have added over 130 full colour illustrations, many with notes and diagrams to highlight the necessary steps required to learn effectively.
Macros
After you have read this publication you will be returning to find code to use in your future applications. For this reason I have added all of the key macros at the end of the publication. They are listed under the function they belong too. This will save a lot of time when you return to the publication.
Five Projects to complete
In harmony with the spirit of Online PC Learning, that project based learning is a fast and effective learning path. I have included projects throughout the eBook. This will give you the chance to practice your skills as you go.
1. User Login
2. My Age Calculator
3. BMI Calculator
4. My Tax Receipts
Companion Resource Workbook
Along with this eBook you will receive a companion Excel file that is set up to demonstrate many of the chapters within.
Foreword Page | 9
9 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Foreword
Why I have written this information
The chapters in this book and the accompanying files will enable you to
quickly grasp the basics of VBA in Microsoft Excel. There is a lot of
published information on the web that deals with the learning Visual Basic
for applications. Often a newcomer becomes lost with the complexity and
randomness of the information provided.
I have presented the chapters in such a way that each chapter will set the
basis for the next chapter so that you can progressively learn the visual basics
for Applications.
Based on my own learning experience and the questions I asked on Online
P See Learning, these chapters should cover all that is necessary to get you
up and running and developing some awesome VBA code.
There are illustrations throughout the chapters to demonstrate all the key
points that are presented.
How to use this e-book
Go through the book chapter at a time. If you feel you fully understand all the
concepts in each chapter then move to the next chapter.
Open the companion Excel workbook resource file that is provided and view
and run the code that are provided as examples and test it out in your
computer.
You will remember concepts more easily if you use them in a file rather than
just read how to go about achieving the desired result.
Best wishes with your learning endeavors
gÜxäÉÜ XtáàÉÇgÜxäÉÜ XtáàÉÇgÜxäÉÜ XtáàÉÇgÜxäÉÜ XtáàÉÇ
Not everybody learns the same way. Some people like learning by rout from books and in many situations that may be necessary. But that’s not me. I am a visual learner and I learn by associating tasks.
We will be learning by examples
Companion Excel Workbook Resource Page | 11
11 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Companion Excel Workbook Resource Along with this eBook you will receive a companion Excel file that is set up to
demonstrate many of the chapters within.
Resource Workbook Contents
o Interface If Function
o Case Function
o Input box function
� My Age Calculator
� BMI Calculator
o Loops
o Error Handling
o Userforms
� My Tax Receipts
As you can see above there are also 3 completed applications.
Chapter 1: What can you do with VBA? Page | 13
13 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Chapter 1: What can you do with VBA?
OVERVIEW
• Automating business processes
• Obtain accurate data analysis
• Reducing labor costs
• Increase job satisfaction
Almost anything that you can do manually in Excel you can do with VBA and
in a fraction of the time normally taken. When the code is written or recorded
it can be executed time and time again in a number of ways.
You can grab objects, workbooks, worksheets, ranges charts and shapes
and do almost anything with them in a fraction of a second.
In fact you can do more with VBA procedures than you can do manually in
many instances. Some tasks can only be accomplished with code.
VBA is an object based language and VBA Macro or procedure is simply a
set of instructions to manipulate objects.
• Format a worksheet
• Add data validation
• Create a chart
• Activate a pivot table
• Filter large data ranges with multiple criteria
• And lots more
Speed up processes
Tasks that would normally take a very long time to do can be accomplished
in just a few seconds.
VBA is an object based VBA is an object based VBA is an object based VBA is an object based language and VBA language and VBA language and VBA language and VBA Macro or procedure is simply a set of Macro or procedure is simply a set of Macro or procedure is simply a set of Macro or procedure is simply a set of instructions to manipulate objects.instructions to manipulate objects.instructions to manipulate objects.instructions to manipulate objects.
Chapter 1: What can you do with VBA? Page | 14
14 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Run a simple test
For many years now, to demonstrate the power of Excel 2003 I have
highlighted all of the cells on a worksheet by clicking in the box diagonally to
the left and above cell A1 on a spreadsheet. Then type a number and press
Ctrl + Shift + Enter. This would insert the number into the approximately 16
million cells on the worksheet.
Execution time varies with computers but the job is done in about 3 to 4
seconds. The point that I would make is that if you were to type a number
into 1 cell at a rate of 1 per second and did that 24 hours a day, 7 days of
the week, it would take about 180 days to complete the task.
We just did that in 3 seconds!
From 2007 onwards the columns and rows increased to 1048576 rows and
16384 columns which is equal to 17,179,869,184 cells on each sheet. If you
tried to do that, there would not be the available resources necessary to
accomplish the task.
If you were to highlight just the first 20 columns which is 20,971,520 cells
and then add a number the way I have described it would take about 6
seconds for the 20 million cells to be filled.
Here is the code to do that. Don’t save your work if run this experiment as
the file will be about 55 mb in size.
Sub AddNumber()
Columns("A:T")= "8"
End Sub
Can VBA save you time? The answer is yes, and lots of it.
Analyze data
Now let’s look at a more practical example.
As an example let’s say you have a large data set with 30 columns as
headers and 5000 rows deep and you want to filter that data based on some
multiple criteria. That is easy enough to do with the advanced filter that Excel
offers. The problem is every time you want a result you need to set up the
filter to run with the new data and criteria.
With a small piece of code, that laborious task is no longer necessary, you
just click a button and the filter is automatically set for you. Then add a
simple variable and the criteria can be changed depending on the option
selected by the user.
Chapter 1: What can you do with VBA? Page | 15
15 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Reduce staff costs
Repetitive tasks
Anything that you do in Excel on a regular basis is a good candidate for a
VBA procedure.
Two real examples
Example 1
A hospital with 20 wards has staff in each ward working four hours a week to
put together a list of all the staff working on each day and each shift. They
then go to their roster and copy that information to another spreadsheet.
To do this with a VBA procedure takes less than 3 seconds and the same
program is used for all 20 groups. Time saved per week is 80 hours at
approximately $30 per hour which saves approximately $2400 per week.
Example 2
Every morning an activity report needs to be run and sent to the director.
This is a repetitive task that takes one hour. Imagine starting your day with
that ahead of you. This process can be automated with VBA instructions and
performed with just a couple of clicks.
The benefits
1. Better job satisfaction
2. Accurate data
3. Labor savings
If you are paying wages time is money and anything that can save time and
eliminate human error is good business practice.
Chapter 1: What can you do with VBA? Page | 16
16 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Chapter 2: Understanding the Visual Basic Editor Page | 17
17 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Chapter 2: Understanding the Visual Basic Editor
OVERVIEW
In this chapter we will take a tour of the Visual Basic Editor. I will run you
through the standard setup and some of the key options you will need to
understand.
• VBE Project Explorer • Changing the project name • Protecting the code • Saving the Workbook • The Properties Window • Docking and Undocking • Understanding Modules • Modules are filing cabinets • Naming the Module • Procedures Window • Intellisense • Adding comments to your code • VBE Immediate Window • Quick test
Basic VBE Components
SHORTCUT FOR VBE: Alt+F11
To get started let’s open the Visual Basic Editor. (The Visual basic editor is a
program that comes with Microsoft Office)
Open the VBE by holding down the Alt+F11key and enable these windows in
your editor. Click on the View tab and select the windows that you to appear
in the editor.
For a basic setup you should have the Project Explorer / Properties Window
and the Intermediate Window visible as you work. These options are
available from the View tab on the menu bar of the Visual Basic Editor as
illustrated below.
Chapter 2: Understanding the Visual Basic Editor Page | 18
18 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
VBE Project Explorer
SHORTCUT FOR THE PROJECT EXPLORER: Ctrl+R As you look at the Visual Basic Editor you will notice that the name given to
each workbook by the Visual Basic Editor is “Project-VBA Project”.
Below the name in the Project Explorer
the hierarchy or tree with all of the
objects for each project exist. If you
cannot see the Project Explorer then
click on the View tab at the top of the
VBE and click on Project Explorer.
When you single click on each object or
module you select it. You can then right
click to view the shortcut menu and
choose from the options. Options
include opening the properties or
viewing the code or deleting the object.
If you double click an object you will be taken to the code for the procedure
in the VBA Code Editor.
Changing the project name
It is good practice to change the name of the Project to more accurately
reflect what that project does. If you have several workbooks open this will
help you to clearly identify each project.
To change the project name:
1. Right click on the VBA Project
Chapter 2: Understanding the Visual Basic Editor Page | 19
19 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
2. Choose the General tab
3. Add your new name in the box for Project Name
4. Click OK
Protecting the code
If you do not want your precious code altered or perhaps you want to keep it
secret, then you should protect the VBA part of your application.
1. Right click on the VBA project title
2. Select the VBA Project Properties
3. Tick the box next to Lock project for viewing
4. Add your password and confirm it in the text boxes provided
5. Click Save
6. Close and save your workbook
When you next go to the VBA Editor you will need to supply tour password
to open it so do not forget what the password was.
Note:
Protection in Excel Workbooks is not hard to crack. So in essence you will
be protecting your code from the honest and less experienced Excel user.
Chapter 2: Understanding the Visual Basic Editor Page | 20
20 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
Saving the Workbook
In Office 2007, Microsoft changed its file structure for workbooks from a binary (.xls) to a special (Microsoft) .xml format. That is why the file structure changed from (.xls ) to (.xlsx). The x indicating the xml format.
It is necessary to save your file to a .xlsm (Macro enabled) file if you are
using 2007 plus versions. You will be prompted (as shown below) with a
warning and if you continue without choosing .xlsm all of your code will be
deleted from the workbook.
DO NOT CLICK “YES” or all will be lost.
Follow the steps listed below and your work will be fine and safely stored.
Here are the steps:
• File / Save As
• Save as type = .xlsm
• File name = “Add Appropriate”
• Location = Where you want to store the file
• Save = This will execute your options
Chapter 2: Understanding the Visual Basic Editor Page | 21
21 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
The Properties Window
SHORTCUT FOR THE PROPERTIES WINDOW: F4
Objects have properties. In fact all objects have properties. What we mean
by properties is that the object can have a name or a color or a size and so
on. In essence it is a setting for the object.
Think of it as descriptive, like an adjective in English. Properties available to
an object vary depending on the object selected.
You will need to have the properties window readily available. It is possible
to float this window if that is preferable to your development style. I
personally like to have the properties window somewhere on the screen as I
am writing code. It can be floating or docked. This illustration below shows
the floating Project Explorer and the Propertied Window. To float them click
on the top of the window and drag the window to where you want. Notice
here we have Sheet2 selected and the relevant properties are displayed for
that object.
Docking and Floating Windows
Docking means, locking the window into its home position in the Visual Basic
Editor. To undock (float) the window, hold down the left mouse button on the
Chapter 2: Understanding the Visual Basic Editor Page | 22
22 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
title and drag the window to the location of your choice. The main thing is
that you can get to it quickly.
To dock the window to the left hand pane, first maximize the VBE editor then
drag the window to the left hand side of the screen.
Understanding Modules
Modules are the home for procedures. You can add multiple procedures /
macros to a single module. Just as you can have multiple rooms in a home.
Modules are filing cabinets (Modular filing cabinet)
Modules are like filing cabinets for your procedures. A filing cabinet
organizes your paperwork. Open a draw and select the tab for “Rates” and
you should expect of find all of the rate bills. Our Modules serve the same
purpose. When you open the VBE you should quickly be able to locate your
specific procedure by the name of the module.
Naming the Module
You should name a Module to represent the contents that it contains. This is
done in the properties window for that module. Double click on the Module
and then change the name in the properties window.
As an example:
If you put all of the procedures
Chapter 2: Understanding the Visual Basic Editor Page | 23
23 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
that filter ranges into a Module, you could call that Module “MyFilters” or
something descriptively similar. This is like a tab at the top of the Modular
filing cabinet. Don’t put unrelated macros in a named module.
So in summary a Module can contain multiple procedures. It is a good idea
to keep them manageable by categorizing the procedures and limiting the
number within each Module.
Procedures Window
The procedures window or code editor is where you add, view and edit the
VBA code. When you record a macro, the code will appear in this window.
Here is an example of a simple procedure to toggle the sheet tabs visibly.
Sub is short for “Sub Procedure”.
IntelliSense
A great feature that is often overlooked is IntelliSense. IntelliSense appears
when you type a period (Dot) to separate the levels of the object members in
that hierarchy. This will give you a list of members associated with the
object. Double click on the list item to insert it into the code for that
procedure.
This is a list of methods and properties available to the object. If you cannot
find it in the list then it is not available to the object.
Chapter 2: Understanding the Visual Basic Editor Page | 24
24 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
If this feature does not appear to be working for you then go to Tools /
Options / Auto List Members to activate IntelliSense.
Adding comments to your code
Macros can be very long and can be associated with other procedures. It is
a good idea to add comment to your code so that others who view and edit it
can understand what is happening. For me, it is so I can remember what the
code is doing each time I visit it. It is very good practice to add comments
throughout your procedures and name them intuitively.
There are two ways to do this. The most common is to use an apostrophe (‘)
in front of your comment. For example: ‘here is my comment
The second method and now almost extinct is the (Rem) statement. Put the
statement in front of you comment e.g.
Rem here is my comment
When you do this you will notice that that line of code will change color to let
you know it is not part of the executable code.
VBE Immediate Window
SHORTCUT FOR THE IMMEDIATE WINDOW: Ctrl+G
This window is very useful in testing small parts of the code as you are
developing the procedure.
You will be able to use this window with single statements. Simply type in
your statement and press enter. As the name suggests, it will execute the
code immediately.
Quick Test
Here is an example. In cell A5 type the value 11, then in the Immediate
window add a question mark followed by Range("A5")>10. The (?) will print
the answer in the Immediate window. Put the curser inside the code and
Chapter 2: Understanding the Visual Basic Editor Page | 25
25 | P a g e C o p y r i g h t © 2 0 1 3 T r e v o r E a s t o n O n l i n e P C L e a r n i n g
press enter and you will see True appear in the next line in the immediate
window. Because the number 11 is greater than the number 10.
? Range("A5")>10