You are on page 1of 85

EXCEL VBA

Legal Notice

Copyright (c) 2019 William Ironside.

All rights are reserved. No portion of this book may be reproduced or


duplicated using any form whether mechanical, electronic, or otherwise. No
portion of this book may be transmitted, stored in a retrieval database, or
otherwise made available in any manner whether public or private unless
specific permission is granted by the publisher. Vector illustration credit:
vecteezy.com

This book does not offer advice, but merely provides information. The
author offers no advice whether medical, financial, legal, or otherwise, nor
does the author encourage any person to pursue any specific course of
action discussed in this book. This book is not a substitute for professional
advice. The reader accepts complete and sole responsibility for the manner
in which this book and its contents are used. The publisher and the author
will not be held liable for any damages caused.
Excel VBA
Ultimate Excel VBA Programming Step By Step
Guide to Go from Beginner to Expert
By: William Ironside
Contents
Introduction to Excel VBA
What Is VBA?
The Difference Between VBA and A Macro
The Structure of A VBA Code
The VBA Module Outline
VBA Procedures and Routines
Sub procedures
Function procedures
The Meaning of Statements
Declaration statements
Executable statements
Assignment statements
Objects
Classes
The Purpose of Collections
The Relationship Between Different Objects
Properties
Methods
Variables and Arrays
Conditions
Loops
Getting Used to the Developer Toolbar
Understanding the VBA Development Environment
Check out your first recorded macro
Understanding Excel Dot Notation
Conditional Logic
VBA Examples and Techniques
Copy and Paste
Adding Buttons to Help You Stay Organized
The Most Popular Excel Functions
Frequent Troubleshooting
Conclusion
Introduction to Excel VBA
If you’re reading this, you probably have a basic understanding of Excel
macros already. The very useful Excel tool which helps you to complete
repetitive tasks much faster. It is a precious tool to learn, and something that
will definitely be useful to you and your work for a long time to come in the
future.
Although basic macros are very useful, there is so much more tat can be
done in Excel to make your work easier, more efficient, and less stressful.
When you learn how to create shortcuts that make your job easier, you have
a much higher level of concentration and ability to truly focus on a task
instead of becoming frustrated with mundane tasks.
However, if you want to reach a level of professionalism where you can
truly use the full power of Excel, you will need to become a master of
VBA. It is much more versatile than simply recording a macro, and it
allows you to have almost endless possibilities with anything that Excel is
naturally able to do. But it does require some knowledge of programming in
order to do it properly. However, this is not a complex level of
programming, so there is no need to worry if you are not a programming
expert. You will get the hang of it in no time with a little bit of practice.
This helpful guide will teach everything that you need to know in order to
use and make the most of VBA. It is organized in logical chapters, so the
best way to get started is to follow each chapter in order so that you don’t
miss any points that connect to other points. Everything makes logical sense
in VBA. So, if you can take a moment to make sure that you have the
proper ground work ready, you can then continue your VBA programming
journey and design VBA programming actions on your own.
What Is VBA?
VBA is short for Visual Basic for Applications. It’s a type of programming
language which was developed by Microsoft. Almost everything that is part
of Microsoft Office is in one way or another based on the possibilities of
VBA. This is one of many programming languages that exist in the world,
but it is really not nearly as difficult to learn as some of the other
programming languages out there.
If you have no previous experience working with a programming language,
the first thing that you should keep in mind is that a programming language
is based on the same principles as any other language on our planet. In
order for the programming language to make sense, certain things must be
included in each command, and they have to be in the correct order. The
same way that you need to align words in your own language in a particular
order if they are to create a thought that makes sense.
However, you will not use programming languages to talk to another
person, you will use them to talk to software. More precisely, you will be
sending the software specific instructions which the software will then
complete for you. But only if you have created the right commands. If there
are any errors in the programming that you wish to send to a software, it
will not complete the task the way you want it to.
In this instance, we will be using VBA to talk to Excel and to make sure
that we can create an environment in Excel that works best for us and helps
us to be as efficient as humanly possible. You will start your journey in
learning VBA by understanding its structure. When you can understand the
structure, you can then easily use each element to create your own journey
through Excel through VBA.
The Difference Between VBA and A Macro
Before we move further, we must make a quick distinction between macros
and VBA, because they are not the same thing. Although VBA is a
programming language, a macro is not. A macro is simply a sequence of
instructions which tells Excel which simple, repetitive tasks it should do in
your stead to make your work life easier. On the other hand, VBA is an
actual programming language and far more complex than a macro. And
although this might sound intimidating to beginners, the possibilities of
VBA are above and beyond to what a simple macro can do. Although VBA
and macros may seem similar because they both allow the automation of
tasks in Excel, they are certainly not the same thing.
The Structure of A VBA Code
The best way to start your journey of learning how to use VBA is to learn
the structure of its code. When you understand the work environment that
VBA works in, you can easily maneuver your way around it and set it up so
that it works best for you.
The VBA code is a combination of programming commands which is
viewable in the VBA code view browser. No matter how long the code is,
the entire code, from the first command to the last one, will be visible in
this single window.
Each code has its own separate window, and different aspects of the code
are marked with different colors. The code is written in what is known as
the VBE (Visual Basic Editor), which you will always use when you want
to construct a new code for Excel.
The VBA Module Outline
Modules are locations in Excel where the VBA codes are stored. Each code
has its own module, and they are organized based on date and topic. You
can also organize the modules any way you like and give them names so
that you can distinguish them better. You can add and remove modules as
you like, and the better you organize them overall, the easier it will be for
you to reach the codes that you need to use at a particular moment.
VBA Procedures and Routines
A procedure is literally the part of the program that performs a task. It is the
part of the Excel software which understand the code and then follows each
step of the code that had been written down. All statements of a code
together fall under the complex understanding of a procedure. You
personally don’t have to worry about procedures because they are triggered
automatically when you decide to use a code. However, it is always good to
understand the terminology in case you see an error for one of your codes
and wonder what went wrong. Under the umbrella of procedures in general
are other types of procedures which all work together simultaneously in
order to smoothly execute a code.
Sub procedures
These are small procedures which are part of the overall general procedure
of a code. Sub procedures usually control the start and end points of a code,
and they also help to trigger other smaller aspects of an entire code, such as
styling fonts or moving from one cell to another. You will use sub
procedures when you construct your code, so you will always need to make
sure that each sub procedure that is started also has a clear end point
somewhere in the code. Sub procedures in the code are marked with the
color blue, so you will easily be able to spot them as you are constructing
your code.
Function procedures
These procedures are the ones that make complex calculations, especially
those that have to do with mathematics. When they are done with their
calculation, the function procedures will return a value into a designated
cell of your choice. You will not be coding the function procedures from
scratch. Instead, you will insert a particular mathematical formula that you
need to use somewhere in your code, and Excel will do the rest
automatically. For example, you will not write “add the following numbers”
into the code that you are making. Instead, you will type “SUM” and then
select the cells that needed to be added up together.
The Meaning of Statements
A statement is a very important part of the code because it is the trigger for
all instructions. This is the part that notifies Excel that a particular task is
about to happen and that action will be required from the software in order
to complete this process properly. Similarly to procedures, there are two
different types of statements that you need to understand.
Declaration statements
These statements determine variable and constants. Simply put, declaration
statements declare the next section of the code that is coming up. For
example, the words that you use to write the code for a sub procedure is
declaration statements because it declares that a type of procedure is about
to get started. You will not be able to change the basic structure of a
declaration statement, nor would you want to, but it is good to understand
the terminology so that you can make your way around the VBA coding
window easier.
Executable statements
These statements are more concerned with actions and how they will apply
to your overall code. They tell Excel that an action is about to take place
and they name the kind of action that will happen. In coding, even though
you can get super creative about what you want to do, you still cannot
invent a new coding language. You can only use the terminology of coding
that has been developed so far.
Assignment statements
These are very specific executable statements which further assign a value,
a variable, or a constant to parts of your code. They make the code much
easier for Excel to understand, even though it may seem that they are a little
more work for you. Although these are another sub category of statements,
they are crucial for the code to work. Your code must make each section of
its coding understandable and clear for the software to work properly.
Remember, if you make mistakes in your code, you may not even realize
that you have made a mistake until it’s too late. This is especially true if you
are working with numbers and a lot of data, because you will not be able to
realize immediately that the number you are getting is incorrect. This can
cause a lot of trouble in the future, so it is important that you understand
that each part of the code must be properly completed in order for the whole
thing to work correctly.
Objects
When Excel performs a particular action, this is called an object. An object
is therefore constructed from the previous elements that we mentioned, such
as statements and procedures. Altogether, when they are executed, they
complete an entire action that is called an object. The VBA systems
basically moves by manipulating different objects one after another in order
to complete a complete task that you would like to assign to it. This is why
it was important to cover the initial terminology first so that you can
understand that each element is part of a whole. And the whole needs to be
developed and checked properly in order for the object to be able to work
properly in the end. Other examples of objects include cell ranges,
workbooks, cell fonts, and worksheets. The most popular types of objects
are ActiveCell (the cell that has currently been selected in the Excel
workbook) and Selection objects, which in this case is the fact that you are
focusing strictly on cells for this particular task.
Objects are further defined by the classes that they have been described and
classified by.
Classes
Classes are features of the code which help to define an object. Their
special role is to define the events, properties, procedures, and variables of
an object. You will probably not be working with classes in the beginning
of your VBA journey, but they will become an important part of your
coding as you become more and more proficient in VBA. Classes are like
the blueprint of an object, which help to further define it and make sure that
the object is always working properly. The reason why you will not need to
work with them in the beginning is because coding classes is a lot more
complex than the coding that you will be used to as a beginner. Try to avoid
them for as long as you are still in the process of learning the codes and
only start playing with them when you are confident that you know enough
about every other aspect of coding in Excel. The reason why is because
even the slightest mistakes in classes will cause the entire code to fail. But
don’t worry, you will definitely get to that point someday.
The Purpose of Collections
Collections in VBA always refer to collections of objects. The feature of
collections in Excel groups similar objects together into one group. Not
only does this help you as a user make your way through the many codes
that will eventually pile up, but it will also help Excel to find the right
object at the right time. You are free to organize and rename the collections
however you like, just make sure that you always make the collections clear
and to the point so that when you want to use them you know exactly which
collection is referring to which part of the Excel use for you.
The Relationship Between Different Objects
Objects are always related to each other in one way or another. Usually,
objects are related to each other due to what is called ‘containment’,
because one object can contain one or more objects within it. Objects are
contained within each other in collections, which help to categorize them
and also help Excel to use the correct object when a particular task is
triggered. But objects are not randomly contained within one another.
Instead, they follow very strict rules of hierarchy, which is further related to
classes. This hierarchy is important for determining which object is
triggered at which point and in which chronological order. Don’t let any of
this confuse you because it all really does make perfect sense once you
become more and more familiar with Excel.
Properties
An object uses properties to help to be defined on a more detailed level. The
properties of a single object don’t have to be permanent for the entire
duration of the object’s life. you can change and alter different properties
related to a particular object without having to code the entire task all over
again from scratch. If you are just starting your journey in Excel, it is
probably best not to interfere with properties too much until you are more
comfortable with your coding skills. But do make a note of this ability
because it will greatly help you when you start organizing all of the codes
that you will be developing in the future.
Methods
Methods are also part of the structure of objects. You may start to think now
that there are too many things going on for you to remember, but it will all
become very easy to understand and to connect together into a whole once
you start working in Excel. The way objects work is that something need to
be done to the object before it is officially activated. This thing that is done
to the object is known as the method. Every method is a different action that
is performed by Excel with the object.
Variables and Arrays
Variables are the equivalent of a storage location. They are assigned names,
either automatic names or names that they have been given by the user, and
they are stored in the computer’s memory. Usually, you can determine
which part of the computer’s memory they will be stored in. Creating a
variable in Excel goes through the process known as declaring, which
means that you assign a name to the variable and also what the
characteristics of this particular variable will be. You will also need to
allocate the appropriate storage space, and you will also need to remember
the location of the storage space so that you can access it again later when
needed. You can declare variables at different levels of a module, depending
on where you want the variable to be activated. You can also use keywords
to define different variables so that you can groups variables together based
on the topic that they are referring to. This is great for making sure that you
can find a variable with ease whenever you need to use it.
If you are only using a single item in a variable, this is known as a scalar
variable. However, if you are adding a group of items to a variable then you
are dealing with arrays. Arrays share the same type of data among them,
and there is a logical relationship between each item. This is another
example where you can see how logical and organized Excel really is, and
although it may seem complex now, it will all become very clear when you
start using all of these elements to create your own codes and tasks.
Conditions
Conditions in VBA only have two purposes. To either determine something
as true, or determine it as false. Depending on which one out of the two will
be determined, Excel will decide whether something needs to be done or
not. For example, if it is TRUE that a cell is colored red, the number inside
it should be the following number in the series. Therefore, if the cell is not
red, (i.e. FALSE) Excel will not do anything in this situation and will not
add the next number in the series. If something is true, something else will
happen. Or, if something is false, something else with either happen or not
happen.
This is one of the most useful features of Excel coding and it is also the
easiest one to grasp because there are only two possible choices for you to
choose from and both of them are logical.
Loops
Loops are another way for VBA to understand that if a particular statement
is present or absent, then something else will happen as a result. However,
the difference between loops and other elements of coding which determine
whether something will happen or not, is that the function of a loop is
specified once, and then it just continues to happen for as long as it is
needed. Loops are very useful when it comes to creating tasks that will
most likely be repeated many times again in the future. These are the kinds
of tasks that you need to do when you have a huge list of data and the way
to handle it is to do one or two things over and over again. This really
makes the whole process much easier, and it also saves you a lot of time
which you can then use to do something more useful for your job.
Getting Used to the Developer Toolbar
Now that you have completed a basic level of knowledge of VBA tools and
terminology, let’s start by opening the developer toolbar before we go any
further. There will be other terminology coming up, however, let’s switch to
a few more active activities so that you don’t always have to just be looking
at words without doing anything.
The easiest way to start the process is to make sure that you have the
Developer ribbon attached to the top of Excel. This will ensure that you
have always access the developer bar when you either need to create a new
code, or when you need to use a code that you have already created in the
past. To do this, click on the round Office button, the click on Options, and
then click on “Top options for working with Excel”. You will see a box
called “Show Developer tab in the Ribbon”. Click on this option to turn it
on. Now, go to Excel’s File menu and click on Options. Click on Customize
Ribbon, and then check the box that is named “Developer”. You will now
see many new tools appear in the Excel Developer Ribbon above. It may
take you a bit of time to familiarize yourself with all of them, but once you
do, you will be on a whole new journey to making the most of Excel’s
macros and the VBA system.
Understanding the VBA Development
Environment
The VBA environment is the one part of Excel that you will obviously need
to get used to the most if you are to make the most of VBA’s capabilities.
Luckily, Excel has made this environment very intuitive, allowing you to
easily reach the areas that you need to work on at that moment. The way to
open the VBA environment is to simply to click on the VBA button in the
ribbon that you made previously. You will see a window pop open with
everything you need in order to use VBA and all of its functions.
At first, it may look like it has too many buttons for you to grab a hold of,
but you will soon realize that most of the buttons that you are seeing are
actually buttons that you have used in your life before. If you have ever
worked in Microsoft Office on a document that included text, you will have
easily seen almost all of these buttons before and you will already know
how to use them all.
The VBA environment is divided into the area on the left which is known
as the project, and the area on the right which is where you will create and
review all of the codes that you have made. Now, let’s make your first quick
little code to get you started!
In the white area on the right, type this code:
Sub Helloeveryone()
MsgBox "Hello everyone!"
End Sub
You will see the code appear in the coding window, and you will also notice
that some of the words are in a different color, as we mentioned before.
Now let’s see how it looks like when you actually run the code. To run the
code, check out the toolbar above. You will see a green triangle which looks
like a “play” button. Click on the green triangle and your code will pop out
in front of you in a new little window, and it will say Hello everyone!
Check out your first recorded macro
Now let’s watch your very first Excel macro being recorded. This is a great
way for you to understand the ins and out of how Excel actually works. And
when you see how a macro is recorded with your own eyes, it will be a lot
simpler and more logical for you to create your own codes in the future.
Everything will make a lo more sense when you are able to see how Excel
understands and prepares the codes for macros, so that they can be used
again in the future.
Most professional developers will tell you, though, that Excel tends to make
things a lot more complicated than they should be when it records things on
its own. This is a software after all, so it relies on pre-programmed codes to
help it as much as possible. When you create these codes on your own, they
will not need to be as complex and as long as Excel tends to make them.
Start by opening the Excel coding sheet side by side to your Excel
worksheet. Now, let’s make Excel record something simple such as aligning
numbers in a column. To do this, in the column A, write a list of numbers
one after the other. For example, you can write the numbers 1 to 10. Then,
click on the Record Macro button in your developer toolbar at the very top.
You will see a new dialogue box open. In this dialogue box, you will need
to give your macro a name, and from the list of selections under “Store
macro in”, make sure that you choose Personal Macro Workbook. This way,
you will ensure that all of your created macros are safely stored in the same
place and that you will not have any security issues in the future. Click OK
when you’re done. Excel is now recording your macro.
Now, go back to the cells that you wish to align in the worksheet. Select all
the numbers 1 to 10, click on the alignment that you wish to make, and
when the numbers are properly aligned, go up to the toolbar and click “Stop
Recording”. In the coding window, you will now see a new item appear,
usually with the title “Personal”, in which your new recorded macro has
been placed. You can click on this and then expand it to see how the macro
code looks.
You have now completed the recording and saving of your very first macro!
If you are someone who is just starting out on this journey, you can
continue to create and record macros this way for as long as you like. It will
be especially useful if you already know the steps that you take more
frequently when you are working in a particular Excel worksheet.
Understanding Excel Dot Notation
Dot notation is an important part of Excel codes. You will often see it when
you are developing or recording macros so it is important that you know
what it means and how you can use dot notation to help you create macros
faster and in a way that is more efficient.
Everything to the left of the dot is an object, and everything to the right of a
dot is what you want to do with an object. For example, if you see a code
that says ActiveCell.Font.Name = “Ariel” it means that you want to change
the font of the current active cell to the Ariel font.
You can use dot notation for any type of code in Excel, and the better you
get to know it the more complex and efficient your codes will be. Because
there are practically no limits to the kinds of codes you can create in VBA,
as long as you understand the language of the coding, you never have to
worry about creating a code that will end up being incorrect.
Conditional Logic
Conditional logic is a very versatile way to develop your codes in Excel.
The conditional logic feature is what will help you differentiate between
different information and different cells in your worksheet, which is the
thing that you will usually be working with most of the time. Conditional
logic is usually very difficult at first glance for people who do not have
previous coding experience, but it makes perfect sense and only takes a few
tries before you become a professional at it. There are a few different types
of logic that Excel recognizes, and we will now go through each one of
them so that you can easily choose which one suits you best for completing
a particular task in Excel.
If Statements
As the name suggests, IF something happens, then something else should
happen as a result. However, if the thing does not happen, then nothing
should change. Similar to the conditionals that you use in your own
language to distinguish between conditions, the programming language uses
the same logic to complete the same process – except in this case you are
talking to a piece of software. This is the simplest of the logical codes, and
it is certainly the first one that you should start with if you have not created
a macro before. Even though there are other conditional logics for you to
choose from, you can actually use the IF function to create any kind of
conditional logic. Of course, for the more complex codes of conditional
logic your IF code will look a lot longer than the conditional logic that you
could have used to speed things up.
Else
This is a part of the code that you can add within an IF statement to give it
more depth and complexity for what you want it to do. You will add this
part of the code after the initial request for the IF code. For example, if you
want to create a code that will tell Excel “If a number is 5 leave it, if the
number is not 5 (else) clear the cell”. This is another versatile code that you
can use however suits you best.
VBA Examples and Techniques
Now that you have a lot more knowledge about VBA and how to code your
own macros, we can now move on to giving you a better helping hand when
it comes to working in Excel. You will soon notice that when you start
coding macros, you can use elements from one macro and then tweak them
to serve you in another one. You don’t always need to code everything from
scratch in order to make your life easier.
In fact, recycling codes from old macros is one of the fastest ways to get
your work done without feeling overwhelmed by the process. So, in order
to help get you started, we will now list a number of the most useful and
most frequently used macros in Excel. You can start by using these codes as
they are, and then when you reach a more advanced level, you can tweak
the codes to make them more personal for you. When you feel like you
have reached a true level of professionalism, you can then code your own
macros entirely from scratch.
Check out the most useful and most common codes that you will need for
VBA:
Copy and Paste
This is easily the most used feature of any text software or any other
software that uses text. And although it is one of the most useful features as
well, sadly, it can easily become annoying when it needs to be done for a
long period of time. When you have to do something over and over again it
becomes tedious and annoying, and it will likely prevent you from
continuing your work without getting annoyed. This is why this is one of
the most useful macros to have saved in your Excel work. And, there are
different things that you will be looking to copy and paste in your work, so
here are all the options of copy/cut and paste that are possible in Excel.
Copy/Cut and Paste single cell
As its name suggests, this code copied info from one cell to another. You
don’t need to know any kind of coding in order to use this as a macro, but
you do need to make sure that you change the cell names to the ones that
you will be using in your work.
Sub Paste_OneCell()
'Copy and Paste Single Cell
Range("B1").Copy Range("D1")
'Cut and Paste Single Cell
Range("B1").Cut Range("D1")
Application.CutCopyMode = False
End Sub

Copying a selection
Sometimes, you will want to copy an entire selection of what you are
working on. Make sure that you change the cell range and name before
using this code.
sub CopySelection()
'Paste to a Defined Range
selection.copy range("b1")
'Offset Paste (offsets 2 cells down and 1 to the right
selection.copy
selection.offset(2,1).paste
end sub

Copy/Cut a range of cells


Make your life easier by being able to copy an entire range of cells from
one location to another. This is one of the most important and useful codes
that you will use when you are working on a large work document that
requires repetitive tasks.
Sub Paste_Range()
'Copy and Paste a Range of Cells
Range("A1:A3").Copy Range("B1:B3")
'Cut and Paste a Range of Cells
Range("A1:A3").Cut Range("B1:B3")
Application.CutCopyMode = False
End Sub

Copy/Cut an entire column or row


For copying an entire column:
Sub PasteOneColumn()
'Copy and Paste Column
Range("A:A").Copy Range("B:B")
'Cut and Paste Column
Range("A:A").Cut Range("B:B")
Application.CutCopyMode = False
End Sub

For copying an entire row:


Sub Paste_OneRow()
'Copy and Paste Row
Range("1:1").Copy Range("2:2")
'Cut and Paste Row
Range("1:1").Cut Range("2:2")
Application.CutCopyMode = False
End Sub

Copy/Cut something to another workbook


This is an incredibly useful code because when you have to move between
workbooks you also have to make many more clicks in the process. Going
back and forth in order to copy something from one workbook to another
wastes a lot of time and it also lowers your concentration at work
drastically. Here is a useful code in how to do this with a single click. Just
make sure that you change the names of the worksheets and the cell that
you are copying to and from.
Sub Paste_Other_Sheet_or_Book()
'Cut or Copy and Paste to another worksheet
Worksheets("sheet1").Range("A1").Copy
Worksheets("sheet2").Range("B1") 'Copy
Worksheets("sheet1").Range("A1").Cut
Worksheets("sheet2").Range("B1") 'Cut
'Cut or Copy and Paste to another workbook
Workbooks("book1.xlsm").Worksheets("sheet1").Range("A1").Copy _
Workbooks("book2.xlsm").Worksheets("sheet1").Range("B1") 'Copy
Workbooks("book1.xlsm").Worksheets("sheet1").Range("A1").Cut _
Workbooks("book2.xlsm").Worksheets("sheet1").Range("B1") 'Cut
Application.CutCopyMode = False
End Sub

Save all workbooks that are open


When you finish your work for the day, instead of going from one
workbook to another in order to save them, you can use a simple code to
help you out in this process.
Dim wb as workbook
For Each wb In Application.Workbooks
wb.Save
Next wb

Save As in VBA
As you work on and organize your Excel files, there will often come a time
when you wish to save your work, or part of your work, as a new file.
Instead of going through the entire process of saving your current work as a
new file, this useful code helps you to complete the entire process with a
single click:
workbook object .SaveAs(FileName, FileFormat, Password,
WriteResPassword, _
ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution,
_
AddToMru,TextCodepage, TextVisualLayout, Local)

You may want to skip adding passwords to your work for the time being,
because if you happen to get locked out of your work, it’s going to be quite
the hassle to try and get back in. although passwords are certainly great for
security, skip them until you are confident enough in your coding skills
before you go back to using them again.

Compare Cell Values


When you have hundreds of cells to work with, it is very difficult to
organize them properly without the help of VBA. There is no way that you
can efficiently scroll from one side of the worksheet to another searching
for a value that you need to use in your work at that particular time. An
example of such work is when you need to compare cell values. This simple
code will help you to compare values of particular cells so that you don’t
have to do it manually and waste a lot of time in the process.
If Range("A1").Value > Range("B1").Value Then
Range("C1").Value = "Greater Than"
Elseif Range("A1").Value = Range("B1").Value Then
Range("C1").Value = "Equal"
Else
Range("C1").Value = "Less Than"
End If

Find the maximum value of a column based on a range


Looking for a maximum value in a column (without changing the way the
column looks) is difficult because it means that you need to scroll your way
through the numbers until you find what you believe to be the biggest one.
Not only could you make a mistake in the process, but you could also lose a
lot of precious time searching for something that can be achieved with a
single click.
Function Max_Each_Column(Data_Range As Range) As Variant
Dim TempArray() As Double, i As Long
If Data_Range Is Nothing Then Exit Function
With Data_Range
ReDim TempArray(1 To .Columns.Count)
For i = 1 To .Columns.Count
TempArray(i) = Application.Max(.Columns(i))
Next
End With
Max_Each_Column = TempArray
End Function
You can display the results of this by suing the following subroutine:
Private Sub CommandButton1_Click()
Dim Answer As Variant
Dim No_of_Cols As Integer
Dim i As Integer
No_of_Cols = Range("B5:G27").Columns.Count
ReDim Answer(No_of_Cols)
Answer = Max_Each_Column(Sheets("Sheet1").Range("B5:g27"))
For i = 1 To No_of_Cols
MsgBox Answer(i)
Next i
End Sub

Highlighting duplicates
Many people use Excel to organize hundreds or thousands of cells of
information. For example, some people use it to organize the names and
email addresses of people that they could potentially contact for a project.
Excel doesn’t automatically tell you if you have a duplicate cell or not,
because it allows you to continue with your work as quietly as possible.
However, you really wouldn’t want to contact someone who have already
contacted and seem annoying. This super handy code will find the
duplicates for you so that you can delete them before anything
uncomfortable happens.
Sub Highlight_Duplicates(Values As Range)
Dim Cell
For Each Cell In Values
If WorksheetFunction.CountIf(Values, Cell.Value) > 1 Then
Cell.Interior.ColorIndex = 6
End If
Next Cell
End Sub

Add up cells that are the same color


This is a very handy way to organize your content by color without
disturbing the way that the worksheet looks like at the moment. As you
work on your Excel worksheet, you can decide to organize the content
based on the color of the cell. This will help you a lot in the future, because
there are actually a number of different codes that you can use to compile
codes for different cell colors. This is an example of how to add up cells of
a specific color.
Function Color_By_Numbers(Color_Range As Range, Color_Index As
Integer) As Double
' Dim Color_By_Numbers As Double
Dim Cell
'Will look at cells that are in the range and if
'the color interior property matches the cell color required
'then it will sum
'Loop Through range
For Each Cell In Color_Range
If (Cell.Interior.ColorIndex = Color_Index) Then
Color_By_Numbers = Color_By_Numbers + Cell.Value
End If
Next Cell
End Function

The above is very useful when you want to only focus on a single color.
However, if you want to be super organized, you can give each topic of
content in your worksheet a specific color as you go through it. There are a
total of 56 different colors in Excel that you can choose from. An even
more handy code is the one that calculates the sums for each color at the
same time. This saves you time so that you don’t have to use the above code
over and over again.
Private Sub CommandButton1_Click()
'Will look at each color and produce summary table of values
'on sheet 1 in cell A1 and downwards
Dim Current_Color_Number As Integer
Dim Color_Total As Double
For Current_Color_Number = 1 To 56
Color_Total = Color_By_Numbers(Sheets("Sheet2").Range("a11:aa64"),
Current_Color_Number)

Worksheets("Sheet1").Range("A1").Offset(Current_Color_Number, 0) =
Current_Color_Number
Worksheets("Sheet1").Range("A1").Offset(Current_Color_Number,
0).Interior.ColorIndex = Current_Color_Number
If Color_Total 0# Then
Worksheets("Sheet1").Range("a1").Offset(Current_Color_Number,
1).Value = Color_Total
End If
Next Current_Color_Number
End Sub

Delete specific rows that meet certain criteria


This is another task that requires too much of your time and will likely
make your work life more difficult unless you can find a way to simplify
the process. Luckily, Excel has a code that makes the whole process far
more easier for you. It will delete every row that meets the specific criteria
which you have written in the code.
Sub Delete_Rows(Data_range As Range, Text As String)
Dim Row_Counter As Integer
For Row_Counter = Data_range.Rows.Count To 1 Step -1
If Data_range Is Nothing Then
Exit Sub
End If
If UCase(Left(Data_range.Cells(Row_Counter, 1).Value, Len(Text))) =
UCase(Text) Then
Data_range.Cells(Row_Counter, 1).EntireRow.Delete
End If
Next Row_Counter
End Sub

Delete rows that are blank


Blank rows aren’t always a problem for people who work in Excel.
However, if you reach a point where you need to send your worksheet to
someone else, you want to make sure that it looks clean and professional.
The following code will remove all blank rows, so that your workbook
looks tighter and more professional.
Sub DeleteBlankRows()
Dim x As Long
With ActiveSheet
For x = .Cells.SpecialCells(xlCellTypeLastCell).Row To 1 Step -1
If WorksheetFunction.CountA(.Rows(x)) = 0 Then
ActiveSheet.Rows(x).Delete
End If
Next
End With
End Sub

Create new worksheet and give it a name when you open Excel
This is the perfect code for people who use Excel all the time and who
always start their work day with a new worksheet. This code is a simple
way to make your life just that little bit easier first thing in the morning,
ensuring that you don’t start your work day having to organize new
worksheets. Instead, as soon as you login to the computer, you will already
be ready to go and start working.
Private Sub Workbook_Open()
Dim New_Sheet_Name As String
New_Sheet_Name = Format(Now(), "dd-mm-yy")
If Sheet_Exists(New_Sheet_Name) = False Then
With Workbook
Worksheets.Add().Name = New_Sheet_Name
End With
End If
Save
End Sub

Function Sheet_Exists(WorkSheet_Name As String) As Boolean


Dim Work_sheet As Worksheet

Sheet_Exists = False
For Each Work_sheet In ThisWorkbook.Worksheets
If Work_sheet.Name = WorkSheet_Name Then
Sheet_Exists = True
End If
Next
End Function

Set the default sheet when you start working


Alternatively, you can also set the default worksheet that you want to start
your day with, especially if it is always the same one.
Private Sub Workbook_Open()
Sheet3.Activate
End Sub

Make a list of all file names in a directory


There will be times when you need to be aware of all the files in a particular
directory. Going through them manually one by one would cause you a lot
of trouble and take up way too much of your time, which you could be
using instead to create better work and reach your deadlines properly. This
nifty code will help you to go through the process in time and to make sure
that you can create a list of documents for yourself in an instant.
Sub List_All_The_Files_Within_Path()
Dim Row_No As Integer
Dim No_Of_Files As Integer
Dim kk25 As Integer
Dim File_Path As String
File_Path = "C:My Documents"
Row_No = 36
'Lists all the files in the current directory

With Application.FileSearch
.NewSearch
.LookIn = File_Path
.Filename = "*.*"
.SearchSubFolders = False
.Execute
No_Of_Files = .FoundFiles.Count
For kk25 = 1 To No_Of_Files
Worksheets("Sheet1").Cells(kk25 + 5, 15).Value = .FoundFiles(kk25)
Next kk25
End With
End Sub

List the files in a particular folder


Likewise, you can also use a similar code to list the files in a particular
folder instead of in an entire directory. You may need this code for work,
but you also use it to help organize the files in your computer or to share
this information with other people without actually giving them access to
any sensitive stuff in your computer system.
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\VBA Folder")
For Each oFile In oFolder.Files
Cells(i + 1, 1) = oFile.Name
i=i+1
Next oFile

Save a range in the form of a CSV file


You could do this manually by clicking on File and then selecting how you
want something to be saved. However, it does take a bit of time to do this
and it can easily become very difficult to do it when you have a long range
that you need to deal with and organize. Here is a great code to help you
overcome this problem and make your life that much easier.
Function ExportRange(WhatRange As Range, _
Where As String, Delimiter As String) As String
Dim HoldRow As Long 'test for new row variable
HoldRow = WhatRange.Row
Dim c As Range 'loop through range variable
For Each c In WhatRange
If HoldRow <> c.Row Then
'add linebreak and remove extra delimeter
ExportRange = Left(ExportRange, Len(ExportRange) - 1) _
& vbCrLf & c.Text & Delimiter
HoldRow = c.Row
Else
ExportRange = ExportRange & c.Text & Delimiter
End If
Next c
'Trim extra delimiter
ExportRange = Left(ExportRange, Len(ExportRange) - 1)
'Kill the file if it already exists
If Len(Dir(Where)) > 0 Then
Kill Where
End If
Open Where For Append As #1 'write the new file
Print #1, ExportRange
Close #1
End Function
Using hyperlinks with VBA
Hyperlinks are also some of the most useful and most often used functions
in Excel, especially if you use a worksheet to collect a variety of data.
Hyperlinks help you to quickly go to a link either inside your computer
system or perhaps somewhere else on the Internet. Luckily, macros allow
you to complete every action that you can possibly think of using
hyperlinks. We’ll go through all of the options in order to give you the best
possible outline of how to use VBA to create brilliant tasks with the help of
macros. This will save you a lot of time and make your work life that much
easier.
Adding a hyperlink with VBA
If you just want to add a hyperlink code to a particular cell or collection of
cells, use this code:
Sub AddHyperlinkToCell()
ActiveSheet.Hyperlinks.Add Range("A1"),
Address:="https://www.example.com/"
End Sub

Adding text to your hyperlink


If you want to be a little more specific with your link and how it displays,
you can easily add text to the hyperlink which will tell you exactly where
the link is going to take you. This is code that you will be using in this
particular situation:
Sub TextToDisplayForHyperlink()
ActiveSheet.Hyperlinks.Add Range("A1"),
Address:="https://www.example.com/", TextToDisplay:="Example"
End Sub

Adding hover text to your hyperlink


If you want to be even more organized, or if perhaps the text of your
hyperlinks becomes repetitive after a while, you can easily use VBA to add
a floating text to your hyperlink. When someone hovers over the link, the
text will pop up, whose purpose is to give the viewer more information
about what hides behind the hyperlink. This is very useful when you want
to organize even more content in your worksheet.
Sub ScreenTipForHyperlink()
ActiveSheet.Hyperlinks.Add Range("A1"),
Address:="https://www.example.com/", TextToDisplay:="Example",
ScreenTip:="This is the link for Example"
End Sub

Remove all hyperlinks from the worksheet


This may not be something that you will be using very often, but there
might come a time when you want to remove all hyperlinks from a
worksheet. If you were to do this manually it would take you a very long
amount of time to complete this process. To delete all hyperlinks with a
single code, use this:
Sub RemoveAllHyperlinksInASheet()
ThisWorkbook.Sheets(1).Hyperlinks.Delete
End Sub

Open a link in a new browser


This is very useful when you are about to open a number of different links
but you want each one to open in a separate tab. This is very useful for
ensuring that you can open multiple links without disturbing the initial link
that you were about to open. This will allow you to stay organized and
prepared for work whenever you need it. This is the code that you will use
to complete this task:
Sub FollowHyperlinkForWebsite()
ActiveWorkbook.FollowHyperlink Address:="https://www.example.com",
NewWindow:=True
End Sub

Link to a folder or file in your drive


Like we mentioned before, hyperlinks also allow you to link to sections of
your computer. This is also great for organization and will make it a lot
easier for you to reach the files that you need to open frequently, or the files
and folders that you always need for work. Although this particular link will
not be useful to people who are not on your computer, you can make this
link useful by making it connect to a file on a shared drive so that everyone
can see it if needed. Use this code to do so:
Sub FollowHyperlinkForFolderOnDrive()
ActiveWorkbook.FollowHyperlink Address:="C:\Desktop\ExcelFiles"
End Sub

Switch to s cell in another sheet


Anything that makes you go back and forth between sheets or workbooks
while you work is truly a waste of time on many levels. You never want to
do these repetitive tasks if you don’t need to, especially because they will
easily make you feel irritated and unwilling to continue with your work. To
avoid this problem, you can use this simple code which will make your life
a lot easier:

Sub GoToAnotherCellInAnotherSheetInTheSameWorkbook()
ActiveSheet.Hyperlinks.Add Range("A1"), Address:="", SubAddress:="'"
& Sheet2.Name & "'!B2", TextToDisplay:="Click Here to Go to
Sheet2, cell B2 of the same workbook"
End Sub

Show all hyperlinks in a worksheet


Even though hyperlinks will be a different color, they are still very difficult
to find if there are many of them in a single worksheet. There may be times
when you will want to organize all the hyperlinks that you’ve added into the
worksheet, and it will be a lot easier to do so if the hyperlinks are clearly
visible. To do this, use this code:
Sub ShowAllTheHyperlinksInTheWorksheet()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(1)
For Each lnk In ws.Hyperlinks
Debug.Print lnk.Address
Next lnk
End Sub

Highlight values that are greater than something else


This is a very useful code to help you find the particular values that you
would like to work with at a particular moment. Instead of having to
manually go through the entire sheet to find larger values, something which
could take hours if you have hundreds of values insert, this code will show
you exactly which values you are looking for. Just make sure to enter the
value that you are looking for.
Sub HighlightGreaterThanValues()
Dim i As Integer
i = InputBox("Enter Greater Than Value", "Enter Value")
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue,
Operator:=xlGreater, Formula1:=i
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
.Interior.Color = RGB(31, 218, 154)
End With
End Sub

Highlight values than are lower than something else


This is of course the opposite option than the one we have mentioned
above.
Sub HighlightLowerThanValues()
Dim i As Integer
i = InputBox("Enter Lower Than Value", "Enter Value")
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue,
Operator:=xlLower, Formula1:=i
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
.Interior.Color = RGB(217, 83, 79)
End With
End Sub

Find negative numbers


In case you need to look for numbers which have a negative value, use this
code to help you out:
Sub highlightNegativeNumbers()
Dim Rng As Range
For Each Rng In Selection
If WorksheetFunction.IsNumber(Rng) Then
If Rng.Value < 0 Then
Rng.Font.Color= -16776961
End If
End If
Next
End Sub

Highlighting a specific section of text


There will be times when you will look for a particular section of text in
your worksheet. Perhaps you would like to check if a section of text exists,
or maybe you would like to edit it to say something else. The fastest way to
do this is to use a code which will help you to find exactly what you are
looking for:
Sub highlightValue()
Dim myStr As String
Dim myRg As Range
Dim myTxt As String
Dim myCell As Range
Dim myChar As String
Dim I As Long
Dim J As Long
On Error Resume Next
If ActiveWindow.RangeSelection.Count> 1 Then
myTxt= ActiveWindow.RangeSelection.AddressLocal
Else
myTxt= ActiveSheet.UsedRange.AddressLocal
End If
LInput: Set myRg= Application.InputBox("please select the data
range:", "Selection Required", myTxt, , , , , 8)
If myRg Is Nothing Then
Exit Sub
If myRg.Areas.Count > 1 Then
MsgBox"not support multiple columns" GoToLInput
End If
If myRg.Columns.Count <> 2 Then
MsgBox"the selected range can only contain two columns "
GoTo LInput
End If
For I = 0 To myRg.Rows.Count-1
myStr= myRg.Range("B1").Offset(I, 0).Value
With myRg.Range("A1").Offset(I, 0)
.Font.ColorIndex= 1
For J = 1 To Len(.Text)
Mid(.Text, J, Len(myStr)) = myStrThen
.Characters(J, Len(myStr)).Font.ColorIndex= 3
Next
End With
Next I
End Sub

Highlight cells that contain cells with misspelled words


This is a very useful code! It helps you to quickly find the cells that have a
spelling mistake in them. It makes it very easy to spot the areas that you
may need to work on a little bit more. But not only that, this code also helps
you find words in another language which you may have used throughout
the worksheet.
Sub HighlightMisspelledCells()
Dim rng As Range
For Each rng In ActiveSheet.UsedRange
If Not Application.CheckSpelling(word:=rng.Text) Then
rng.Style= "Bad" End If
Next rng
End Sub
Find cells that contain an error
There are times when an error occurs in a cell without you even knowing.
Sometimes this is because you have not entered a code properly, but other
times it could just be due to the click of your mouse which you do not
realize that you’ve made. In either case, errors in cells make it very difficult
for Excel to correctly calculate everything in the worksheet. This means
that you might end up relying on data which is not accurate, and depending
on how serious your job is, this could also become a serious problem. This
is the code that will help you to quickly go through your worksheet and
make sure that you are able to fix all of the errors that need fixing.
Sub highlightErrors()
Dim rng As Range
Dim i As Integer
For Each rng In ActiveSheet.UsedRange
If WorksheetFunction.IsError(rng) Then
i = i + 1 rng.Style = "bad"
End If
Next rng
MsgBox "There are total " & i & " error(s) in this worksheet."
End Sub

Highlight cells that have a specific text in them


Sometimes, you may need to look for cells which have a specific word in
them. This happens when you need to organize the spreadsheet in a way
that does not allow you to see these particular variables visibly. You cannot
possibly organize a worksheet to show you every single cell at the same
time, especially if you have many cells that you need to work on. This is
exactly where VBA comes in to help you find the things that need finding
as quickly as possible. Hopefully even with a single click.
Sub highlightSpecificValues()
Dim rng As Range
Dim i As Integer
Dim c As Variant
c = InputBox("Enter Value To Highlight")
For Each rng In ActiveSheet.UsedRange
If rng = c Then
rng.Style = "Note"
i=i+1
End If
Next rng
MsgBox "There are total " & i &" "& c & " in this worksheet."
End Sub

Highlight cells which have unique values


This is a great code to help you find anomalies in your worksheet. This
doesn’t necessarily mean that the cells are incorrect, it simply means that
you will use this code when you are looking for values that are out of the
ordinary. You will need to choose the selection of the worksheet in which
you will be looking for these values. You could potentially look for them
throughout the entire worksheet, although this might bring back too many
variables for you to go through so it is better to look for them through a
selection.
Sub highlightUniqueValues()
Dim rng As Range
Set rng = Selection
rng.FormatConditions.Delete
Dim uv As UniqueValues
Set uv = rng.FormatConditions.AddUniqueValues
uv.DupeUnique = xlUnique
uv.Interior.Color = vbGreen
End Sub

Printing a custom page or pages


This is a great code to use when you also have to print pages from your
worksheet. Especially if you are often printing particular pages with
particular settings needed from the worksheet. Once you set this code up the
way you needed it to look like, you will never have to go through the whole
process of setting up printing again. Simply click on the VBA button (more
about that below) and print the pages that you need in no time.
Sub printCustomSelection()
Dim startpageAs Integer
Dim endpageAs Integer
startpage= InputBox("Please Enter Start Page number.", "Enter
Value")
If Not WorksheetFunction.IsNumber(startpage) Then
MsgBox"Invalid Start Page number. Please try again.", "Error"
Exit Sub
End If
endpage= InputBox("Please Enter End Page number.", "Enter
Value")
If Not WorksheetFunction.IsNumber(endpage) Then
MsgBox"Invalid End Page number. Please try again.", "Error"
Exit Sub
End If
Selection.PrintOutFrom:=startpage, To:=endpage, Copies:=1,
Collate:=True
End Sub

Sort worksheets according to their name


This is a very handy code that will help you to organize worksheets by their
name with a simple click. Although you might be a very organized person,
perhaps there will be times when you will receive a worksheet from
someone else who has not taken the time to organize their work. Instead of
wasting time making things more logical for you, you can simply use this
code to get everything ready for you to start working on the worksheet you
need right away.
Sub SortWorksheets()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort
Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub

Send your active workbook via email


Here’s another great quick code to help make your work life easier. If you
need to send a particular workbook via email, this is the code that will
complete this process automatically for you. However, this particular code
is only for the worksheet that is currently active on your screen. But this is
fine because it is assumed that you will be sending the worksheet that you
are working on at the moment.
Sub Send_Mail()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = "example@example.com"
.Subject = " Report"
.Body = "Hell, Please find attached Report."
.Attachments.Add ActiveWorkbook.FullName
.display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub

Save a particular range as PDF


This is a great way to create a PDF document that will specifically look at a
particular part of the worksheet. You would not be able to do this another
way, because it would require you to first remove the section that you
would like to turn into a PDF in a Word document and then continue your
work from there. This is obviously a much slower way to complete your
work, which is why this code will help you complete this task without
having to leave Excel.
Sub HideSubtotals()
Dim pt As PivotTable
Dim pf As PivotField
On Error Resume Next
Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.n ame)
If pt Is Nothing Then
MsgBox "Example text."
Exit Sub
End If
For Each pf In pt.PivotFields
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
End Sub

Create a table of contents


This is a great code either for yourself or for someone who you are working
with on this particular project. Instead of getting lost in mountains of
content, you can quickly create a table of contents with a simple code,
which will help everyone have an easier time getting to know the content in
the worksheet. If you were to develop something like this manually, it
would literally take you hours to complete the task. Especially if there are
many cells of content that you need to go through.
Sub TableofContent()
Dim i As Long
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Table of Content").Delete
Application.DisplayAlerts = True
On Error GoTo 0
ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1)
ActiveSheet.Name = "Table of Content"
For i = 1 To Sheets.Count
With ActiveSheet
.Hyperlinks.Add _
Anchor:=ActiveSheet.Cells(i, 1), _
Address:="", _
SubAddress:="'" & Sheets(i).Name & "'!A1", _
ScreenTip:=Sheets(i).Name, _
TextToDisplay:=Sheets(i).Name
End With
Next i
End Sub

Use VBA to search on Google


Did you know that VBA can also help you to search for information on the
internet without having to leave Excel? This saves you an even greater
amount of time, because you don’t have to constantly switch from one
window to another. This code will do all of the difficult tasks for you and it
will then come back with the Google information that you were searching
for.
Sub SearchWindow32()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Enter here your search here", "Google Search")
search_string = query
search_string = Replace(search_string, " ", "+")
'Uncomment the following line for Windows 64 versions and comment out
Windows 32 versions'
chromePath = "C:Program
FilesGoogleChromeApplicationchrome.exe"
'Uncomment the following line for Windows 32 versions and comment out
Windows 64 versions
chromePath = "C:Program Files
(x86)GoogleChromeApplicationchrome.exe"
Shell (chromePath & " -url http://google.com/#q=" & search_string)
End Sub

Remove any extra spaces from selected cells


This code helps you go through and complete one of the most annoying
things that you would ever have to do in a worksheet. Not only is it
incredibly difficult to find extra spaces just by looking at hundreds and
hundreds of cells, but an extra space can also really ruin the visual display
of the overall worksheet. This excellent code will help you find extra spaces
instantly by highlighting them, after which you can decide whether or not
you need and want to remove this extra space or if you want to keep them
instead.
Sub RemoveSpaces()
Dim myRange As Range
Dim myCell As Range
Select Case MsgBox("You Can't Undo This Action. " & "Save
Workbook First?", _
vbYesNoCancel, "Alert")
Case Is = vbYesThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
Set myRange = Selection
For Each myCell In myRange
If Not IsEmpty(myCell) Then
myCell = Trim(myCell)
End If
Next myCell
End Sub

Convert date into day of the week


Imagine if, in a worksheet with hundreds or thousands of cells, you
suddenly need to change all of the dates into days of the week. Doing this
manually would likely drive you crazy and would take days to complete.
There would be no way of speeding this process up manually because you
would still have to change each cell individually. Luckily, this code will
complete the entire process for you with a single click, making your life
that much easier.
Sub date2day()
Dim tempCell As Range
Selection.Value = Selection.Value
For Each tempCell In Selection
If IsDate(tempCell) = True Then
With tempCell
.Value = Day(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub

Count the number of words in a spreadsheet


Although this is perhaps not something that you would often have to do in
Excel, since the software isn’t exclusively for text documents, this code will
help you complete the process and count the number of words properly.
Sub Word_Count_Worksheet()
Dim WordCnt As Long
Dim rng As Range
Dim S As String
Dim N As Long
For Each rng In ActiveSheet.UsedRange.Cells
S = Application.WorksheetFunction.Trim(rng.Text)
N=0
If S <> vbNullString Then
N = Len(S) - Len(Replace(S, " ", "")) + 1
End If
WordCnt = WordCnt + N
Next rng
MsgBox "There are total " & Format(WordCnt, "#,##0") & " words
in the active worksheet"
End Sub
Adding Buttons to Help You Stay Organized
Excel buttons are a great way to assign macros to a very visible area on
your screen while you are working. The buttons may look very simple, but
there is a number of things that you can do with them in order to
personalize your experience. We will now go through the things that you
can do with the buttons so that you can quickly create your own buttons and
start working. Buttons will make your work life much easier, and they will
allow you to prepare your Excel work environment is a very personalized
way.
Adding a macro button
Adding a new macro button is very easy and something that you will
quickly get used to the more time you spend in Excel. From your developer
section, click on “Insert” and then click on “Button”. Next, you will have to
move your mouse over an area in your spreadsheet in order to form the
shape of the button. The button can be as big or as small as you would like
it to be, but it is usually best to cover an area of about 6 cells. This is big
enough for you to see, but also small enough so that the button won’t
interfere with what you see on the worksheet. When you release the left
click of your mouse a pop up window will appear in which you will click
on “Assign Macro.”
From here, you can choose whether you want to assign an existing macro,
create a new macro from scratch, or record a macro.
Add some style to your button
You have almost endless possibilities when it comes to the design of your
button. However, before we move on to that, it is best to mention that the
purpose of the button is to make your life easier. If you spend too much
time making the button look pretty, then you will have waste a lot of time
which you could have spent working on your project at work.
If you do decide to give your button some style, you can change the name,
shape, color, and text style of your macro. Perhaps the color feature will be
the most useful one if you have a number of different macro button on the
same spreadsheet. Assigning the buttons different colors will help you to
find the right button as soon as you need it, instead of having to read the
title of each button.
The Most Popular Excel Functions
There are numerous built-in functions in Excels which help you to speed up
the process for speeding up specific tasks. Because Excel was not only
created for professionals, but for people all over the world, the Excel team
really wanted to make sure that you can make your way around the
spreadsheet as soon as possible. Here are some of the most popular Excel
built-in functions that you will use in your time working in an Excel
worksheet.
CLEAN – This function will remove everything that cannot be printed later
on. This function will save you a lot of time from having to go back and
edit the symbols and letters that your printer will avoid.
TRIM – Removes spaces that are duplicates at the beginning or the end of
a text string. Spaces can be very annoying both in your spreadsheet and
then especially when you are trying to code something. This built-in
function will get rid of all the unwanted spaces so that you don’t have to
spend any time doing it yourself.
LOWER – This function will make sure that any text which is part of this
code will be converted to the lower case. There is almost nothing more
annoying than having to manually click next to individual letters over and
over again just because you want to change the letter to lower case.
UPPER – Similarly, this function will convert all letters in a text string to
the upper case, so that you don’t have to go back and type them all again.
FIXED – This function will round a number to a specified number of
decimal places. This is great for when you are asking Excel to make
automatic calculations by using formulas, and then you need it to make sure
that the given numbers are restricted to a particular decimal place.
VALUE – Converts text into a number. This is something that you will be
using when, for example, you want to turn the names of months in the year
into their equivalent numbers. Or perhaps if you want to convert the names
of the days of the week into numbers as well.
REPLACE – Replaces one string of text with another string of text that
you have specified in the remained of the code. This is very useful for when
you want to edit content in your spreadsheet and make sure that the entire
spreadsheet is using the right text as information.
IFERROR – This is a great function that will check for errors in the area
that you have specified. If there are any errors spotted, the code will notify
you about the problem right away so that you can easily go back and fix it
before it’s too late. This is one of the best built-in functions to make sure
that all of the work you do in your spreadsheet is of the highest accuracy.
ERROR.TYPE – Looks for errors in cells and then returns with
information telling you what kind of error has been made. This can really
help you to make sure that you can fix the error quickly, and not have to
spend time going back and forth looking for what could be the cause of the
problem.
ISBLANK – Looks for cells that have been left blank. It is not always a
bad thing for a cell to be blank, but if you want to check if you have entered
all of your data into the required range, this built-in function can help you to
quickly find a location where you might have forgotten to enter a value.
TYPE – Tells you what type of data has been entered into a particular cell
or a particular cell range. This is a great function for bringing you closer to
the content that you are working with in Excel, and make sure that
everything you are working with is based on accurate information.
CELL – Returns all information that is based on a particular cell that you
have selected to provide you with more information. Great for staying up to
date with how your cells are doing and if there is anything in them that may
need to be changed.
INFO – Returns the information about the current environment that you are
working in. it is a great function that will help you to find any errors that
may have occurred in your environment along the way.
LOOKUP – Looks for a specific value of data within your spreadsheet, and
then notifies you when this value has been found – whether in a single
location or perhaps in multiple locations. This is an excellent built-in
function to help you search for information instantly in your spreadsheet.
MAX – Returns the largest value from a specified range. You can use this
in any range across your spreadsheet, as long as you make sure to insert the
right range as part of your code.
MIN – Returns the smallest value from a range that you have selected to
work with.
Frequent Troubleshooting
If you are just starting out with VBA, you will probably often find yourself
in a situation that you don’t know how to get out of or perhaps you don’t
understand how you got yourself in this position in the first place. Luckily,
Excel is such a versatile program that everything can be easily fixed, so you
really don’t have to worry about things going horribly wrong. However,
because we want to help you have all the information that you need in one
place, we will now go through the most frequently asked questions and
troubleshooting that most beginners have problems with.
“I get a message asking me if I want to enable or disable a macro”
This will happen if there was an error during the creation of a macro, or
perhaps if there was an error when you were closing the worksheet the last
time you were working on it. What happens in this case is that there
remains an empty module from the corrupted macro, in which case Excel is
no longer sure if you want to run the macro or not.
To fix this problem, right click somewhere on your sheet and select View
Code. This will open the VBA editor and show you the project explorer.
Look for the workbook that you are currently working in, and then on the
left side, look for the module that was associated with this worksheet but is
now not working. Right click on the module that is no longer working and
then click on Remove Module. You can repeat this task for any module
where you need help removing a macro that has somehow corrupted. When
you do this correctly, Excel will no longer ask you whether or not you wish
to run macro.
“How do I run a macro automatically when a cell changes content?”
Instead of always having to check if a macro has run when a cell changes its
value, you can create a macro that will do this automatically for you. As
long as you assign the correct range for the macro to keep track of what is
happening in a particular cell, the macro will run accordingly as soon as
anything in the cell changes. This will provide you with a lot of help and
saved time so that you will never forget to properly complete a new cell,
because the macro code will do that for you.
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Range("C5")) Is Nothing Then
Exit Sub
Else
'The cell you are monitoring has changed!
'Do whatever you need to do...
End If
End Sub

“How do I stop other people from seeing my macros?”


For privacy reasons, you won’t always want people to see your macros or
how you have created them. This is because there is a possibility that
people could mess with your macros and there by mess with the content of
your worksheet. This is definitely not something that you want to
experience, because you will not know where the changes were made or
which part of your worksheet is no longer accurate. The way that you can
avoid this situation happening is by locking your macros from anyone else
being able to see them.
To do this, make sure that you are in the VBA editor, and then click on
Tools. Click on Properties and then look for the tab that says Protection.
Then, click on “Lock project for viewing”. You will then be prompted to
enter a password, which will protect all of your macros from anyone who
does not have the password. However, make sure that you remember the
password. Because if you cannot remember it, then the macros will also be
hidden from you, which is not what you want to happen.
“How do I quickly find an empty cell in a column?”
Instead of having to scroll for ages to find a new empty cell in which you
can enter new content, you can quickly find the first empty cell by using a
very simple code to help you out. This is the code that you should create
with a macro to help you out with this process:
If ActiveSheet.UsedRange.Count < 2 Then
MsgBox 1
Else
MsgBox Columns("A:A").Find(What:="",
LookAt:=xlWhole).Row
End If
“How do I skip to the last row in my worksheet?”
Similarly to the previous question, you don’t want to scroll for ages to find
the first empty row that you can use to continue entering new information.
You can also achieve this wit a short and simple code that will complete the
task for you with a single click.
MsgBox ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
“How do I perform the same operation across all workbooks?”
This is a super useful code that will help you to do one and the same thing
across all workbooks. This will save you a lot of time, because if you were
to do this manually, you would have to go through each workbook and do
the same tasks over and over again. And if there are many cells for you to
go through, this will take hours of your time.
Sub AllFolderFiles()
Dim wb As Workbook
Dim TheFile As String
Dim MyPath As String
MyPath = "C:\Temp"
ChDir MyPath
TheFile = Dir("*.xls")
Do While TheFile <> ""
Set wb = Workbooks.Open(MyPath & "\" & TheFile)
MsgBox wb.FullName
wb.Close
TheFile = Dir
Loop
End Sub
“What do I do when some of my files become read-only?”
This is a frequent thing that happens in Excel, which makes many people
stressed when they try to fix it. Read-only files are those which you can no
longer edit, which means that you can no longer enter content in them. This
can be frustrating when you are in the middle of work and how have to deal
with this. Luckily, there is a very simple way around this problem without
having to worry too much about it.
Simply clear out the folder in this location: c:\windows\temp directory, and
then restart your machine.
“Excel keeps crashing, telling me that there are not enough resources?”
This is something that can happen if you have a worksheet with truly a lot
of content in it. Excel is certainly a great piece of software, but even
software can become overwhelmed. Anything can cause this message to
appear, so there is not one particular location that you will need to look for
in order to solve this problem. Instead, follow these steps to fix the issue:

1. Close all Excel windows


2. Restart your machine
3. Use the Search option on your machine to search for all files
that end with the extension .xlb
4. Rename each file with a new extension .old
5. Now open Excel again

“How do I reset a range that has been used?”


When you have a spreadsheet that has a lot of information, to the amount of
hundreds of cells, there may come a time when an entire range needs to be
reset to its original number. Perhaps this would happen if you made a
mistake somewhere along the way, or if there was an error in one of the
macros that caused this disturbance. As you can imagine, this is not
something that you would ever want to do manually, nor would you be able
to. You cannot possible remember what was in each cell range that needs to
be restarted. And even if you could, it would take you hours to complete
this task. Instead, use the code below to fix the issue.
Sub DeleteUnused()

Dim myLastRow As Long


Dim myLastCol As Long
Dim wks As Worksheet
Dim dummyRng As Range

For Each wks In ActiveWorkbook.Worksheets


With wks
myLastRow = 0
myLastCol = 0
Set dummyRng = .UsedRange
On Error Resume Next
myLastRow = _
.Cells.Find("*", after:=.Cells(1), _
LookIn:=xlFormulas, lookat:=xlWhole, _
searchdirection:=xlPrevious, _
searchorder:=xlByRows).Row
myLastCol = _
.Cells.Find("*", after:=.Cells(1), _
LookIn:=xlFormulas, lookat:=xlWhole, _
searchdirection:=xlPrevious, _
searchorder:=xlByColumns).Column
On Error GoTo 0

If myLastRow * myLastCol = 0 Then


.Columns.Delete
Else
.Range(.Cells(myLastRow + 1, 1), _
.Cells(.Rows.Count, 1)).EntireRow.Delete
.Range(.Cells(1, myLastCol + 1), _
.Cells(1, .Columns.Count)).EntireColumn.Delete
End If
End With
Next wks

End Sub

'================================
Sub TestForMergedCells()

Dim AnyMerged As Variant

AnyMerged = ActiveSheet.UsedRange.MergeCells

If AnyMerged = False Then


MsgBox "no merged"
ElseIf AnyMerged = True Then
MsgBox "all merged"
ElseIf IsNull(AnyMerged) Then
MsgBox "mixture"
Else
MsgBox "never gets here--only 3 options"
End If

End Sub
'=====================================

“How do I pick random items from a selected list?”


Depending on how many things you need to pick randomly, this could
potentially take forever to complete. Luckily, there is a code that will help
you to achieve this in an instant.

1. Enter the item selection range, e.g. C1:C80


2. Then, in D1:D80 enter =RAND()
3. Sort the list in column D
4. Press F9 to generate the numbers
5. Repeat this again if you want to get new numbers
Conclusion
Going through the power and the agility in VBA is quite the adventure. It is
always very daunting for people who are only getting started in Excel, but
to be honest, without VBA you are not using Excel the way that it was
supposed to be used. If you are only looking to create a simple spreadsheet,
you could do this easily in many other programs without a problem. But
with Excel, spreadsheets are a form of art which help you organize content
better than any other software ever could. There have been numerous
software options that claim to be a replacement for Excel, but they
absolutely do not have the amount of options that Excel has, and they likely
never will. Excel was created by some of the most talented people in
Microsoft, so it is no wonder that it has become such a wonderful and
important tool for people who need to organize information and content.
But Excel was never just created to provide users with a generic
spreadsheet. The intent has always been to create a working environment
that can be versatile and save the user as much time as possible, so that they
can focus on other aspects of their job. Tis is why VBA was developed
within Excel. Even though spreadsheets are excellent for organizing
content, sadly, the way that content is organized in a spreadsheet requires
numerous repetitive tasks that repeat over and over again. This is something
that can easily become annoying and ruin your concentration for any further
projects.
VBA is not nearly as complex of a programming tool as it appears to be.
Most importantly, it is a programming language that relies on logic a lot,
which means that it is not difficult to code in VBA as long as you take some
time to learn the basic language elements that we previously mentioned.
The great thing about VBA is that it does not require any additional
purchases of tools or equipment in order to work. As long as you have a
keyboard and a mouse attached to your computer, you will be able to work
with VBA without any problems. Its most powerful feature is the power to
quickly complete repetitive tasks, which means that it relies on quite simple
formulas that are short and to the point of what they are supposed to
achieve.
You will likely start your coding journey in VBA by creating very long
codes because the process of long codes will make more sense to you than
having to look for a shortcut. But the same way that you get comfortable
with shortened words in the language that you are speaking, you will also
quickly notice ways that you can shorten your codes so that you don’t have
to work on them so much.
Experts have said that it takes about three months of practice to learn the ins
and outs of VBA and how to use it almost to its fullest potential. The thing
that you will quickly find surprising is that the more you work with VBA,
the more you will actually remember many of the codes by heart and you
will eventually not even need to rely on someone else’s codes or functions
in order to make VBA work for you.
VBA is also a fantastic skill to have when you are working with other
people. This is especially true in the areas of finance and marketing,
because they usually have many numbers, statistics and graphs that they
need to work with on a daily basis, which means that VBA makes life a lot
easier for these people because it speeds up their work and makes sure that
they no longer have to waste any time. But this is why you also need to take
some time to learn VBA, because if everyone else on your team knows how
to do something but you don’t, then you will find yourself lost and having
to deal with quite a few problems.
VBA also allows you to interact with other Office applications, which
means that you will not have to open different windows all the time
whenever you want to switch to working on something else. VBA allows
you to send emails, insert images, create Word documents, prepare
PowerPoint templates, and so much more. The great thing about Office
applications is that they have a great way or working with one another. But
none are as versatile and as quick to adapt as Excel is.
The best way to start your learning journey with VBA is to use someone
else’s examples to practice. This is why we provided you with the best and
most popular codes to get you started so that you don’t have to worry about
anything right off the bat. By using examples that have already been coded,
you will be able to better familiarize yourself with VBA codes and you will
quickly find ways to make simpler codes of your own. Remember, VBA is
based on logic. Keep working and practicing until you reach a point where
you can complete and set up VBA tasks intuitively. You will also notice that
you will be much better at noticing potential errors before they have even
occurred. Every new skill that you develop in your job can help you to
reach even higher levels in your workplace, and most importantly, it will
enable you to help your colleagues so that you can all work faster as a team.
EXCEL VBA
Legal Notice

Copyright (c) 2019 William Ironside.

All rights are reserved. No portion of this book may be reproduced or


duplicated using any form whether mechanical, electronic, or otherwise. No
portion of this book may be transmitted, stored in a retrieval database, or
otherwise made available in any manner whether public or private unless
specific permission is granted by the publisher. Vector illustration credit:
vecteezy.com

This book does not offer advice, but merely provides information. The
author offers no advice whether medical, financial, legal, or otherwise, nor
does the author encourage any person to pursue any specific course of
action discussed in this book. This book is not a substitute for professional
advice. The reader accepts complete and sole responsibility for the manner
in which this book and its contents are used. The publisher and the author
will not be held liable for any damages caused.
Excel VBA
Ultimate Excel VBA Programming Step By Step
Guide to Go from Beginner to Expert
By: William Ironside

You might also like