Beruflich Dokumente
Kultur Dokumente
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.
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 authors 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.
In Conclusion 184
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.
1. User Login
2. My Age Calculator
3. BMI Calculator
4. My Tax Receipts
Foreword
Not everybody learns the same way. Some people like learning by
rout from books and in many situations that may be necessary. But
thats not me. I am a visual learner and I learn by associating tasks.
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.
Trevor Easton
10 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Companion Excel Workbook Resource Page | 11
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.
Sub AddNumber()
Columns("A:T")= "8"
End Sub
Can VBA save you time? The answer is yes, and lots of it.
Analyze data
As an example lets 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.
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.
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
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.
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.
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
2. Choose the General tab
3. Add your new name in the box for Project Name
4. Click OK
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.
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
want. Notice here we have Sheet2 selected and the relevant properties are displayed for
that object.
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 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 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.
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 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. Dont 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.
If this feature does not appear to be working for you then go to Tools / Options / Auto List
Members to activate IntelliSense.
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.
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 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
OVERVIEW
Understanding Objects
Object Properties
Is there method in your Methods
What are Events
I mentioned previously that VBA is an object based language. VBA manipulates objects.
The key to understanding VBA in the Excel application is to understand the relationship
between:
1. Objects
2. Properties
3. Methods
4. Events
Lets go Camping
Here is an illustration that may help. I personally like camping. In fact as I am writing this I
am sitting under the awning of my camper trailer at Burrum Heads on the Frazer coast of
Queensland, Australia. A truly magnificent holiday destination.
To understand the object model take the illustration of a caravan or trailer park.
Understanding Objects
The caravan park has many caravans, some are coming and others are going each day.
Think of the caravan park as a container or Object and each caravan in the park is an
object associated with that park. The caravan park is an object with a collection of member
objects (caravans) inside its area. We can see a hierarchy here because the caravan park
is the main object that contains member objects (caravans). Now let us apply that to
understanding VBA a little better.
The Excel Application is an object and you can add workbooks and then you can add
worksheets to each workbook. The Excel Application can have hundreds of workbooks or
objects each containing different collections of worksheets (objects). Yes, you see it is all
about objects. Adding, moving and manipulating objects.
Now back to our illustration. Each caravan has rooms, a bed, a kitchen, two wheels, a roof
and walls and tables. All of these are objects collected under the caravan object. OK, now
lets take the table and fold it up and put it out of sight under the bed. It is still there but we
cannot see. However we can pull it out and use it anytime we want.
The Excel Workbook has Worksheets and these Worksheets have Ranges, Cells, Charts
and even Pivot Charts. All of these are objects under the Workbook collection. Everything
that you can see is an object. Of course some objects can be hidden out of site but they
are still member objects of that collection and can be unhidden and referenced as we need
them.
Object Properties
The caravans have different properties. Some are longer than others some are different
colors. In fact all of these physical objects have properties. Look inside the caravan at the
objects, the bed has different properties to the table and so on. I think we can see this point
very clearly. Properties are descriptive as adjectives are in the English language. A green
caravan, a pink door, a silver sink they describe the property. You can change the
property of the pink door to white by painting it.
Now in Excel, every object has properties. You just dont notice this because Microsoft sets
most of these properties by default. A worksheet has a different name and set of
properties. These are the properties that you will be changing with VBA or in the properties
window. A chart has different properties to a cell. The beautiful thing is that you can
change these properties with code, if we understand them. Look at the Worksheet
properties below. Can you see how easy it is to change the properties of an object in the
properties window? You can also refer to and change properties with VBA to achieve
remarkable effects. Its like magic.
we going to do this? Well first we need to pull down the annex and unplug the power, move
the car and connect it to the trailer. Then we will tow it to the new site. These are the
methods we will use to accomplish the task. These are the methods available to the object
for moving the object.
In Excel, Methods are also actions. Lets say we want to move a range (object) from one
sheet to another sheet. What methods or actions are available to us? We might select the
data and copy it, then select the destination and paste the data, then clear the contents
from the initial range. These are methods to manipulate the objects involved in the move.
user to a specific area or we could change the properties of the sheet. We can run
procedures from these events.
In the illustration below of a VBA procedure, I am using the Workbook open event to run a
series of actions. When the workbook opens we can set things up for the user.
To find what events are available to the sheet object, first select the object from the drop
down list on the left and then the event from the dropdown list on the right.
OVERVIEW
When it comes to VBA code many people get scared. They labour under the
misapprehension that its too difficult to get started.
Where Do I Start?
Imagine this for a minute. What if someone were to write the code for you? Yes
thats right; write your code for you!!
Microsoft Excel with its macro recorder does just
that. When you turn it on and then perform an
action in Microsoft Excel it records that action
and writes those actions in code.
Let me tell you what I think about the Macro
Recorder.
As you might notice I am quite impressed. It is true that without macros excel can
do phenomenal things. It truly is an awesome program. But if you add the power of
Visual Basic for Applications, it literally takes off into outer space. Being an object-
based language, Excel VBA will allow you to accomplish almost any task. YES
ALMOST ANY TASK!
Im going to introduce you to the macro recorder. I will show you a few of the basics
that are involved and get you started in recording your first macros.
Many of us would have a video camera at home. When you turn on that video
camera everything in front of the lens is captured and you can play it back over and
over again.
The macro recorder does exactly that. It will record your actions and then you can
playback that action or group of actions over and over again.
Because a macro recorder is going to record every single thing you do it is a good
idea that we rehearse our actions beforehand. With more complex recorded
macros you may even need to write them down step-by-step so that you can record
succinct and clear code.
We are going to record a macro to hide the sheet tabs.
1. Click File and Choose Options
2. Click Advanced locate Display options for this workbook
3. Remove the tick from show sheet tabs
Rehearse these actions
Start Recording
1. Add an appropriate name. For example because we are hiding the sheet tab with
this macro we could name it HideTabs or Hide_Tabs.
2. Spacers are not allowed.
3. Create a shortcut. Click inside the box next to Ctrl+ and push down the shift key
and add a letter. If we choose H then the shortcut to run the macro would be
Ctrl+Shift+H.
4. Choose the location where you want to store the macro. We will select This
Workbook.
5. Add a description. My first fantastic macro
6. Click OK to begin recording
7. Run through the steps you rehearsed
8. Stop the recording from one of these 3 locations
1. From the View tab
2. From the Developer tab
3. From the Status bar
Make the tabs visible again from the File / Options / Advanced
There are multiple ways to run the macro that you have just recorded
From the view tab
On the developer tab
Push Ctrl+F8
Hit the keyboard shortcut Ctrl+Shift+H
Click inside the code and then Click the green run button
Hold down the Alt+F11 key on your keypad to open the Visual Basic editor.
Double-click on the module that contains your procedures.
Read through how the code is working
ActiveWindow.DisplayWorkbookTabs = False
Change the False to True and run the code to see what happens.
If you change the code as shown below you turn it into a toggle button
Click it once and if the tabs are hidden it will unhide them click it again and it will
hide them. I use this little piece of code all the time. It cannot be recorded but I am
sure that you can see that we have used recorded code to create it.
ActiveWindow.DisplayWorkbookTabs = Not ActiveWindow.DisplayWorkbookTabs
OVERVIEW
Adding a Module
Removing a Module
Adding a Userform
Code Keywords
Entering code
Relative and absolute references
Line-continuous character
Stepping through the code
In this chapter we are going to look at many of the basic processes in working with objects
and their code. When you record a macro, a module is automatically added for you and the
code is inserted.
What if we want to add our own module and VBA code?
We will also have a look at the way the code is structured.
Finally I will show you how to step through the code to check each section for errors.
Adding a Module
Method 1
1. To add a module
2. Right click any object
3. Choose Insert
4. Select module
Dont forget to name your module appropriately as described previously.
Method 2
Removing a Module
Adding a Userform
We will look at Userforms a little later in another chapter. For now lets see how to add a
Userform.
Method 1
1. To add a userform
2. Right click any object
3. Choose Insert
4. Select Userform
Dont forget to name your module appropriately as described previously.
Method 2
Removing a Userform
Code Keywords
Special terms are designated as keywords and are displayed in blue.
For example the word Sub is a keyword that precedes the name of the macro. Notice the
end of the macro is always concluded with the keywords End Sub. Notice in the code
below that the Boolean statement True is a keyword.
An apostrophe preceding code indicates a comment that is descriptive and will appear in
green. It becomes a non-executable part of your code. It is good practice to get into the
habit of adding comments to your code.
Copy the code below and add it to a module to get familiar with the way comments and
keywords are recognized in the visual basic editor.
Sub Test()
' Test Macro
' Test for keywords
' Keyboard Shortcut: Ctrl+Shift+A
ActiveCell.FormulaR1C1 = "1"
Selection.AutoFill Destination:=Range("A1:A10"), Type:=xlFillSeries
Range("A1:A10").Select
Selection.Font.Bold = True
End Sub
Entering code
There are 3 ways to enter code into the procedure window of the editor:
Type it in
Record a macro
Paste the code from another source
Lets look at each one individually.
When you want to write your own code the first step to take is to add a module:
1. Select Insert then select Module to insert a new module
a. Name the module from the properties window
2. Now type the keyword Sub followed by an appropriate name for your macro.
a. E.g. Sub My_First_Macro
b. Notice the underscores to join multiple words into one word.
3. Now press Enter
a. This is what will now appear:
Sub My_First_Macro
End Sub
4. Between the lines type
a. Range("A1").Value = "This is my first written macro"
b. Your code block will now look like this:
Sub My_First_Macro
Range("A1").Value = "This is my first written macro"
End Sub
c. With your curser inside the code push the F5 key and you will see the text "This
is my first written macro" inserted into cell A1 of the active worksheet.
5. Congratulations you have written and executed your first macro.
It is a good idea to make use of IntelliSense when writing your code. It will ensure that
your code is accurate.
Tip: Type your code in lower case. If your syntax is correct the Visual Basic Editor will
change the first letter of the keywords for the objects properties and methods to upper
case. This will indicate that you do not have any syntax errors in that section of the code.
When you record a macro, the macro recorder will add a lot more code than you actually
need. Do not let this be of a concern, the code will work fine.
It is worthwhile shortening the code where possible to remove the parts that are not
necessary.
Lets perform a little test:
1. Select any cell on the worksheet
2. Click on the developer tab and then Record Macro
3. On the worksheet Home tab choose Font / Borders
4. Add a medium border
5. Stop recording the macro
The code block below is what will be recorded. That is a lot of code for just a simple task.
Take heart, it is not all necessary.
This code can be shortened.
Here is the abreviated code.This is all that is necessary to accomplish the task.
There are many times when you will need to paste from a website or other source. The
basic steps are listed below.
Note: If you are pasting from a word document then caution needs to be exercised with
fancy quotes and dashes. If the word application has fancy quotes enabled, and it probably
will, then follow this simple step.
Fancy quotes will need to be replaced with the straight apostrophe.
Line-continuous character
Type a space, then type an underscore and then press ENTER.
2. Add a new module to the Visual Basic Editor and add the code that you see below.
a. Sub MyColors()
' MyColors Macro
Range("D4").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorLight2
.TintAndShade = 0.399975585192419
.PatternTintAndShade = 0
End With
Range("D5").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent3
.TintAndShade = -0.249977111117893
.PatternTintAndShade = 0
End With
Range("D6").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("D7").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 255
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
3. Close the Visual Basic Editor by Alt+F11
4. In the ribbon select Developer / Macro
5. The Macro dialog box will appear
1. Now add a deliberate error to the code. In this instance I have retyped the word
Selection incorrectly. We will step through the code and allow the editor to find the error
for us.
2. Reset the colors to on fill for the range D4:D7
3. Open the macro dialog box again and select Step Into
4. Push the F8 key repeatedly to move you down the code until you come to the error in
the code.
OVERVIEW
What are variables?
Naming a variable
Why use variables?
Declaring variables
What is a data type?
What is the scope of a variable?
What are variables?
As a simple example, look at the variable below called MyVar that references
Range(A1) of the active worksheet. In the procedure where this variable resides, we no
longer need to add Range(A1) to the code. We would simply type MyVar instead of
the range reference when we run the procedure. It is there, ready to be used as many
times as we want during the life of that procedure.
It would be written this way in our procedure.
Set MyVar = Range(A1)
Note that in this variable, because we are referring to an object we need to add Set before
the variable to tell VBA we are referring to an object. If you were referring to a number, we
would not need to add the Set parameter. A variable for the number 100 would read as
below:
MyVar = 100
Open the Visual Basic Editor, insert a module and copy and paste the code that you see
below. On the sheet that is active, add a value to cell A1. Return to the Visual Basic Editor
and put the curser in the code and press F5 or click the Run button in the menu. You will
notice that the value that you added to cell A1 will appear in the message box.
Sub Macro1
Set MyVar = Range(A1)
MsgBox MyVar
End Sub
Now change the value in cell A1 and run the procedure again. The message box value will
change also.
Now let me demonstrate one of the powerful features of variables.
If you were to use the reference to cell A1 fifty times in a lengthy procedure and you
wanted to change that reference to cell A2, you would need to locate all fifty occurrences
and change them individually. As you can see, if you were to assign a variable to the range
reference, all you would need to do is make the change to the variable and all the
references would be accurately updated. It is fast and eliminates human error in lengthy
code. There are also other advantages that we will talk about later in this chapter.
Naming a variable
I used the name MyVar, in the previous demonstration; however you can use any name
you like. You should name the variable to describe the action it is associated with. If for
example you were using a variable to establish a discount for a product you sell, then you
might call the variable SaleDisc. This will make understanding what that variable is
referring to and make editing the procedure much easier.
Note:
There are a couple of caveats with regard to the naming of variables.
A variable must start with a letter and it can be a single letter. For example a non-
descriptive single letter such as. X (single letters are not descriptive and are considered
by many to be bad coding practice if used as a variable) has little meaning. Reading a
variable named this way can be very confusing. It is best to use abbreviated and
descriptive terms.
The name cannot be longer than 250 characters
It cannot be an Excel keyword. As an example you cannot call a variable Sub or Sheet
as these are reserved by Excel.
It must be a single word or multiple words joined by an underscore to form a continuous
character string. For example, My_Var. After a while you will develop your own naming
conventions that if used consistently will help you to understand what the variable stands
for.
Declaring variables
What does it mean to declare a variable?
In simple terms it means to tell VBA how much memory will be needed to store the data for
the variable. To explain a little further, there are different types of data as you can see from
the list below. Each type will require a different amount of memory to store or hold that
data.
Let us refer to our illustration of a storage container again. Not all storage containers hold
the same amount. You choose the size of the container based on the amount that needs to
be stored. You would not use a forty litre container to hold one small screw. That would be
a waste of storage space that could be better utilized elsewhere.
The same applies to variables. We do not waste memory. The right data type saves
memory space and improves efficiency.
Here is a list of the most common data types and storage sizes:
Data type Storage size Allowable Range
Boolean 2 bytes True or False
60 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Chapter 6: How to use Variables in VBA Page | 61
The list above is largely self-explanatory, however here is a little more information that you
may find helpful that clearly identifies when to use each data type.
Boolean: This is True (-1) or a False (0) so there are only two possible outcomes. Only
2 bytes of memory are needed
Integer: Whole numbers between -32,768 to 32,767
Long: Number values from -2,147,483,648 to 2,147,483,647 and the memory is 4
bytes.
Double: Numbers with decimals and holds double precision data for both positive and
negative numbers. This type requires 8 bytes of data.
Currency: Money and fixed point calculations
String: Characters that are not numbers. Text is most commonly declared as a
string. It can be a continuous sequence of numbers or spaces. 10 bytes of
memory is required plus the length of the string.
Date: Used to store dates and times. Dates and times are numbers. 8 bytes of
memory is needed.
module is active. You can use either the Private of the Dim statement to achieve this as
shown in the two examples below.
Dim MyVar as Range
Sub Macro1
Set MyVar = Range(A1)
End Sub
OVERVIEW
We will be looking at the basic structure for IF function as it is used in VBA. This magical
function has many variations that you can use to create decision modeling within your
Excel applications. We will discuss all the information you will need to use the VBA If
function effectively. Test code is provided for the seven common uses covered in this
chapter.
If Then
If - Else
If Then - ElseIf Else
If And -Then
If Or - Then
If Not - Then
IIf Function
Open the resource file that came with this eBook and navigate to the If Function worksheet. This will
enable you to test each of these examples.
Decision Modelling
You may remember this scene from Alice in Wonderland. This is my granddaughters
favourite film. It can help us to focus on the heart of decision modelling.
Would you tell me which way I ought to go from here? asked Alice.
That depends a good deal on where you want to get, said the Cat.
I really dont care where replied Alice.
Then it doesnt much matter which way you go, said the Cat.
We need to help the user of our applications to decide the right way to
proceed. It does matter! We do not want Alice in Wonderland applications.
If like Alice it does not matter to you then you too are in for a wild
ride.
Decision modelling is all about making the right decision or choosing the right road to take
with your VBA Application.
In fact it can mean the difference between your application being very successful or an
abysmal failure.
Why not consider using the If-Then construct as an effective way to made decisions with
the VBA code?
Why is this important? It is because good decisions are essential for the development of
successful applications.
Single If-Then
In the VBA example below, if the value of Rng1 is greater than 50 then were going to add
50 to Rng2 to plus the value of Rng1.
If Rng1.Value > 50 Then Rng2.Value = 50 + Rng1.Value
Here is the code that you can copy to a module in your Excel application for testing.
1. Press Alt+F11 to open the VBA editor and from the menu choose Insert / Module,
then copy and paste the code below.
2. Add a value greater than 50 to sell A1 of the active sheet in your workbook.
3. Run the code by putting your curser in the code block and pressing F5.
4. The condition will be met (True) then our new value will be added to Rng2.
Note:
I have assigned variables to our ranges so that the code will be easier to read I have also
dimensioned or declared them with the Dim statement. This is what is called a single line If
-Then construct or a line continuous construction because it presents the complete If -
Then argument on one line.
Sub If_Range_Single()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value > 50 Then Rng2.Value = 50 + Rng1.Value
End Sub
Sub If_Range_Multiple()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value > "" Then Rng2.Value = 20 + Rng1.Value
If Rng1.Value < 50 Then Rng2.Value = 50 + Rng1.Value
If Rng1.Value >= 50 Then Rng2.Value = 70 + Rng1.Value
End Sub
Disadvantages:
A disadvantage with the single line If-Then statement is that it can be hard to read
and to decipher if edits are needed. A better approach is to use multiple lines by
adding the keywords End If. This indicates to VBA that the If statement has ended.
Another disadvantage that should be mentioned is that every line is executed to
achieve just one result. It would be far better coding to only execute the line that
evaluates to True. I will show you how to do this a little later in this article.
IfThen End If
To have the If function on two lines we need to tell VBA where the function ends. To do this
we use the keywords End If. Here is our one line example expressed in two lines with the
End If keywords at the end of the If statement.
Sub If_EndIf()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value < 50 Then
Rng2.Value = 50 + Rng1.Value
End If
End Sub
This illustration shows the basic movement of the If Then -Else function
construct used in VBA coding.
For the sake of variety we will change our If statement to include an InputBox variable that
will allow us to enter a value (Amount).
In the code that you see below if the amount that is entered is equal to or greater than 50
then a message box will appear and show the amount that we entered into the InputBox. If
the amount that we enter into the InputBox is less than 50 then no message box will
appear.
This code is the same as our previous two line If statement.
Sub If_Input()
Dim Amount As Variant
Amount = InputBox("Enter an Amount:")
Now let us add the Else statement to allow us to run code if the True statement is not met,
in other words if it is False. So instead of running two If statements that both need to be
executed we run just the one. The action occurs only when the condition is met (True,
False). This is a more efficient code.
Sub If_Input_Else()
Dim Amount As Variant
Amount = InputBox("Enter an Amount:")
If Amount >= 50 Then
MsgBox "Amount: " & Amount
Else
MsgBox "The Amount is less than 50"
End If
End Sub
Rng2.Value = 50 + Rng1.Value
Else
Rng2.Value = 70 + Rng1.Value
End If
End Sub
If And Then
There are two other common operators thatare reserved as keywords in VBA that work
hand in hand with the If fuzznction. They are the And / Or operators. These two operators
will allow you to reduce your code even further and add greater flexibility. These operators
should have been used in some of the previous examples.
First lets have a look at the And operator.
Example 1
Sub If_And_Single()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value > 50 And Rng1.Value < 100 Then Rng2.Value = 50 + Rng1.Value
End Sub
Example 2
Here is another example for you to test with the InputBox. Less than 25 will receive no
discount, between 25 and 50 will receive a discount of 10% and over 50 will receive a
discount of 20%. The results will appear in the message box.
Sub If_Input_ElseIf()
Dim Amount As Variant
Dim discount As Double
Amount = InputBox("Enter an Amount:")
If Amount >= 0 And Amount < 25 Then
discount = 0.1
ElseIf Amount >= 25 And Amount < 50 Then
discount = 0.2
Else
discount = 0.3
End If
MsgBox "Savings: " & discount
End Sub
If Or Then
The other common operator here is the Or operator that is reserved as a keyword in VBA.
With the Or operator, only one condition needs to be met. So both (True and False) or
(False or True) will cause our code to act. Look at the piece of code below and you will see
that if the value is less than 50 Or greater than 100 then our action will be carried out.
Focus on this part of the procedure.
If Rng1.Value < 50 or Rng1.Value >100
Sub If_Range_Single()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value < 50 Or Rng1.Value > 100 Then Rng2.Value = 50 + Rng1.Value
End Sub
Im sure that you can see why these two operators are used so frequently with the If
function in decision modeling within VBA applications.
If Not Then
Another operator that we can use with our If statement is Not. It is used to reverse the
statement. Not is another VBA keyword. In the procedure that you see below the message
box would simply indicate that 500 is not less than 499. So if you need reverse logic you
might want to use the Not operator in conjunction with your If function.
Add the code below into a module and test it. Then change the values and test it again.
Sub If_MsgBox()
If Not 500 < 499 Then
MsgBox "500 is not less than 499"
End If
End Sub
IIf Function
The Immediate If Function (IIf) almost perfectly mirrors the worksheet If function. This
function is more often used in Microsoft Access then it is in Excel. It will run a little bit
slower and will evaluate both conditions. If applied incorrectly an error is generated as both
conditions need to be evaluated. It is good to know that the IIf function exists, and how it is
constructed but I think youll find that you will not use this construct very often.
Here is the syntax:
IIf (condition to evaluate, True part, False part)
Copy the code below to a module and add a value to cell A1 of the active sheet and run
the procedure. Now remove the value and run the procedure again.
Sub IIf_Msg()
Dim rng As Range
Set rng = Range("a1")
MsgBox IIf(IsEmpty(rng), "Cell is empty", "Cell is not empty")
End Sub
Conclusion
OVERVIEW
Benefits of the Select Case function
Syntax
Select Case - (Single condition)
Select Case - (Multiple conditions)
Select Case Else
Multiple Conditions (Comma separator)
Multiple Conditions (To)
Combining Multiple Conditions (To + separator)
Using Operators with Select Case
Select case and Text Conditions
Option Compare Text
Combining Numbers and Text Conditions
Combining Select Case (Magic combinations)
List of Keywords and Operators for Select Case function
Open the resource file that came with this eBook and navigate to the Select Case Function
worksheet. This will enable you to test each of these examples.
Syntax
Lets have a look at the way that the syntax is constructed.
Select Case (Expression to test)
Case (Test1)
Execute code 1
Case (Test2)
Execute code 2
Case Else
Execute code 3
End Select
The Select Case Function will only run when a test condition is met. Notice that there are
three basic parts to the Select Case Function.
1. The expression to test, for example. (Range("A1").Value). This expression is
often best set as a variable.
2. A single or multiple statements to test with this expression.
3. Code that is executed when the statement condition is met.
With up to three conditions it probably has little advantage over the If Function.
It would be the function of choice however if more than three conditions needed to be met.
If you are a beginner to Visual Basic for Applications then it would be recommended that
you learn how to use the If Function first and then move to the Select Case function for
larger decision-making and application modelling.
I have prepared this table that compares the If Function to the Select Case function under
various conditions. It should help in deciding which function is best to use in various
situations.
Please note: This is just a guide.
End Select
End Sub
The code can be added to the same line by using a Colon: (as shown below). I think that
this makes the function easier to read. It will make no difference to the performance of the
function.
Case 5: Range("B1") = 50
Sub Case_Else()
Select Case Range("A1").Value
Case 5
Range("B1") = 50
Case 10
Range("B1") = 100
Case 15
Range("B1") = 150
Case 20
Range("B1") = 200
Case Else
Range("B1") = ""
End Select
End Sub
Rng2 = 50
Case 30 To 40, 50 To 60
Rng2 = 100
Case Else
Rng2 = ""
End Select
End Sub
Specific word
If you wanted to make the procedure not case sensitive, it is necessary to add the (Option
Compare Text) above the procedure as shown below.
Option Compare Text
Sub Case_Text_Compare()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case "Online"
Rng2 = "Online is there"
Case Else
Rng2 = "Wrong text"
End Select
End Sub
Lets switch our Select Case function code to a message box. By using an operator with
text we can set conditions for words in any part of the alphabet. The message box would
vary depending on whether we had used (Option Compare Text) above our procedure.
Sub Case_Text_Compare2()
Select Case "robert"
Case Is < "Peter"
MsgBox "Is less than"
Case Is > "Peter"
MsgBox "Is greater than"
End Select
End Sub
In this procedure we are checking for the express R (Capitals) between "a" To "m" and "n"
To "z". Add this to a module and test it by changing the expression letter.
Sub Case_Text_Compare3()
Select Case "R"
Case "a" To "m"
MsgBox "between a and m"
Case "n" To "z"
MsgBox "between n and z"
End Select
End Sub
Sub Case_Text_Number()
Var = "R" ' 22 'must set a variable here
Select Case Var
Case 1 To 10, "a" To "m"
MsgBox "between a and m or 1 to 10"
Case "n" To "z", 20 To 30
MsgBox "between n and z or 20 to 30"
End Select
End Sub
That covers all of the basics for the Select Case Function. Both the If function and the
Select Case Function are fantastic decision making tools. The skill that we need to develop
is to know when each should be used effectively.
While these two functions are not synergistic they certainly go hand in hand with many
similar features and outcomes.
With both of these functions at our disposal we can create simply awesome applications
with automated decision making processes that can mean the difference between a
successful outcome and failure.
OVERVIEW
Key points from this chapter:
Microsoft Excels use for message boxes
Simple Message Box
Message Box Syntax
Constants available to the message box function
How it all works behind the scenes
Multiple lined Message Boxes
Message Boxes to give the user options
VBA Examples
Note:
The Action is stopped and there is a warning, but more importantly the user is helped to
make the right decision.
Lets see how we can create a simple message box like this with Visual Basic for
Applications.
Open the Visual Basic Editor and insert a new module from the Insert Tab. Into this module
we will put the test code that you see this article. Test each piece of code until you fully
understand the wonderful features available.
Copy and paste this into the module you created earlier. Put the mouse pointer inside the
code and press the F5 key to run the macro.
Sub MessageBox()
Range("A1").Value = 50
MsgBox "The value was added successfully"
End Sub
Syntax
Delete the line: MsgBox "The value was added successfully". Now type the keyword
MsgBox, after you typed the keyword MsgBox and push the space bar you are prompted
with all of the options available to the message box.
Test this out; your code should look just like this. We are being told here exactly what to do
step-by-step.
Prompt
The square brackets indicate optional parameters. The prompt parameter is the only one
that is required (must be added between double quotes). That is the only one that we used
in our simple procedure.
Prompt="The value was added successfully"
Type a comma as a separator after the prompt. You will be asked to choose the button
constant. If we fail to use this parameter vbOKOnly constant will be added by default (you
will not see it in the code).
Have a look at the options available in the dropdown list. All of these constants are in the
table below.
Note:
Each constant has a numeric value equivalent.
Select vbInformation from the drop-down list. Your code should look like this:
MsgBox "The value was added successfully", vbInformation
or
MsgBox "The value was added successfully", 64
Now click inside your code and push the F5 key to run the procedure.
Notice the information icon in the message box.
Syntax:
[buttons] =, vbInformation (or the number 64).
Note: I do not suggest that you use numbers as it will be difficult to decipher your code.
List of Icons
There are four icons available to us. Here are the four constants.
vbCritical
vbQuestion
Visual Basic Editorxclamation
vbInformation
List of Buttons
Default Button
In our previous illustration you will notice by default that our first button is highlighted or
active. We need to be able to control which button the operator should be choosing and
make that button the active button, when the message box opens.
There is a very good reason for this:
If we had the wrong button active by default we can have problems because people often
just simply click through message boxes without reading them. This can bring devastating
results to our project. The wrong data could be irretrievably deleted. So how do we change
the default button?
In the button parameter for our code we would choose to add the constant that will show
which button should be the default.
Note:
Multiple button options will need to be added.
vbYesNoCancel + vbInformation + vbDefaultButton2
As you can see from the illustration now our second button is highlighted as the active
button because we have used the constant vbDefaultButton2.
Here are the four constants for setting the active button.
vbDefaultButton1
vbDefaultButton2
vbDefaultButton3
vbDefaultButton4
To make your code easier to read we could add button syntax as a variable. This is
because the button syntax can include Button Type, Icon and Default Button.
Note:
When we click one of these buttons (constants) a whole number (Integer) is processed so
we would need to dim this variable with the data type Integer.
Add and run this code in your module.
Sub MessageBox()
Dim ButtonType As Integer
ButtonType = vbYesNoCancel + vbInformation + vbDefaultButton2
Range("A1").Value = 50
MsgBox "The value was added successfully", ButtonType
End Sub
Title
Our next parameter is the title for the message box. All we need to do is type a comma
then inside double quotes add the text that we want to appear in the title of the message
box.
MsgBox "The value was added successfully", _
VbInformation, "Operation Complete"
Syntax:
[, title]= , "Operation Complete"
That is all the information we need to know to get us started with buttons and icons in our
message boxes.
Lets move along to our next parameter.
Help file
[helpfile, context]
The help file and context deal with a specific help file and context that may be set up for
the message box. We will not deal with this in a basic tutorial. You will in fact find that you
will rarely use these two parameters.
Before we start adding some examples that you can use lets have a look at what happens
when you click a button in the message box. VBA will recognise the constant but what it
actions is the value that the constant stands for. As an example if we were the click vbOK
then the value (1) is what is processed. However if we had 3 buttons in our message box
with the constant vbYesNoCancel then the values 6 for Yes / 7 for No / 2 for Cancel
would be returned as an integer and processed accordingly if clicked.
applications. This will demonstrate the functionality and flexibility of this wonderful decision-
making tool that VBA offers.
In the example below you can add any code that you like in the code section. The
procedure will be paused and a simple message box with all of the default settings will
appear with the text in it saying "Hello Everybody"
Sub MessageBox()
'any code
MsgBox "Hello Everybody"
End Sub
A variable is assigned for the button parameter in the message box. The variable could
have been written this way ButtonType = 4 + 64, but unless you know 4 and 64 stand for
the value of the constants vbYesNoCancel and vbInformation then the variable will be
quite a mystery.
Sub MessageBox()
Dim ButtonType As Integer
ButtonType = vbYesNoCancel + vbInformation
' any code
MsgBox "The value was added successfully", ButtonType
End Sub
Lets create a scenario that will often be presented within our applications. Our code is
going to allow the user to delete some vital information from a dataset. Lets see how we
can use the message box to guide the user to make the right decision. Ive taken this
example from the Simply the Best Phonebook project on the website.
The variable named CheckDelete is added to the message box.
Note:
We have declared (dimension) the message box with the data type VbMsgBoxResult.
A message box will appear and if the user clicks Yes then the value of the cell A1 is
deleted. If the user clicks No then the value is not cleared from the cell.
This is our first example where we are encouraging the user to make a decision by using
the If function in association with the message box. Notice that we run the If function on
one line of code. (Refer to previous chapter).
Sub DeleteCheck()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo)
If CheckDelete = vbYes Then Range("A1").ClearContents
End Sub
If the user clicks Yes then we run the code and then give the user a confirmation message
to let them know that this has occurred.
This is particularly useful if we are working with data that the user cannot see or that is on
a different worksheet. It is establishing good communication with the end user.
Sub DeleteCheckMsg()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo)
If CheckDelete = vbYes Then
Range("A1").ClearContents
MsgBox "Your data has been deleted"
End If
End Sub
Unfortunately most people are in the habit of clicking their way through programs without
reading the messages that are given to them. To avoid disaster that could occur when
someone clicks the Yes button or hits the Enter key without properly reading the message
we could set the default button to No. That way the user would have to make a conscious
decision to delete the data by clicking the Yes button which is not the default.
vbYesNo + vbDefaultButton2
Sub DeleteCheckNo()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo +
vbDefaultButton2)
If CheckDelete = vbYes Then
Range("A1").ClearContents
MsgBox "Your data has been deleted"
End If
End Sub
In this code we simply add the Else statement to the message box which will provide the
user with a message regardless of the choice. We will be confirming the users decision for
both Yes and No.
Sub DeleteCheckValue()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo +
vbDefaultButton2)
If CheckDelete = vbYes Then
Range("A1").ClearContents
MsgBox "Your data has been deleted"
Else
MsgBox "The value was not deleted"
End If
End Sub
The If Function is used here once again. This time we are adding the ElseIf statement
along with the Else. The range that we are adding text to is set as a variable. Depending
on the decision that the user makes we will be sending back that result to the user in a
message box.
This is a very basic example, however Im sure that you can see the wonderful possibilities
in being able to present variable data back to the user in a message box so that they can
make the right decisions in their workflow.
Sub AddCheckShow()
Dim CheckAdd As VbMsgBoxResult
Dim rng As Range
Set rng = Range("A1")
CheckAdd = MsgBox("Do you want to add the word (Yes)", vbYesNoCancel +
vbDefaultButton2, "Add Value")
If CheckAdd = vbYes Then
rng.Value = "Yes"
MsgBox "Your data is added. The Value is " & rng
ElseIf CheckAdd = vbNo Then
rng.Value = "No"
MsgBox "Your data is added. The Value is " & rng
Else
rng.Value = ""
MsgBox "The value is blank"
End If
End Sub
The example below is the same as the previous code, however, this time I have used the
Select Case Function. For me it is a lot easier to read and will run very efficiently.
Sub AddCheckCase()
Dim CheckAdd As VbMsgBoxResult
Dim ButtonType As Integer
Dim rng As Range
ButtonType = vbYesNoCancel + vbInformation + vbDefaultButton2
Set rng = Range("A1")
Conclusion
Message boxes are a wonderful communication and decision making tool at our disposal.
The effectiveness of message boxes in our VBA applications lies entirely in our hands.
Take the time to use message boxes to empower the end user with effective accurate
decisions.
So far in our decision modeling we have looked at the If Function, the Select Case and
Message Boxes as tools that we can use. The best is yet to come, because we will now
take this to a new level with the Input Box function.
OVERVIEW
.
1. Syntax
2. Input Function
3. Input Method
4. Type argument
5. A Simple Input Box
6. VBA Examples
7. Create a User Login
a. Example 1 Add a name
b. Example 2 Create a login
c. Example 3 Create a login dynamic
d. Example 4 Login with 3 attempts (Download)
8. Collect employee age
a. Example 1 Age list
b. Example 2 Age calculator (Download)
9. BMI Calculator
a. Example Basic BMI Calculator (Download)
10. Working with Ranges
a. Example Dynamic print area
We can let the end users of our applications interact with the data flow with Input Boxes.
They are quick, effective and easy to construct and modify. Putting this function into your
box of tricks will add greater flexibility to your work
We can let the end users of our applications interact with the data flow with Input Boxes.
They are quick, effective and easy to construct and modify. Putting this function into your
box of tricks will add greater flexibility to your work
Open the resource file that came with this eBook and navigate to the Input Box worksheet.
This will enable you to test each of these examples.
Syntax
Then type any single word followed by an equal sign. Type InputBox(
The syntax will then be available as shown below. The Microsoft table below explains each
parameter. You will notice that the Prompt is mandatory and is inserted between double
quotes.
You will rarely use [Xpos] (4) and [Ypos] (5) which are the left and top positions for the
Input box. Helpfile (6) and ContextID (7) are seldom used.
Prompt (1), Title (2), Default (3) and Type (8) are the parameters we will use the most.
Input Function
The input box function will allow the user to enter a value into the input box; however the
data is always coerced to text and would return a string value.
Input Method
If we add the word application before the InputBox syntax we turn the Function into a
Method. Option Type (8) now appears. This will allow us to set the data type for the input
box. No other type will be allowed. Below is a list of type values and their respective
meanings.
Type argument
Value Meaning
0 A formula
1 A number
2 Text (a string)
4 A logical value (True or False)
8 A cell reference, as a Range object
16 An error value, such as #N/A
64 An array of values
Sub InputSimple()
'Input variable
ShowBox = InputBox("Type Your first name", "Add Name", "Type name here")
End Sub
VBA Examples
I have added the four examples below to help with the understanding of the InputBox
function and Method. After these four examples I have included four small practical
projects that I think you will find very helpful.
You will also be able to download two workbooks containing three of the projects.
1. A user login
2. An age calculator
3. The BMI calculator
4. Print area range tool
Notice in this example that we are using the Prompt, Title and Default parameters of our
syntax.
Sub InputName()
'Declare the variable
Dim AddName As String
'Input variable
AddName = InputBox("Type Your first name", "Add Name", "Type name here")
'Add name to the worksheet
Range("A1").Value = AddName
End Sub
We can extend the flexibility of this simple login by adding the user name and in the next
column adding the date and time that the login occurred. All those who login are recorded.
In this example we are adding a variable that finds the next available row to into which we
will add our data.
Sub Login()
'Declare the variables
Dim AddData As Range
Dim AddName As String
'Copy location
Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'Input variable
AddName = InputBox("Type Your first name", "Add Name")
'Check for a value
If AddName = Empty Then Exit Sub
'Add data to the worksheet
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
End Sub
Let us take this one step further by adding a Select Case statement that requires that the
user uses a passcode to be able to login. If the user fails to select the right pass code then
a message box is sent telling them that they are not authorised to login to the workbook.
With this login code we need to add the names of those allowed to login directly into the
VBA procedure. In this instance it is, Trevor, Harry and Mary.
Sub Login2()
'Declare the variables
Dim AddData As Range
Dim AddName As String
'Copy location
Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'Input variable
AddName = InputBox("Type Your first name", "Add Name")
'Check for a value
If AddName = Empty Then Exit Sub
'Check for the right name
Select Case AddName
Case "Trevor"
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
MsgBox "Welcome: - " & AddName
Case "Harry"
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
MsgBox "Welcome: - " & AddName
Case "Mary"
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
MsgBox "Welcome: - " & AddName
Case Else
MsgBox "Name not authorised"
End Select
End Sub
Here is a practical example of all of the features we have just mentioned plus extending the
flexibility by allowing the number of users to login to be as many as we require.
To do this we loop through the range of valid users and compare this with the value that is
typed into the Input box.
This illustration shows how the worksheet should be structured. In practice you would not
put the list of users where they could be visible. In fact all of this information should really
be hidden.
If the wrong password is added three times, the workbook will close and not be saved.
Note:
Be careful if you edit this code because it is possible to create a procedure that cannot be
exited.
Sub LoginCheck()
'Declare the variables
Dim AddData As Range, Check As Range
Dim Nme As String
'Count attempts
Set Check = Sheet1.Range("E2")
'Destination location
Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'Input variable
Nme = Application.InputBox("Add your login code name:- You have 3 attempts",
Type:=2)
'Variable for authorise
Auth = 0
'Loop through range of names
For Each cName In Sheet1.Range("D2:D14")
If cName.Text = Nme Then
AddData.Value = Nme
AddData.Offset(0, 1).Value = Now
MsgBox "Welcome: - " & Nme
Auth = 1
Exit For
End If
Next cName
In this example we are just simply collecting the age of the employee and adding it to a list
on the worksheet. The ages are added one after the other in column five.
Sub InputAge()
'Declare the variable
Dim AddAge As Long
'Input variable
AddAge = InputBox("Type Your Age", "Add Age", "Type your age")
'Copy location
Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = AddAge
End Sub
Lets use the Import box method once again, this time to calculate the age of an individual
based on the date of birth entered into the Input box. The Type will now appear as a
parameter. In this procedure we are setting the Type to (1). This restricts the entry into the
Input box to a number. Dates are numbers! If the user enters text it will be rejected.
You will notice that we do all of the calculations on the worksheet and return the calculated
value to the user in a message box at the end of the procedure.
You will find this in the resource file.
Note:
A formula needs to be added to cell G8 to calculate the age.
G8 formula =If(F8="","",DATEDIf(F8,TODAY(),"Y")&" Years,
"&DATEDIf(F8,TODAY(),"YM")&" Months, "&DATEDIf(F8,TODAY(),"MD")&" Days")
The result will appear in the message box. Notice we are adding this cell values to the
message box content.
Sample file
Sub InputAge()
'Declare the variables
Dim AddAge As Long
Dim mMyAge As Range
'Set the the result range
Set MyAge = Sheet1.Range("G8")
'Variable for input box
AddAge = Application.InputBox("Type Your Age", "Add Age", "Type your date of birth",
Type:=1)
'Check for value
114 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Chapter 10: Understanding the Input box construct Page | 115
BMI Calculator
Two input boxes are called one after the other and the data is stored on the worksheet.
In this example we are using the Input box Method by inserting Application before the
keyword InputBox. The data type that we have chosen is (1) indicating that we are limiting
this to numbers only. We show two input boxes one after the other to collect the Height
and then the Weight which is necessary to calculate our BMI.
Height is added to F8 and Weight is added to G8 on the worksheet.
A formula is added to cell H8 to calculate the BMI for us. This is stored as a variable and
shown in the message box result.
H8 formula =G8/((F8/100)*(F8/100))
Sub BMI_Calculator()
'Declare the variables
Dim Height As Long
Dim Weight As Long
Dim BMI As Range
'Variable for result
Set BMI = Sheet2.Range("H8")
'Input variable for height
Height = Application.InputBox("Add your height in centermetres:", Type:=1)
'Check for value and add value
If IsNumeric(Height) And Height <> 0 Then
Sheet2.Range("F8") = Height
Else
End Sub
Sub InputPrint()
'Declare the variable
Dim PrintArea As Range
'Set error handler
Conclusion
The Input box function and the Input box Method are awesome tools for collecting data
from a user and then using that in our calculations and decisions in our applications. It
presents us with the opportunity to very allow the user to interact with the processes we
have set.
We have now discussed the four decision modelling tools at our disposal.
The functions are:
1. If function
2. Select Case function
3. Message box function
4. Input box function and method.
With these functions we can help the end user to make effective decisions as they use our
applications.
OVERVIEW
In this chapter we will look closely at loops in VBA.
What are loops?
Do Loop
Do Until Loop
Do While Loop
For Loop
For Each Loop
Nesting Loops
Open the resource file that came with this eBook and navigate to the Loop worksheet.
This will enable you to test each of these examples.
Illustration
As an example to help us to understand loops, think of our planet Earth that orbits (loops)
around the Sun. With each loop (orbit) life-giving tasks
(changes) are carried out that make this planet the jewel
of the universe. We are looping around the sun at
approximately 67,000 miles an hour (108,000 km per hr),
so hang on.
VBA Loops
Similarly we can loop through huge datasets and make changes that would otherwise take
the user an enormous amount of time. Yes, we can do this at high speed if our loops are
constructed properly and used in the right circumstances.
We are often confronted with the arduous task of working with large data sets and ranges
of various sizes and types. Loops work their way through data sets performing repeated
tasks for us. Skilfully using loops can save you heaps of time, effort and worry. You can
literally find a needle in a haystack.
There are basically five different types of loops and endless combinations of these.
In this chapter may I invite you to open Microsoft Excel and the VBA Editor? Hold down the
Alt Key and press F11. This will open the VBA editor; from the Insert tab choose Insert
Module.
This information is also contained in the resource file that accompanies this eBook.
Note:
There are 17 basic procedures (Macros) that you can add, test and modify to use in your
own VBA procedures. Please note though that these procedures are here to help us to get
the concept or the understanding behind how loops work in our VBA code.
Loops are controlled VBA structures used to repeat a given section of code a certain
number of times or until a particular condition is met.
In this section we will look at the five different types of loops and also show how to nest
loops.
1. Do Loop
2. Do Until Loop
3. Do While Loop
4. For Loop
5. For Each Loop
6. Nesting Loops
Do Loop
Here is how a Do loop works in its simplest form. All this loop does is simply repeat the
code until a condition is met.
In the example below we will be adding the value of the variable num = 1 to establish a
range and also increment that range. Each time that we loop we are adding one (1) num =
num + 1 to the value of the variable. The loop will continue to operate until the number is
greater than 30. Loop Until num > 30. Test this loop out in your module.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
num = 1
Do
Range("A" & num).Value = num
num = num + 1
Loop Until num > 30
End Sub
Do Until Loop
The Do Until loop that is almost identical to the Do loop. In this loop we are putting the
condition to be met at the start of the procedure. If the condition is not met the loop does
not run at all. So we have checked the condition before the procedure runs. Do Until num
> 30. With a very large set of data this could make a significant difference to the time the
loop would take to run if the condition was not met.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Do_Until()
'loops until a condition is met
'fills cells B1:B30 with the value of "num"
'increase the variable "num" by 1 with each loop
Dim num As Integer
num = 1
Do Until num > 30
Range("B" & num).Value = num
num = num + 1
Loop
End Sub
Do While Loop
This loop is in fact the reverse of the two previous loops. It will run while a condition is met.
Loop While num < 31 Notice that this time our condition is <31. Because we only want to
add 30 values.
This procedure loops while a condition is met and will fill the cells of the C1: C30 with the
value of our variable. Notice that the condition to meet occurs at the end of the procedure.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Do_While()
'loops while a condition is met
'fills cells C1:C30 with the value of "num"
'increase the variable "num" by 1 with each loop
123 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Chapter 11: Understand VBA Loops by Examples Page | 124
num = 1
Do
Range("C" & num).Value = num
num = num + 1
Loop While num < 31
End Sub
This is a more effective way to construct the loop with the condition at the beginning to be
checked before the procedure is executed.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Do_While2()
'loops while a condition is met
'fills cells D1:D30 with the value of "num"
'increase the variable "num" by 1 with each loop
Dim num As Integer
num = 1
Do While num < 31
Range("D" & num).Value = num
num = num + 1
Loop
End Sub
For Loop
The For loop is probably the loop that is used the most. For this reason I have added six
examples to deal with some of the features that you will find useful in your VBA coding.
The number of times that the loop runs is set at the beginning of the procedure. By default
it will increment by one each time the loop is run.
In the loop we are adding all 56 colours to the first 56 cells in column F.
A variable must be set at the beginning of the procedure for this loop.
For ColCell = 1 To 56
There are no Until or While features with this loop it simply loops 56 times.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Loop_For()
'loops 56 times
'fills cells F1:F56 with background colors
'adds a backgroud color with each loop
Dim ColCell As Integer
For ColCell = 1 To 56
Range("F" & ColCell).Select
With Selection.Interior
.ColorIndex = ColCell
.Pattern = xlSolid
End With
Next ColCell
End Sub
In this example we are adding a number to the range and then changing the font colour to
represent all 56 colours available. Two variables are set, one for the For loop and one for
our range object.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Loop_For2()
'loops 30 times
'fills cells G1:G56 with
'adds a number and colors the number with each loop
Dim ColNum As Integer
Dim Rng As Range
For ColNum = 1 To 56
Set Rng = Range("G" & ColNum)
Rng.Value = ColNum
Rng.Font.ColorIndex = ColNum
Next ColNum
End Sub
A wonderful feature of the For loop is that we are able to change the default incremental
value of 1 to whatever we want. In the example below we miss one, run one, miss one, run
one et cetera. This is achieved by using the Step keyword after our variable.
For num = 2 To 30 Step 2
To make this easy to see I have changed the font size by one point after each loop to show
which way the loop is running.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Loop_For_Step()
'loops 15 times
'fills every second cell in range H1:H30 with numbers
'changes the font size by 1point with each loop
End Sub
The loop shown here is the reverse of the loop above. Notice two important differences
that are contained in our variables. First the numbers are reversed 30 To 1 and second the
Step incremental number has a minus sign before it. I changed the font size to show you
which way that the loop is running.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Loop_For_Step_Minus()
'loops 30 times from highest to lowest
'fills every cell in range I1:I30 with numbers from highest to lowest
'changes the font size by 1point with each loop
Dim Rng As Range
Dim num As Integer
End Sub
It is good practice to provide an exit for our loop especially if we are looping through large
sets of data. This will dramatically cut down the time the loop will take to run.
To achieve this we need to add an If statement that sets a condition and if the condition is
met we use the two keywords Exit For to stop the loop.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Loop_For_Exit()
'loop stops in the middle if condition is met
'exit for loop
Dim num As Integer
End Sub
As mentioned previously this loop will run exactly the number of times that we tell it to. But
what if we are not sure how many times we want the loop to run because our data may
change on our worksheet? To cope with this we can count the number of cells and add that
figure as the second number in our variable.
Add some extra data into column A and test the flexibility of this procedure for yourself.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Loop_For_2()
'allows for a variable amount of data in the range
'bolds all numbers in the rfange
Dim num As Integer
Sub For_Each()
'loops through the object range
'changes the font to bold
Dim mycell As Range
End Sub
With the procedure below we are looping through each sheet in our workbook and
protecting each sheet. You can add a password to this to make the protection secure.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub For_Each_Protect()
'loops through each worksheet and protect the sheet
Dim sht As Worksheet
End Sub
Now that youve protected all the workbooks it would be a good idea to unprotect them
again and that is what the code below achieves for us.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub For_Each_UnProtect()
Dim sht As Worksheet
'loops through each worksheet and unprotect each sheet
End Sub
Nesting Loops
To understand the concepts of nesting loops think about the illustration at the beginning of
this chapter about our earth orbiting around the sun. At the same time, the earth itself is
looping or orbiting on its own axis. We can see a structure here of an outer loop and an
inner loop. Around the sun is the outer loop and on its axis is the inner loop.
It is common practice to nest loops or to put one loop inside of another loop so that two
sets of conditions need to be met.
In the procedure below, For Each sht is the outer loop and For Each mycell is the inner
loop.
This macro will add the cell address to the Range("K1:K30") of every sheet in the
workbook.
I have included several examples here of nested loops. The first example loops through
each sheet and adds the cell address to the range on each sheet.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub For_Each_Nest()
'loops through each worksheet
'adds the cell address to the range
Dim sht As Worksheet
Dim mycell As Range
End Sub
This example loops through each worksheet and checks for a value in a range on each
sheet and if that value exists it colours the background of the cell to a yellow.
The outer loop is the sheet object and the inner loop is the range object.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub For_Each_Nest2()
'loops through each worksheet
'checks for a value in a range
'colors the background if it exists
Dim sht As Worksheet
Dim mycell As Range
End Sub
This is a little bit more complex. Have a close look at it and see if you can see the
relationship between the two loops. This loop is not in the resource file.
Here is an explanation of what is being achieved.
Numbers are added to multiple columns and the numbers increase by one with each
column. As you will see in the VBA code, we are running this procedure to work on the
next worksheet (Sheet2) as our first worksheet is getting a little cluttered by now.
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Nested_For()
'adds numbers to multiple columns
'increases numbers by 1 for each column
Dim MyRows, MyColumns As Integer
For MyRows = 1 To 30
For MyColumns = 1 To 5
Sheet2.Cells(MyRows, MyColumns).Value = MyRows + MyColumns
Next MyColumns
Next MyRows
End Sub
This is our final example for this chapter. We are looping through 30 rows over five
columns and checking for the value of 20. If the value exists then we are changing the
interior background colour of the cell to yellow.
Again this procedure is run on our next worksheet (Sheet2).
Copy and paste it into the module. Put your curser inside the procedure and push F5 to
execute the code.
Sub Nested_For2()
'loops through multiple columns
'checks for a value and colors the background if it exists
Dim MyRows, MyColumns As Integer
Dim Rng As Range
For MyRows = 1 To 30
For MyColumns = 1 To 5
Set Rng = Sheet2.Cells(MyRows, MyColumns)
If Rng.Value = 20 Then
Rng.Interior.ColorIndex = 6
End If
Next MyColumns
Next MyRows
End Sub
1. As a final comment a word of caution needs to be given with regard to loops in your
VBA procedures. Loops can the slow down a workbook if they are poorly
constructed or if the data to be looped is extensive.
2. Care should be taken in creating a user-defined function (UDF) for a loop. If this
function is used as part of a cell formula in an uncontrolled fashion the workbook
can perform poorly.
3. In particular you we need to avoid what are known as endless loops. These will
start a loop and the condition is never met. We hope that the planet Earth loops in
this manner but not our VBA procedures.
In conclusion
All of the examples above are used to help us to understand how loops function and the
various types of loops available to us. The goal is to help us to see the concepts that we
can now use to making our VBA application a far more rewarding experience for our end
users. An experience that will save both you and any users of your applications lots of time
and effort.
OVERVIEW
Why Use Error Handling?
How to Configure Error Settings
How to Reset Errors
Three Types of VBA Errors
When to use error handling
What is the VBA Debug?
Understanding the On Error Statement
Good habits to minimize errors
Open the resource file that came with this eBook and navigate to the Error Handling
worksheet. This will enable you to test each of these examples.
We all want our applications to appear error free, providing the user with a friendly
environment in which to work. It is very disconcerting than to open an application and to be
greeted with the VBA Debug message box.
We would like to be given the thumbs up by those using our applications but when this
occurs the thumb points the other way.
Skilful use of error handling can make the difference between a problem plagued program
and a successful user-friendly application. Error handling should successfully anticipate
potential problems and guide the user past these without incident.
Notice the section Error Trapping. Set the option Break on Unhandled Errors.
When these errors occur they are recognised by the VBA compiler as being illegal. The
error occurs before the procedure starts to run. This is a compilation error.
In the procedure below we have the wrong data type declared which will produce a
compilation error.
When this type of the error occurs VBE will go straight into debug mode highlighting the
offending piece of code and presenting you with the message box. The only options given
are Help and OK which will take you to the offending code. This is called a fatal error as
the execution is terminated.
Note:
You will need to reset the VBE before you proceed.
Run the code in the sample resource file that you downloaded.
Sub Compile_Error1()
'compile error
'wrong data type
Dim Rng As String
Rng = Range("D4")
Rng.Value = 20
End Sub
Run-time errors
A Run-time error can occur as your code is being executed. The code will stop running, the
Visual Basic dialog box will appear with three options (End, Debug and Help), and if you
choose Debug, the line that is causing the error will be highlighted.
In the code below the Object variable is not set, causing the procedure to fail at Run-time.
Again a fatal error is indicated.
When presented with these options End will ignore what has happened Debug will take
you to the offending line of code.
Run the code in the sample resource file that you downloaded.
Sub Run-time_Error2()
'Run time error
Dim Rng As Range
'Object variable not set
Rng = Range("D4")
Rng.Value = 20
End Sub
Logic errors
Logical errors are the bugs in your VBA code. What do we mean by bugs in our code? The code
will run successfully but the outcome will be false or inaccurate. The way that these errors occur
is by missing logic in the code of the procedure. Hence the term logical errors. These errors are
often difficult to pinpoint. To find these errors we need to step through the code using the F8
key.
They are not compile or run-time errors so they often slip under the radar.
As an example you might assign the wrong object range reference to a variable which will skew
the data giving inaccurate results.
need error handling. There are no rules here. Consider when to add error handling to the
application, for this reason.
In the development stages of the application it might be wise to comment out (add an
apostrophe before the line) your error handling or add it only after you are confident that
your procedure is free of bugs and Run-time errors. The reason for this is that VBE Debug
does a great job in highlighting your Run-time errors, making your development process
much easier.
You are letting the VBE Debug do the work of finding your errors for you.
At this stage the question could be asked, what exactly is the VBA Debug?
If the Debug toolbar is not showing choose View / Toolbars / Debug. Have a look at the
features available here by hovering you mouse over the icons. Use Microsoft help for more
detailed information about these features. Press the F1 key to activate the help menu when
needed.
In the example provided we are going to calculate the average sales per customer and
show the result in a message box. I will run you through all of the errors that could occur
and solutions that can be used to deal with them.
If all runs correctly you should expect to see a message box with the result of total sales
divided by customers to give the average sales per customer. As shown in the illustration
below.
We need to understand the On Error Statement. Here is an explanation for the three forms
of this statement.
1. On Error GoTo 0
Statement Description
On Error GoTo 0 Disables any enabled error handler in the current procedure.
The first On Error statement is the default setting for VBA. On Error GoTo 0 will reset VBA
to the standard Run-time error message box. This is the same as if you had no error
handling. The default message box is illustrated below showing that the procedure has
been terminated giving us an option to End the error handler or to choose Debug and go
to the line of code causing the error if it is in the same procedure.
The example below clears the value for customers and then attempts to divide Total Sales
by Customer (0) thereby causing Run-time Error 11. The execution of the code is
terminated at this line Result = Sales / Customers.
Sub Error_Default3()
'Default error handling
'Declare variables
Dim Sales As Range, Customers As Range
Dim Result As Long
'set range objects as variables
Set Sales = Range("C4")
Set Customers = Range("D4")
'Clear the value to cause the error
Customers.Value = ""
'div#0 error here
Result = Sales / Customers
Note:
The two valuable pieces of information and the three options given to us in the message
box.
We are told that it is a runtime error (91) (Division by zero) and that we can ignore it by
clicking End, find the cause by selecting Debug or go to the Help menu. This is extremely
helpful.
Our second On Error statement is the On Error Resume Next statement. This statement
skips the error and continues to process the code. There are times when we can use this
very effectively by fixing the error if it occurs and then moving to the next statement.
However this statement skips the error and does not fix it. Caution should be used in using
this statement as it may allow some very undesirable effects to go uncorrected.
Note:
You should reset to default error handling as soon as possible with
On Error GoTo 0.
As you run the code below you will see that the error is skipped and our procedure
continues to run and executes the result in a message box.
Run the code in the sample file that you downloaded.
If you were to check the Microsoft help files you would see this table of information.
Statement Description
On Error Resume Next Specifies that when a run-time error occurs, control goes to the
statement immediately following the statement where the error
occurred where execution continues. Use this form rather than
On Error GoTo when accessing objects.
On Error GoTo [label or line] instructs VBA to transfer to the line following the label line
when an error occurs. All of the code between the error and the line following the label is
skipped. In the example below a message box occurs notifying the user that a problem
exists on the worksheet. The same label name must be used in our code at the start and in
the error block. You can use any single word name that you want.
This statement can be used effectively to control and correct Run-time errors.
Note:
We need to exit the procedure prior to our label this will prevent the error handler from
running if no errors occur. To do this we use the VBA keywords Exit Sub.
Statement Description
On Error GoTo [Label] Enables the error-handling routine that starts at line specified in
the required line argument. The line argument is any line label or
line number. If a run-time error occurs, control branches to line,
making the error handler active. The specified line must be in the
same procedure as the On Error statement; otherwise, a compile-
time error occurs.
Sub Error_Handler5()
'Error hanldling with a label
Dim Sales As Range, Customers As Range
Dim Result As Long
'Error handler label to exit and give a message
You may wish to use generic error handling in your code that fits most situations. To do
this you could set the error handler with a label as shown above and replace the message
box section with the code that you see below. This error message presents a couple of
small messages along with the error number and a description to the user. It then directs
them to take specific action.
Note:
Change the text between the double quotes to suit your application needs. It is helpful to
include the procedure name and module in the text.
Resume
In our next example below when the error occurs we are directed to the label and an input
box is presented to enable the user to correct the error by adding a number to customers.
Then we use the Resume Statement to run the code with the values added by the user.
You will be only permitted to use the Resume Statement within an error handling block.
Run the code in the sample file that you downloaded.
Sub Error_Handler_Resume6()
'Resume error handing
Dim Sales As Range, Customers As Range
Dim Result As Long
'Error handler label
On Error GoTo Errhandler:
'set range objects as variables
Set Sales = Range("C4")
Set Customers = Range("D4")
'Clear the value to cause the error
Customers.Value = ""
'div#0 error here
Result = Sales / Customers
'result in the message box
MsgBox Result
'Exit the procedure
Exit Sub
'Error handler label
Errhandler:
'Correct the error with an input from the user
If Err.Number = 11 Then
Correct = Application.InputBox("Add the number of Customers:", Type:=1)
Range("D4") = Correct
'Resume the code from the error
Resume
End If
End Sub
Resume Next
The Resume Next Statement will cause the execution to recommence at the line
immediately following the error. If you were to use this statement in the error handling block
you would need to both repair the error and run the line of code to process the result.
A preferred way to achieve the desired result would be to use the Resume Label in the
error handling block. In the example below we use the label Fixit: as the point in the code
to return to and in the error handler we call a statement Resume Fixit: to take us back to
that point in the code.
Note:
We are using two labels and two statements. The second statement is called from the error
handling block.
Run the code in the sample file that you downloaded.
Sub Error_Handler_Resume_Label7()
'Resume label
Dim Sales As Range, Customers As Range
Dim Result As Long
'Error handler label
On Error GoTo Errhandler:
'set range objects as variables
Set Sales = Range("C4")
Set Customers = Range("D4")
'Clear the value to cause the error
Customers.Value = ""
'Resume label
Fixit:
'div#0 error here
Result = Sales / Customers
'result in the message box
MsgBox Result
'Exit the procedure
Exit Sub
Errhandler:
'Correct the error with an input from the user
If Err.Number = 11 Then
Correct = Application.InputBox("Add the number of Customers:", Type:=1)
Range("D4") = Correct
'Resume label
Resume Fixit:
End If
End Sub
I have listed some of the core practises that will help to minimise errors.
1. Using error handling will enable you to trap and fix errors as they occur in your code. It
is a good habit to get into to make sure that we use some form of error handling in our
applications.
2. Keeping our procedures a manageable size and indenting the code will also aid in
minimising errors. It is better to have many small procedures to accomplish our goal than
one large one. Not only will it minimise errors for us, but our code will run more
efficiently.
3. Trial your application with a single or multiple users and log all errors that occur.
Everybody approaches Excel with different habits and youre more likely to pick up the
full spectrum of possible errors this way. The approach that I have noticed that often fails
is to try to correct problematic code after it is released to all users.
These practices will have the end users giving the thumbs up.
OVERVIEW
What is a Userform?
Why use a Userform?
Userform Project
Insert a Userform
Userform Properties
Toolbox
Adding Controls
Writing our code
What is a Userform?
A userform is a dialog box that you create and customize in the Visual Basic Editor. It is an
object that can contain VBA code and events. You can add a large variety of controls to the
userform.
Open the resource file that came with this eBook and navigate to the Userform worksheet.
This will enable you to test each of these examples.
Here is the form that we will be using to collect and add our receipts.
A userform presents a user-friendly interface. From this platform you can control the
options available to the end-user. You do not have to go to the worksheet. It is often good
to prevent this.
Userforms enable a variety of possible uses that otherwise would be difficult to achieve at
a sheet level.
In harmony with the spirit of Online PC Learning we will be learning how to use userforms
by developing a project.
Userform Project
Our project is My Tax Receipts. It will enable you to add and sort your tax receipts for
years into a database without leaving the userform. You can then filter the tax receipts
between dates from an interface sheet. This is a great little project to get started with
learning to use userforms in VBA.
The illustration at the beginning of this chapter shows the interface sheet and the userform
ready for action.
Before we get started we need to add three dynamic named ranges to the workbook.
Change the name of Sheet3 in your workbook to Lists and in cells D4/H4/F4 add the
headers that you see below.
1. Tax Category 2. Stored Location 3. Company
Note: Make sure that there is data under the headers as our named ranges are going
to be dynamic. If there is no data for VBA to find, an error will occur. Copy the
information from the illustration.
These three dynamic named ranges will be the values that populate our three combo
boxes so we will add them at the beginning of this project. From the ribbon on your Excel
spreadsheet choose Formulas/Name Manager/New then add the name below and the
formula to create three dynamic named ranges. Category/Company/Location
Category =OFFSET(Lists!$D$5,,,COUNTA(Lists!$D$5:$D$100))
Company =OFFSET(Lists!$H$5,,,COUNTA(Lists!$H$5:$H$100))
Location =OFFSET(Lists!$F$5,,,COUNTA(Lists!$F$5:$F$100))
Here is the link to the website article for understanding dynamic named ranges
Title:
Excel Dynamic Named Ranges: Add Power and Punch to Excel
Link:
http://www.onlinepclearning.com/excel-dynamic-named-ranges/
Note: You can use a static named range however you would need to redefine it each time
new data is added.
Previously I have discussed key elements of the Visual Basic Editor in Chapter 2. If you
have not read that chapter or the information is a little hazy then please revisit this chapter.
Insert a Userform
How to create a userform!
Open Microsoft Excel and use the shortcut key Alt + F11 to open the Visual Basic Editor.
1. Click the Insert Tab
2. Choose Userform
3. The userform will appear. The white boxes on the side of the userform will enable you to
resize the form to your approximate needs.
4. VBA will hide the toolbox if it thinks you are not using it. Click inside the userform and it
should appear. If it is not visible then choose the View tab and click Toolbox.
5. From the View tab click Properties if it is not visible
We will need to have quick access to the Toolbox and the Properties dialog box.
Userform Properties
When you click inside the userform you should see a dotted border around it. When this
occurs the properties dialog box will display the userform properties.
For our project we want to change the name of the userform from Userform1 to a name
that will help us to understand the userform and its purpose. To do this we will use a basic
naming convention. When working in VBA you should use a naming convention that is
consistent.
In the properties box name the userform frmTax_Receipt (no spaces allowed) and add a
caption My Tax Receipts (spaces are allowed here)
Here is a sample of the naming convention that is commonly used.
Userforms start with frm
Text boxes start with txt
Combo boxes start with cbo
Labels start with lbl (if you are not referring to the labels in you code there is no need to
give them a special name)
The only rules that apply are not to use a reserved VBA keyword nor add spaces in the
name.
Note: At this stage of the project your userform should now have a name and a caption. If
you want to see what the userform will look like in Excel then push the F5 key or click the
Run button in the menu at the top. To return to the VBE, close the userform by clicking the
x in the top right hand corner of the userform.
Note the dotted border when the userform is selected and the new name for the userform
in the Project Explorer.
Toolbox
The Toolbox contains all of our controls that can be added to the userform. Place the
curser over the controls to reveal the name of the control. If you need to use controls that
are not in the toolbox then right click inside of the toolbox and choose Addition Controls.
The Additional controls dialog box will appear. As you scroll down you will see some
controls have an (x) in the box on the left hand side. These are the available controls in the
toolbox. To add additional controls add an (x) in the box and click OK. To remove a
control, click inside the square to remove the x and then click OK.
Note: Not all of these controls are available to VBA Excel.
Adding Controls
Adding Labels
Now that you have your label, right click and choose Properties. You will be able to
change the label name but most importantly we want to change the Caption. While the
properties box is open set the size of the font that you want and the font type and style.
Note: In the properties box you are able to select the way that the properties for controls in
our userform are formatted and behave. You have the choice of Alphabetic or
Categorized tabs at the top of the Properties dialog box to choose from.
Top Tip: Once you have formatted one label right click and copy it eleven times onto the
form. Align the labels to suit and change the Captions to reflect the nine labels that you
see in the illustration above. The labels will not be referenced in the VBA project.
As well is the nine text labels we have three labels that will indicate the fields that will be
mandatory. These labels simply have an asterisk inside of them that is formatted to a
larger font size and colored red. Create one and copy the other two and move them to the
correct place on the userform, as shown in the illustration below.
To add a text box, click on the text box icon in the Toolbox and then return to your
Userform and click down on the left mouse button and drag the text box over the form.
The only thing that we need to do to our text box controls is to add the correct name to
them.
Note:
Copy the control names from the illustration above.
Add the combo box controls to the userform in the same manner as the text boxes and
labels. Make sure that the name is correct for each of the three combo box controls. As
you can see from the illustration below we are going to populate each combo box with a
dynamic named range that you previously added into the name manager.
The illustration below shows where the dynamic named range should be typed in the
RowSource of the properties of the combo box.
Make sure that the ranges have data in them. VBA would be looking for a named range
that as yet does not exist if the ranges are empty.
You can set the option to allow a user to add different values from those in the range to a
combo box if you wish. In the properties select Match Entry and choose 2-
MatchEntryNone (illustration below). If you allow this then analyzing the data at a later
date can be a little difficult.
163 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Chapter 13: Build your First Userform Database Page | 164
Option Buttons
As well as assigning the correct names to our option buttons we need to group the two
buttons together. To accomplish this select both buttons by dragging the curser over both
of them or by holding down the shift key and clicking on the both option buttons. Right click
on the two selected buttons and from the drop-down menu choose Group.
Adding a Picture
If you wish to add a picture or a logo to your userform then follow these two steps.
1. First prepare the picture or logo and make sure that it is a very small image. The image that
I used in this Userform is a 7 kB. I will briefly describe how I formatted this image. This
image was formatted by opening a Microsoft PowerPoint and inserting clipart or your image
(logo) that you feel would be appropriate to the theme of this application. The background
was then removed in PowerPoint and the image was saved to a location on the desktop by
right clicking and choosing Save Image As. On the desktop the image was right clicked and
opened in Microsoft Picture Manager where it was resized to 7 kb.
2. Second add an image control to the userform. As you can see from the illustration below we
can add the picture by clicking Picture and then locating our image to import it into the control.
Note the two properties below:
164 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Chapter 13: Build your First Userform Database Page | 165
a. PictureAlignment
b. PictureSizeMode.
These properties will allow you to manipulate the image within the control.
Tab order
To set the tab order for the controls in your userform, click on the View Tab and choose
Tab Order (illustration below). Move the controls up and down to suit the order that you
would like the Tab key to move through them.
The first thing that we want to do is to run a small piece of code to open the Userform from
a button on the worksheet.
From the Insert tab in the VBE choose Module. Into the newly created module add this
small piece of VBA code.
Sub Showme()
frmTax_Receipts.Show
End Sub
Name the three worksheets Interface, Database and Lists. On the Interface sheet insert
a rectangle shape then right click on the shape and choose Assign Macro. Select the
macro Showme and click OK.
Click on the button and the Userform should appear above the worksheet. Do not move
forward with the rest of this project until this is successfully working. Check that the three
combo boxes have the values contained in the three dynamic named ranges.
2. Add 2 variables
3. Add 2 If statements to check that a date is added and that our mandatory fields
have been filled in.
4. Move the information from the Userform to the database.
5. Sort of the database
6. Reset the Userform
This code is dimensioning our variables which simply means telling VBA the data type for
each variable.
Dim ws As Worksheet
Dim addme As Range
These two variables are for the worksheet that contains the database and for the next
empty row in our database list.
Set ws = Sheet2
Set addme = ws.Cells(Rows.Count, 4).End(xlUp).Offset(1, 0)
Add two If statements to check that a date is added and that our mandatory fields
have been filled in.
A common mistake that many make with Userforms is to add a date incorrectly. We are
going to check the date is in fact a date before we allow the user to proceed.
If Not IsDate(txtDate.Value) Then
MsgBox " The date field must be a proper date", Visual Basic Editorxclamation, "Date
format error"
Me.txtDate.Value = ""
Me.txtDate.SetFocus
Exit Sub
End If
Our Userform has three mandatorily fields that need to be checked to see if a value exists
in each before we can process the userform. The If statement below checks these three
fields.
We reference our variable addme to find the next available cell to add our first value from
the userform. When we find that cell we add our txtDate and then offset one column in the
same row and add our cboCompany then offset one column and add txtDescription then
offset one column and add our cboCategory et cetera. When we get to our option button
we run an If /ElseIf /Else statement to check and to send the right value to our database.
Notice that we format the txtDate. You will need to change this depending on the location
in which you live in the world. And we also format our txtAmount as currency.
With ws
'set the date format to suit your area
addme.Value = Format(txtDate.Value, "mm/dd/yy")
addme.Offset(0, 1).Value = Me.cboCompany.Value
addme.Offset(0, 2).Value = Me.txtDescription
addme.Offset(0, 3).Value = Me.cboCategory
addme.Offset(0, 4).Value = Format(Me.txtAmount.Value, "$##,###.00")
If OPT1.Value = True Then
addme.Offset(0, 5).Value = "Paper Copy"
ElseIf OPT2.Value = True Then
addme.Offset(0, 5).Value = "Scanned Copy"
Else
addme.Offset(0, 5).Value = ""
End If
addme.Offset(0, 6).Value = cboLocation
addme.Offset(0, 7).Value = txtRemarks
End With
Living in the real world we know that our dates are not always going to be added in
consecutive date order. So to deal with this problem we are going to sort the data each
time we add a new tax receipt. The data is sorted by dates and in ascending order.
ws.Select
With ws
ws.Range("D4:K10000").Sort Key1:=Range("D4"), Order1:=xlAscending,
Header:=xlGuess
End With
'return to sheet
Sheet1.Select
We are going to choose the final option (3) because it is the easiest.
Remember this code goes into the userform not the module. Double-click on the cmdAdd
button to access the code for the userform. Take the time to look through the code again
and make sure that you understand exactly what each part of the code is doing.
End With
'sort the data
Sheet2.Select
With ws
ws.Range("D4:K10000").Sort Key1:=Range("D4"), Order1:=xlAscending,
Header:=xlGuess
End With
'return to sheet
Sheet1.Select
'reset the form
Unload Me
frmTax_Receipts.Show
'update the sheet
Application.ScreenUpdating = True
End Sub
Double-click on the cmdClose button and add the VBA code between the two lines.
Unload Me
End Sub
On the interface sheet add exactly the same headers that you added to the database sheet
but this time start at cell reference C7.
Note: These headers must have exactly the same words that you used in the database. It
is best to copy and paste them to ensure accuracy.
This is where your filtered data will be copied to. It is not necessary to visit the database.
Directly above these headers add these values and formats to the cells shown below. This
is where you will enter your starting and finishing dates.
Cell C5 Start Date
Cell D5 Finish Date
Cell C6 Format this cell as a date type
Cell D6 Format this cell as a date type
To the right of these headers add the values below to the cell references and then the two
formulas to the cell references indicated. The text must be exact as this will form our
criteria block for the advanced filter.
Go back to the interface sheet and insert a shape, right click on the shape and choose
Assign Macro and select the macro FilterMe.
After you have added multiple values to the database, run some tests with the advanced
filter by adding start and finishing dates.
In Conclusion
In this project we have learned many things about how a Userform works and how we can
use it to speed up our data entry process. This is just the tip of the iceberg. You will find
that you will be using Userforms all the time in order to enhance the user experience,
control data movement and data entry in your applications.
OVERVIEW
Where do I start?
Great Idea Bad Design
Im going to share with you my recipe for success.
In the line of fire
Here is the nitty gritty stuff
Map the application and its development
Develop an effective user interface
Where do I start?
I have a lot of applications sent to me where people are having trouble accomplishing their
goals. Sometimes the solution is simple but impossible to implement in the application
because of the initial application design.
The thoughts of many can be summed up with the idiom I feel like Im banging my head
against a brick wall. It feels good when you stop. The way to stop is to start with good
design.
Have you ever played the game pin the tail on the donkey? You have to accomplish this
goal blindfolded and disorientated.
Don't start developments blind, don't go in blindfolded and have a stab in the dark.
Dont play pin the tail on the donkey with your work
Go in with your eyes wide open and realise that your focus early in the projects
development will prevent future failure. A stab in the dark probably won't hit the spot.
I remember the first application that I developed was a patient handover and transfer
program that enabled a ward in a very large hospital to be able to transfer patients from
bed to bed and from ward to ward. I spent two weeks researching how I could accomplish
a multitude of features that were necessary for this application to work. I listed all off the
requirements and developed little test files for each of the sections. I'm happy to say after
many years that application is still in use to this day and has saved them huge amounts of
time and paperwork.
That set a pattern for me and gave me the encouragement that I needed to continue
developing applications. It really is a good feeling when you see something that you have
developed being used by multiple users and saving heaps and heaps of time.
Contact the stakeholders or client and users to find the scope for your application (If
applicable).
Make sure that you are on the same wave length with the application owner and especially
with the end users. Meet and discuss what is required. Be very specific and listen twice as
much as you talk. Ask for a list of the proposed outcomes for the application and a list of
functions and requirements.
Now make your own list of all of the requirements, starting from the most important.
This will be your future check list and will assist with other key elements.
1) Most important requirement
Sub point 1
Sub point 2
Sub point 3
2) Second most important requirement
Sub point 1
Sub point 2
Sub point 3
Ask to look at what is currently being used to get a feel for what is needed.
Have the current file that is in use sent to you. You will learn a lot from this file about what
is required and more importantly about user habits.
Estimate data volume over time. Do this now not later
I have an Excel application to calculate data volume. Try to estimate how much data will be
entered daily then multiple this number by your expected life of the application.
150 rows daily over 5 yrs. = approx. 300,000 rows
150 does not sound like much but 300,000 is a bit more significant
Choose the right platform for the development.
Ask the question. Will Excel handle this or is it a job for Microsoft Access? This will depend
on what version of Microsoft Office you are running. With Office 2007, Microsoft changed
from a binary format to an xml format. Hence the x. [xlsx] at the end of the file extension.
This now permits greater volumes and less file corruption. But the point still remains, why
spend days developing an application that will not handle the data volume or run the test of
time.
This is the nuts and bolts of your application. Get out pen and paper and turn on
your artistic flare. Have a look at the illustration above and below.
As an example show where the data is stored and then the sheet that it will be
filtered to and any other relationships that exist.
This is ever so important because at this stage you are thinking about what
processes you have available to accomplish the desired outcomes. If you cannot
work out how it will work on a flowchart, then it will not work in the actual
application. Dont fall into the trap of saying, Ill work that out when I get to it.
Redesign the relationships now, in the design stage to facilitate the needs of the
application.
Set up a project development schedule. Stage the project and all its components.
This can be simple or complex depending on the size of the application. This could
be as simple as breaking the project into stages and days allocated for completion.
Send this to the stakeholders and or client for review. Just to make sure that you
are both on the same page.
1. A big mistake that many make is in the way data is viewed and presented.
2. Set out your data in a flat file where possible. Think of rows as records and
columns as fields. Set your data to run down the worksheet where possible.
3. Avoid merged cells, they are road blocks to analysis.
4. Filter your data first then move and analyse it in another sheet if you can. This
will dramatically improve the performance of the application.
5. In your columns [fields] do not mix data types. For example dont put text and
numbers in the same column.
Have you noticed how much work we have done and not one bit of it has been in
Excel.
Now our development will be with purpose and move along very quickly. We know
the relationships and have a good idea of how it all fits together.
Develop the most important aspects first and work toward the least important
I guess this is just common sense. Remember if the engine doesnt work it does not
matter good looking car is. So get the core elements up and running first.
Sad to say this is often omitted with Excel programs. You can have the best
application there is, but if consumer sentiment is negative, it will fail. If it can move
global markets then I'm sure consumer sentiment can sink our little file. Think of the
users experience and ask Is it clearly defined how to operate this program? Is
there a help menu available?
Get some fresh eyes to have a look at it and ask for honest feedback.
I use a video set to assist with this. Make sure you do not throw the end user in
there without any training. Remember we are all a little intimidated by new things
and especially things we do not understand. The human response is often to
degrade or even belittle things that may be presented as intimidating.
Offer personal training and follow up with support contact if possible.
Find the weaknesses and develop strategies to overcome or work around them.
Testing can take a long time but is well worth the heartache that an untested
application can cause. Dont fall into the trap of thinking that you can put the
application to use and fix problems as they occur. You will lose the trust and
confidence of the end users.
Run a trial
When the application is completed and working as you want, then run a trial
deployment. If the application/s can be deployed in sections then try to do so.
When you develop your next application why not try to use some of these suggestions.
In Conclusion
There has been a lot to learn in this book. We have looked at the basic VBA Functions
techniques and procedures.
Keep challenging yourself to learn new skills and link your skills together to build more
complex scenarios.
Always remember this: If the work that you create pleases you then it is good work. It may
not appeal to everybody but that does not matter.
You may remember the parable of the old man, the young boy and the donkey. No matter
what they did, no matter how hard they tried it was impossible to please everybody. So
dont try to please all.
I wish you well in your learning endeavors and feel free to contact me on the website to
pass on your feedback, comments and if necessary request support.
Variable Scope
Sub Macro1
Dim MyVar as Range
Set MyVar = Range(A1)
MsgBox MyVar
End Sub
If Function Macros
If Then Macro
Sub If_Range_Single()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value > 50 Then Rng2.Value = 50 + Rng1.Value
End Sub
If The Multiple
Sub If_Range_Multiple()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value > "" Then Rng2.Value = 20 + Rng1.Value
If Rng1.Value < 50 Then Rng2.Value = 50 + Rng1.Value
If Rng1.Value >= 50 Then Rng2.Value = 70 + Rng1.Value
End Sub
If The End If
Sub If_EndIf()
Dim Rng1 As Range, Rng2 As Range
Sub If_EndIf_Multiple()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Condition 1
If Rng1.Value <= 20 Then
Rng2.Value = 20 + Rng1.Value
End If
Condition 2
If Rng1.Value >20 Then
Rng2.Value = 50 + Rng1.Value
End If
Condition 3
If Rng1.Value >= 50 Then
Rng2.Value = 70 + Rng1.Value
End If
End Sub
Sub If_Input()
Dim Amount As Variant
Amount = InputBox("Enter an Amount:")
If Amount >= 50 Then
189 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 190
Sub If_Input_Else()
Dim Amount As Variant
Amount = InputBox("Enter an Amount:")
If Amount >= 50 Then
MsgBox "Amount: " & Amount
Else
MsgBox "The Amount is less than 50"
End If
End Sub
Sub If_Range_ElseIf()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value < 20 Then
Rng2.Value = 20 + Rng1.Value
ElseIf Rng1.Value < 50 Then
Rng2.Value = 50 + Rng1.Value
Else
Rng2.Value = 70 + Rng1.Value
End If
End Sub
Sub If_Nested_Multiple()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value < 20 Then
Rng2.Value = 20 + Rng1.Value
Else
If Rng1.Value < 50 Then
Rng2.Value = 50 + Rng1.Value
Else
If Rng1.Value >= 50 Then
Rng2.Value = 70 + Rng1.Value
End If
End If
End If
End Sub
If And Then
Example 1
Sub If_And_Single()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
If Rng1.Value > 50 And Rng1.Value < 100 Then Rng2.Value = 50 + Rng1.Value
End Sub
Example 2
Sub If_Input_ElseIf()
If Or Then
If Not Then
Sub If_MsgBox()
If Not 500 < 499 Then
MsgBox "500 is not less than 499"
End If
End Sub
IIf Function
Sub IIf_Msg()
Dim rng As Range
Set rng = Range("a1")
MsgBox IIf(IsEmpty(rng), "Cell is empty", "Cell is not empty")
End Sub
Sub Case_Multiple()
Select Case Range("A1").Value
Case 5
Range("B1") = 50
Case 10
Range("B1") = 100
Case 15
Range("B1") = 150
Case 20
Range("B1") = 200
End Select
End Sub
Sub Case_Else()
Select Case Range("A1").Value
Case 5
Range("B1") = 50
Case 10
Range("B1") = 100
Case 15
Range("B1") = 150
Case 20
Range("B1") = 200
Case Else
Range("B1") = ""
End Select
End Sub
Sub Case_Comma()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case 5, 10, 15, 20
Rng2 = 50
194 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 195
Case Else
Rng2 = ""
End Select
End Sub
Sub Case_To()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case 5 To 14
Rng2 = 50
Case 15 To 20
Rng2 = 100
Case Else
Rng2 = ""
End Select
End Sub
Sub Case_To_Comma()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case 5 To 10, 15 To 20
Rng2 = 50
Case 30 To 40, 50 To 60
Rng2 = 100
Case Else
195 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 196
Rng2 = ""
End Select
End Sub
Sub Case_Operators()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case Is < 20
Rng2 = 20
Case Is < 50
Rng2 = 50
Case Else
Rng2 = ""
End Select
End Sub
Sub Case_Text()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case "Online"
Rng2 = "Online is there"
Case Else
Rng2 = "Wrong text"
End Select
End Sub
196 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 197
Sub Case_Text_Compare()
Dim Rng1 As Range, Rng2 As Range
Set Rng1 = Range("A1")
Set Rng2 = Range("B1")
Select Case Rng1
Case "Online"
Rng2 = "Online is there"
Case Else
Rng2 = "Wrong text"
End Select
End Sub
Sub MessageBox()
Range("A1").Value = 50
MsgBox "The value was added successfully"
End Sub
Sub MessageBox()
Dim ButtonType As Integer
ButtonType = vbYesNoCancel + vbInformation + vbDefaultButton2
Range("A1").Value = 50
MsgBox "The value was added successfully", ButtonType
End Sub
Displaying a Message
Sub MessageBox()
'any code
MsgBox "Hello Everybody"
End Sub
A Message Box with Three Buttons and In Icon
Sub MessageBox()
Sub DeleteCheck()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo)
If CheckDelete = vbYes Then Range("A1").ClearContents
End Sub
Sub DeleteCheckMsg()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo)
If CheckDelete = vbYes Then
Range("A1").ClearContents
MsgBox "Your data has been deleted"
End If
End Sub
Sub DeleteCheckNo()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo +
vbDefaultButton2)
If CheckDelete = vbYes Then
Range("A1").ClearContents
MsgBox "Your data has been deleted"
End If
End Sub
Sub DeleteCheckValue()
Dim CheckDelete As VbMsgBoxResult
CheckDelete = MsgBox("Are you sure you want to delete this data?", vbYesNo +
vbDefaultButton2)
If CheckDelete = vbYes Then
Range("A1").ClearContents
MsgBox "Your data has been deleted"
Else
MsgBox "The value was not deleted"
End If
End Sub
Sub AddCheckShow()
Dim CheckAdd As VbMsgBoxResult
Dim rng As Range
Set rng = Range("A1")
CheckAdd = MsgBox("Do you want to add the word (Yes)", vbYesNoCancel +
vbDefaultButton2, "Add Value")
If CheckAdd = vbYes Then
rng.Value = "Yes"
MsgBox "Your data is added. The Value is " & rng
ElseIf CheckAdd = vbNo Then
rng.Value = "No"
MsgBox "Your data is added. The Value is " & rng
Else
rng.Value = ""
Sub AddCheckCase()
Dim CheckAdd As VbMsgBoxResult
Dim ButtonType As Integer
Dim rng As Range
ButtonType = vbYesNoCancel + vbInformation + vbDefaultButton2
Set rng = Range("A1")
CheckAdd = MsgBox("Do you want to add Yes", ButtonType, "Add Value")
Select Case CheckAdd
Case vbYes: rng.Value = "Yes"
MsgBox "Your data is added. The Value is " & rng
Case vbNo: rng.Value = "No"
MsgBox "Your data is added. The Value is " & rng
Case vbCancel: rng.Value = ""
MsgBox "The value is blank"
End Select
End Sub
Sub InputSimple()
'Input variable
ShowBox = InputBox("Type Your first name", "Add Name", "Type name here")
End Sub
Add a name
Sub InputName()
'Declare the variable
Dim AddName As String
'Input variable
AddName = InputBox("Type Your first name", "Add Name", "Type name here")
'Add name to the worksheet
Range("A1").Value = AddName
End Sub
Create a login
Sub Login()
'Declare the variables
Dim AddData As Range
Dim AddName As String
'Copy location
Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'Input variable
AddName = InputBox("Type Your first name", "Add Name")
'Check for a value
If AddName = Empty Then Exit Sub
'Add data to the worksheet
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
End Sub
Sub Login2()
'Declare the variables
Dim AddData As Range
Dim AddName As String
'Copy location
Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'Input variable
AddName = InputBox("Type Your first name", "Add Name")
'Check for a value
If AddName = Empty Then Exit Sub
'Check for the right name
Select Case AddName
Case "Trevor"
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
MsgBox "Welcome: - " & AddName
Case "Harry"
AddData.Value = AddName
AddData.Offset(0, 1).Value = Now
Sub LoginCheck()
'Declare the variables
Dim AddData As Range, Check As Range
Dim Nme As String
'Count attempts
Set Check = Sheet1.Range("E2")
'Destination location
Set AddData = Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
'Input variable
Nme = Application.InputBox("Add your login code name:- You have 3 attempts",
Type:=2)
'Variable for authorise
Auth = 0
'Loop through range of names
For Each cName In Sheet1.Range("D2:D14")
If cName.Text = Nme Then
AddData.Value = Nme
AddData.Offset(0, 1).Value = Now
MsgBox "Welcome: - " & Nme
Auth = 1
Exit For
End If
Next cName
'Not authorised after 3 attempts and close workbook
If Auth = 0 Then
If Check.Value = 3 Then ActiveWorkbook.Close False
MsgBox "You are not authorised"
Check.Value = Check.Value + 1
'Call macro again
LoginCheck
End If
End Sub
Sub InputAge()
'Declare the variable
Dim AddAge As Long
'Input variable
AddAge = InputBox("Type Your Age", "Add Age", "Type your age")
'Copy location
Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = AddAge
End Sub
Sub InputAge()
'Declare the variables
Dim AddAge As Long
Dim mMyAge As Range
'Set the the result range
206 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 207
BMI Calculator
End Sub
On Error GoTo 0
End Sub
Loops Macros
Do Loop
Sub Do_Loop()
'loops until a condition is met
'fills cells A1:A30 with the value of "num"
'increase the variable "num" by 1 with each loop
Dim num As Integer
num = 1
Do
Range("A" & num).Value = num
num = num + 1
Loop Until num > 30
End Sub
Do Until Loop
Sub Do_Until()
num = 1
Do Until num > 30
Range("B" & num).Value = num
num = num + 1
Loop
End Sub
Do While Loop
Sub Do_While()
'loops while a condition is met
'fills cells C1:C30 with the value of "num"
'increase the variable "num" by 1 with each loop
Dim num As Integer
num = 1
Do
Range("C" & num).Value = num
num = num + 1
Loop While num < 31
End Sub
Sub Do_While2()
'loops while a condition is met
210 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 211
num = 1
Do While num < 31
Range("D" & num).Value = num
num = num + 1
Loop
End Sub
For Loop
Sub Loop_For()
'loops 56 times
'fills cells F1:F56 with background colors
'adds a backgroud color with each loop
Dim ColCell As Integer
For ColCell = 1 To 56
Range("F" & ColCell).Select
With Selection.Interior
.ColorIndex = ColCell
.Pattern = xlSolid
End With
Next ColCell
End Sub
Sub Loop_For2()
'loops 30 times
'fills cells G1:G56 with
'adds a number and colors the number with each loop
Dim ColNum As Integer
Dim Rng As Range
For ColNum = 1 To 56
Set Rng = Range("G" & ColNum)
Rng.Value = ColNum
Rng.Font.ColorIndex = ColNum
Next ColNum
End Sub
Sub Loop_For_Step()
'loops 15 times
'fills every second cell in range H1:H30 with numbers
'changes the font size by 1point with each loop
Dim Rng As Range
Dim num As Integer
End Sub
Sub Loop_For_Step_Minus()
'loops 30 times from highest to lowest
'fills every cell in range I1:I30 with numbers from highest to lowest
'changes the font size by 1point with each loop
Dim Rng As Range
Dim num As Integer
End Sub
Sub Loop_For_Exit()
'loop stops in the middle if condition is met
'exit for loop
Dim num As Integer
End Sub
Sub Loop_For_2()
'allows for a variable amount of data in the range
'bolds all numbers in the rfange
Dim num As Integer
End Sub
Sub For_Each_Protect()
'loops through each worksheet and protect the sheet
End Sub
Sub For_Each_UnProtect()
Dim sht As Worksheet
'loops through each worksheet and unprotect each sheet
End Sub
Nesting Loops
Next mycell
Next sht
End Sub
End Sub
Sub Nested_For()
'adds numbers to multiple columns
'increases numbers by 1 for each column
Dim MyRows, MyColumns As Integer
For MyRows = 1 To 30
For MyColumns = 1 To 5
216 | P a g e Copyright 2013 Trevor Easton Online PC Learning
Appendix - Macros in this eBook Page | 217
End Sub
Sub Nested_For2()
'loops through multiple columns
'checks for a value and colors the background if it exists
Dim MyRows, MyColumns As Integer
Dim Rng As Range
For MyRows = 1 To 30
For MyColumns = 1 To 5
Set Rng = Sheet2.Cells(MyRows, MyColumns)
If Rng.Value = 20 Then
Rng.Interior.ColorIndex = 6
End If
Next MyColumns
Next MyRows
End Sub
Compile Error
Sub Compile_Error1()
'compile error
'wrong data type
Dim rng As String
rng = Range("D4")
rng.Value = 20
End Sub
Resume Next
Sub Error_Resume_Next4()
'Resume next error handling
Dim Sales As Range, Customers As Range
Dim Result As Long
'Error handler to ignore the error
On Error Resume Next
'set range objects as variables
Set Sales = Range("C4")
Set Customers = Range("D4")
Customers.Value = ""
'div#0 error here
Result = Sales / Customers
'result in the message box
MsgBox Result
On Error GoTo 0
End Sub
Range("D4") = Correct
'Resume the code from the error
Resume
End If
End Sub
Sub Error_Handler_Resume_Label7()
'Resume label
Dim Sales As Range, Customers As Range
Dim Result As Long
'Error handler label
On Error GoTo Errhandler:
'set range objects as variables
Set Sales = Range("C4")
Set Customers = Range("D4")
'Clear the value to cause the error
Customers.Value = ""
'Resume label
Fixit:
'div#0 error here
Result = Sales / Customers
'result in the message box
MsgBox Result
'Exit the procedure
Exit Sub
Errhandler:
'Correct the error with an input from the user
If Err.Number = 11 Then
Correct = Application.InputBox("Add the number of Customers:", Type:=1)
Range("D4") = Correct
'Resume label
Resume Fixit:
End If
End Sub
Sub Showme()
frmTax_Receipts.Show
End Sub
Sub Filterme()
Sheet2.Range("D4").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Range("M5:N6"), CopyToRange:=Range("C7:J7"), Unique:=False
End Sub
End With
'sort the data
Sheet2.Select
With Sheet2
Sheet2.Range("D4:K10000").Sort Key1:=Range("D4"), Order1:=xlAscending,
Header:=xlGuess
End With
'return to sheet
Sheet1.Select
'reset the form
Unload Me
frmTax_Receipts.Show
'update the sheet
Application.ScreenUpdating = True
End Sub
If the work that you create pleases you then it is good work. Be willing
to accept criticism of your work because it is an open door to
improvement. Feedback from others will help you identify
weaknesses and strengths from which you can adjust and build your
skills and expertise. Remarkable effects can be achieved when you
challenge yourself with VBA project based learning.