Excel Master The Complete 3 Books in 1 For Excel
Excel Master The Complete 3 Books in 1 For Excel
Skates
All right reserved. No portion of this book may be reproduced, stored in a retrieval system, or
transmitted in any form or by any means – electronic, mechanical, recording or otherwise –
except for brief quotation in printed reviews without the prior written permission of the
publisher or the author.
Excel VBA
Step-by-Step Illustrated Guide for Complete Beginners to
Master VBA
Introduction
What is Excel VBA?
Recording the Macros
Chapter 1: VBA Variables
Declaring Variables and their scope
Chapter 2: Strings
Chapter 3: VBA Macros
Worksheet Ranges
Chapter 4: Loops
Chapter 5: Arrays
Chapter 6: Functions
Conclusion
Excel Macros
Step-by-Step Illustrated Guide for Complete Beginners to
Master Macros
Introduction
Chapter 1: What are Macros?
Macros
More brief definition of a Macro
Macro Recorder
Is Macro Recorder enough for all our automation needs?
Chapter 2: Getting Started with VBA
What can you do with VBA?
Using the VBA
The developer option
Examples of function procedures
Referring to an object inside the sub-procedure
Referring to property of the object ‘Columns’
Chapter 3: Macro Security
Security settings
Trusted Locations
Storing macros in your Personal Macro Workbook
Macro settings
Chapter 4: Recording your first Macro
Steps to record your first Macro
Running a Macro
Assigning a macro to a button
Saving a Macro-Enabled Work Book
Chapter 5: Absolute vs. Relative Macro Recording
Absolute Macro Recording
Relative Macro Recording
How to perform Relative Macro Recording?
Example of Relative Macro recording
Chapter 6: VBA Excel Objects
Excel is an object too!
Example of uses of an object
Properties of objects
Chapter 7: Sending Email from Excel
Steps for sending the email
Chapter 8: Debugging
Bugs
Debugging in Excel
Moving down the code, statement by statement
Conclusion
Excel Formulas and Functions
Introduction
Chapter 1: What are formulas and functions?
Chapter 2: Text Formulas
Chapter 3: Comparison Formulas
Chapter 4: Operators
Chapter 5: Absolute vs Relative Cell References
Chapter 6: SUM
Chapter 7: IF
Chapter 8: AND
Chapter 9: LEN
Chapter 10: OR
Chapter 11: NOT
Chapter 12: XOR
Chapter 13: SUMIF and SUMIFs
Chapter 14: COUNT and COUNTA
Chapter 15: AVERAGEIF and AVERAGEIFs
Chapter 16: LARGE and SMALL
Chapter 17: COUNTIF and COUNTIFS
Chapter 18: VLOOKUP
Chapter 19: HLOOKUP
Chapter 20: A few notes about Pasting, Ordering and Filtering
Conclusion
Introduction
Getting Started!
Hello, there future Excel Programmers! Thanks for viewing this book.
This book has been designed to be your go-to book for excel
programming. It is drafted in simple English to make your programming
experience fun and easy. It’s fine even if you don't have the slightest
idea about Excel VBA, this book will help you get a grab on the
programming in no time. (With just a little effort) Before going further, I
would like to tell my prospective readers that who exactly is the target
audience for this book. Please find below my assumption about you:
You do have an access to a computer (A laptop or a desktop). The
computers, in turn, have a connection to the internet.
You are a frequent user of the Microsoft Excel tool
***
3. Once the customize tab is open, you can find the developer
option in the second column
4. Check the Developer Option
5. Click Ok
6. Now we will convert the formula to its value. For this right
click on the date cell, select copy. Now right-click on the cell
again, and select paste values(V).
7. Now Select the cell where you entered your name. Go to the
home tab, traverse to the font section and select bold(B). Also,
change the font size to 14.
8. Now to stop recording, go to the developer section. Select stop
recording.
Cheers! Your first project for the Excel VBA macro is finished.
To ensure that your macros are working fine, you should test
your code. Move the cursor to an empty cell, press
Ctrl+Shift+N. Within a snap, the excel code will be executed.
Your name, date and time will be displayed on the sheet. You
can also view the code that has been recorded by the excel
tool. Go to the developer tab, and click on macros. You can
now view the code that was automatically generated
There are specific rules when declaring variables in the VBA tool:
The first letter of the variable should be a character. The rest can
be numbers, letters, or punctuation characters
There is no distinguishment between the upper-case and lower-case letters
when declaring variables
A variable name should be without any space
Special characters such #, $, %, &, or! cannot be used in the variable name
The size of the variable name should not exceed 255 characters
To better understand the variables, most programmers use mix cases, for
example, PerformanceRate or Employee_Salary.
The VBA tool also puts some restriction on the variable names. Words
such as Dim, End, With, Sub, Next and For cannot be used by the
programmers as these words are reserved by VBA. If any of these words
arise in your code, you will get a compile error.
***
A good rule of thumb is to use the variable with the smallest size but it
should also serve your purpose.
***
Declaring Variables and their scope
Now let’s have fun by playing with the strings in the VBA tool. Strings
fundamentally compromise of characters that are arranged in a
sequence. The characters in the string can consist of alphabets, special
characters, numbers or any of these. The characters in the string must be
enclosed with double quotes.
Str() A string
representation of a
number
Val() A numerical
representation of a
number
Trim() To remove spaces
in a string
Left() To get a portion of
the string from the
left side
Right() To extract a
portion from the
right side
Mid() To extract any part
of the string
Len() To retrieve the
number of
characters in the
string
Not too bad prospective Programmers! You now must be having a good
understanding of how you can play with the string functions. String
function can be convenient especially when you have to manipulate
large datasets. Instead of retrieving all the functionality manually you
can write a macro code, bind it with a button and you're good to go.
Chapter 3: VBA Macros
Jumping to an advanced level
So far, we have covered some basics of the VBA Macros. We will now
be pacing up our game by jumping over to an advanced level.
VBA Macros has considerably made the lives of excel users easy. With
the implementation of VBA Macros in your worksheet, you can
significantly save up time by automating your operations of excel.
Instead of working on large data sets manually, formatting thousands of
records, applying formulas to manipulate data, you can write a VBA
Macro, bind it with the excel sheet and do all the operations within
seconds.
Worksheet Ranges
Exploring some Excel Settings
Pacing up your VBA Code
***
Worksheet Ranges
The VBA programming has got a lot to do with the ranges on the
worksheet. The following points need to be kept in mind whenever we
are working with range objects:
If you are not associating the worksheet name to the range in your code,
then you must ensure that the sheet on which you want your macros to
run must be in the active state
The Macro recorder doesn’t always create the best code. You can always
edit the Macro generated code to make it more efficient
One of the most frequently used operations of the Excel Macros is
copying a range. If you are using the macro recorder to generate you a
code while copying a range, you will get the below code.
In the above code, the VBA procedure is beginning to select the cells
from the active cell. It is then extending the range until a blank cell
arises.
One other exciting feature of VBA Macros is the selection of the entire
column or the entire row. The following is an example of the selection
of the entire row.
Similarly, the entire column functionality of excel can also be used to
select the entire column.
***
***
This will turn off the screen updates while the Macros is being executed.
To turn on the feature again, execute the below code.
Macros display alerts messages to the users while the code is being
executed. In this case, if the Excel is unattended and the Macros is
executing then the alert message will bring the code to a halt. They
require the humans to respond to the alert messages. However, there is
an option to disable the alert messages so that the Macros is not brought
to a halt.
You can also turn the alerts by writing a statement at the end of your
code. To do this, we will just change the DisplayAlerts statements to a
True condition.
Another to pace up the speed of your Macro Program is to ensure that
you declare variables at the start of your code. It is imperative that you
declare the data type of all the variables. Although Excel doesn't throw
an error if a variable's data type is left undefined but Excel won't know
the exact size of the variable. As a result of this, Excel might assign
space much more extensive than what it is required. This will result in
extra memory consumption and can also decrease the performance of
your code.
Chapter 4: Loops
Repeating blocks of VBA
Loops are essential as they make macros more capable and they also
make the code easier to write. Instead of writing numerous statements
for every cell on the worksheet, loops help to simplify your code.
Several types of loops are supported in VBA.
For-Next loop in the programming language is referred to as the
simplest type of loop. There is a control variable that acts as a counter to
the loop condition. The counter begins from the start value and
continues to be executed till the end value is reached. Code that is
written between the For statement and the next statement is repeated in
the loop. Let’s look at an example.
In the above example, we are performing a multiplication operation in
the For-Next Loop. The counter will begin from 1 and continue to
execute till the counter value is reached 50. There is the only statement
written in the For-Next loop. The statement multiplies the counter value
with the Product value and stores it in the Product variable. When the
For-Next loop counter value is reached till 50, the Product value will be
displayed on the screen. However, it is not advisable to change the
counter value in the For-Next Statement as it can generate unpredictable
results. For-Next loop can also include Exit statement within the block.
The Exit statements are placed in the For-Next block to terminate the
loop immediately.
In the following example, an Exit Statement has been inserted in the
For-Next loop.
The MsgBox will display the value of i. The value of i is incremented.
As shown in the above example, when the value of I will be equal to 4,
the code will enter in the if statement. In the if statement, the value of i
is first multiplied by 10 and then it will be printed on the screen. Soon
after this, an exit statement will be executed which will end the loop
immediately. When the above code is executed, the following output
will be displayed on the screen sequentially.
The exit statements can be beneficial especially when we want to handle
exceptions or errors in our code. If for example, there is a chance that a
garbage value can come in a specific variable. I don't handle the garbage
value, there is a chance that loop will be executed till infinity. This can
result in memory overload. To cater to this scenario, the exit statements
are placed so that the loop is terminated immediately.
Another type of loop is the Nested For-Next loop. The nested statement
comes in handy when you want to loop through tabular data or
multidimensional data. A table has data placed in both columns and
rows. One loop is used to traverse through the columns whereas the
other loop can be used to traverse through the rows. This is how you use
the nested For-Next loop.In the following example, we will be filling up
data in both the rows and the columns.
In this example, we will be filling up a 3 columns x 3 rows table. The
outer for loop fills up the data in the columns whereas the inner for loop
fills up the data in the rows. The output of the code can be seen below.
You declare the first index number, the keyword To and then finally the
last index number. All this is enclosed inside the parentheses. One
flexibility VBA offers is that you don't necessarily have to mention the
lower index every time. In this case, VBA assumes that the lower index
is 0. For example, the above statement can also be written as:
VBA by default assumes the lower index to be zero. However, if you
don’t want VBA to assume the lower index to zero, you can use the
Option Base statement to force VBA to change the lower index
accordingly. For example, if you want VBA to assume the lower index
to be always set to 1 then you should write:
You also need to ensure that this statement is written before the
declaration of the array.
So far, we have discussed one-dimensional arrays. A more natural
explanation of the one-dimensional array is a single line of a value of
the same data type. When we want to have more than one dimension in
an array, this is known as the multi-dimensional array. VBA can handle
up to 60 dimensions in the multi-dimensional array. However, this is a
sporadic case in which 60 dimensions are being used in the VBA code.
A multidimensional array is also declared using the Dim statement.
The value 10 will be stored in the element of the array that is placed in the
2nd row and 4th column. Dynamic arrays are also supported by VBA. The
advantage about using a dynamic array is that you don't have to declare the
number of elements it will hold at the start of your code. The array size is
declared at runtime. Dynamic arrays help to save memory.
Chapter 6: Functions
Performing Specific Tasks
***
Playing with built-in functions
Well the good thing about using VBA is that it has made the life of
programmer easy by defining some built-in Functions. You don’t have
to write every function from the scratch. You just need to know the
exact name of the function and Voila!
Let’s look at some built-in functions of the VBA tool.
The above procedure has been created to display the system date. In this
scenario, we have used the built-in excel function, Date. The Date
function doesn’t require any input arguments. We can also retrieve the
time by writing Time instead of Date. Time again is also a built-in
function of the excel tool.
Let’s look at another example
***
Exploring the worksheet functions
Similarly, you can also calculate the maximum value from the Range
using the Max() function of the worksheet.
Vlookup Function
If you have ever interacted with an excel programmer, I am sure you
must have heard about the Vlookup Function. You can never be an
Excel Guru if you don't know how to implement the Vlookup Function.
Vlookup is a potent function as it can help you the exact information
from a table of any size. The Vlookup Function intakes four
parameters. The first parameter represents the item that needs to be
searched in the table. For example, in the below example we are looking
for the product B. The second Parameters represents the range in which
it needs to be looked up, the third parameter represents the column
number that we want to return as a result, and finally, the four parameter
intakes a true or a false value. The true value tells the vlookup to return
a value that can be an approximate match whereas the false value tells
the vlookup to only return a value when there is an exact match. In the
following example, the user will be entering the product name in order
to retrieve its price from the table. The product name will be entered
using the InputBox Function. The price of the product will then be
displayed on the output screen using the MsgBox Function.
As shown in the below diagram, the input box is prompted on the screen
when the Macros is executed.
By the end of this chapter, you must have become very much familiar
with the Excel VBA. In this section, I will just briefly gives some
essential guidelines.
It is always a good practice to declare your variables at the start of your
code. Leaving your variables undefined will only save you from few
seconds but later on, you will have to bear with the consequences. So
make a habit to declare all the variables at the start. This will
significantly impact on your code quality.
Once you are done finalizing your code and everything is running
perfecting, make sure you do the last minute cleanup of your code.
Make sure all the code lines are indented. This will help you understand
your code better when you will review it later. Make sure all your
variables are declared and the description of the variable should be
relevant to their actual operation. For example, if a variable will be
holding Amount in it so a good practice it is to name it as "Amount"
rather than naming it as XYZ. It is always a good practice to add
comments in your code. Do a quick check to remove any redundancy in
your code.
Introduction
Getting Started!
A very disciplined approach is taken for writing this book which will
be very easy for readers to understand, who we assume are very new
to this topic. We will explore all the areas relating to Macros and will
also go in to the VBA(Visual Basic for applications). We will also
mention some important techniques for recording Macros and how
Macros are actually stored in excel(Which format?).
After reading this book, the reader will have complete knowledge
about Macros, VBA(Visual Basic for Applications), the relationship
between VBA and Macros, what is the difference between Absolute
Macro recording and Relative Macro Recording, what are VBA Excel
Objects, how to send an e-mail directly from Microsoft excel and a
dedicated chapter defining a complete approach for debugging. Apart
from this many other small level details will also be explained, so that
our reader doesn’t feel the need to google anything and deviate from
the actual topic.
Now before moving further, you should know that the VBA is not
limited or restricted to Microsoft Excel only, it is also very
consistently used with applications like MS-word and MS-
Access(Microsoft’s own database Application).
What can you do with VBA?
Some tasks require complex calculations which cannot be satisfied with in-
built functions of Excel. This is where VBA plays its part, you can write set
of instructions for performing calculations and create Macros comprising of
these instructions. You can use these Macros again and again as long as it
satisfies your needs. This would not be possible without the ability to build
customize Macros.
This is where you will write your Macros. When inside VBA editor,
click on ‘insert’. Few options will be displayed in a drop-down list.
From the drop-down list select the ‘Module’ option. This will open a
new window. In this window, you will write your Macro commands.
Don’t worry, we don’t expect that you will write commands yet. We
just wanted to show you the place in the editor where we will be
writing our Macro commands.
Now, since you know how to open VBA editor and ‘Module’ for
typing Macro commands, its time that we learn about the developer
option.
The developer option
Before we start programming in VBA, we need to do one more step: Enable
the Developer option. To do this, follow these steps:
1. Open a workbook in Excel.
As you can see in the picture given below, we have checked the
developer option.
(Shortcut: Alt+F11)
Examples of function procedures
Here we shall look at the method of writing function procedures. Function
procedures are very helpful in VBA code as they can be written to return a
value and can be called as many times as you like.
Function sum(a, b)
sum = a+b
End function
The function in the above code takes two parameters ‘a’ and ‘b’, adds
them and stores the result in a variable called Sum.
With the above example, you must have had an idea about importance
of function parameters. You can pass as much as 255 arguments to a
function or you can pass non. That’s right, you can even write a
function without giving an argument.
Example of sub-procedure
Referring to an object inside the sub-procedure
Excel VBA contains a very interesting function called “HasFormula”. This
“HasFormula” lets you know that whether a specific cell inside the excel
workbook contains a formula or not. If the cell contains a formula, it returns
true, otherwise it returns false.
Sub check ()
Dim checkFormula As Boolean
checkFormula = Range(“B1:B2”).HasFormula
MsgBox checkFormula
End Sub
Function clearRange()
Columns.(“A:A”).clear
End Function
The second line in the above function clear the contents of the cell :
“A”.
Chapter 3: Macro Security
At this stage, you have a basic concept about Macros and VBA. In this
book, we will be moving very slowly towards more advanced topics,
addressing all the aspects of every single topic.
Macro security is very easy yet very sensitive topic. The reason it is
considered sensitive is because if not understood properly it can be
dangerous for your computer because without proper security you can
get viruses through Macros, which ultimately can take the control of
your whole computer and can harm your privacy.
Security settings
Inside Excel workbook under the ‘developer’, there is an option called
‘Macro Security’. Click on the ‘Macro Security, and a new window will
appear with a list of options. The name of this window is Trust Center,
highlighted as shown below.
Trusted Locations
In ‘Trust Locations’, all of your trusted locations for opening files will be
listed. If you want to add a new location, always make sure that the new
location is trustable and secure. Otherwise you can get dangerous malware
and viruses from unknown sources. Never add unknown location for
opening files, if you want to have a secure and computer-friendly
environment (who d0esn’t want it).
Storing macros in your Personal Macro Workbook
To store the Macros in your personal Macro Workbook, first you need to
create a Macro. To create a Macro go to ‘Developer’ tab. Under the
‘Developer’ tab click on ‘Record Macro’. You will be asked to type in the
name for your Macro to save in the workbook as shown in the figure below.
You will see a text field as shown in the figure above that says, “This
workbook”. Since we want to store the macro in our personal
workbook, we will click on the list for it to drop down. Then click on
Personal Macro Workbook and then press ‘OK’. Now as the name is
set we shall perform actions which we want to store in the Personal
Macro Workbook. After that click on Stop Recording under the
‘Developer’ tab as shown in the figure given below.
Now close this workbook and you will be asked if you want to save
the changes. Click on ‘save’. You have successfully stored Macro to
your Personal Workbook.
Macro settings
Another very important option inside the trusted window is ‘Macro
settings’. This option gives you variety of choices as shown below in the
figure:
With this option Macros will be disabled, but you will be alerted if
there are any security notifications regarding Macros that are present.
All the security notifications and all the Macros are disabled with this
option
With this option you can run all types of Macros whether trusted or
not. This setting is usually not recommended as it makes our machine
vulnerable to viruses and malware software.
Chapter 4: Recording your first Macro
If you have understood the VBA then this is just piece of cake for you.
Recording the Macro doesn’t mean that you will write the code in
VBA and it will show the output in Excel workbook. The latter is true
that the output will be showed in the Excel workbook, but prior is
partially true. We said partially because ultimately VBA code is
responsible for Macro behavior, but you will not write it. It will be
automatically written.
Steps to record your first Macro
Now before we start, we would like to mention something here, the steps
we follow will create a Macro which will do a task we want Excel to do.
You can follow any steps you want as long as you understand the
concept(how to record and use Macro).
1. Go to ‘developers’ tab.
3. When the Macro has been clicked, any action you perform will be
monitored by Excel and will be converted to VBA code.
We mentioned earlier that all of the moves that you do while recording
Macro are converted to VBA code. So, where is this VBA code? This
VBA code is stored in Module.
As shown below, following are the lines that were generated while I
was performing steps during Macro Recording.
5. Select properties.
6. Select the name of the button and its caption. What you write in the
caption will appear on the button.
After following all these steps, you have successfully created your first
Macro. It was easy, wasn’t it? If you keep following all the steps
systematically and keep learning patiently then you will be able to
master all Macro techniques easily.
Saving a Macro-Enabled Work Book
When we work with Macros inside the Excel, we need to save the
workbook in a Macro-enabled format. The reason for this is that it provides
an added security from external threats. To do that first we have to click on
‘file’ tab on the top left of the screen. Now if you move down some options
you will see an option that says, “save as”. Click on it and then you will be
asked to select the location for saving the macro. Choose any location
according to your need or priority. Once you have selected a location, click
on the drop-down list as shown in figure below.
recording:
Example of Relative Macro recording
The beauty of relative Macro recording is that you can run the Macro
anywhere in the sheet, it will execute and show the results in the cells that
you have selected(currently).
Steps:
1. Go to ‘Developer’ tab.
6. We chose the cells ‘F6, G6, H6’ and wrote something as shown in
figure below:
7. After you are done updating cells, click on stop recording. You have
successfully saved a relative Macro.
8. Again under ‘Developer’ tab, click on Macros. A window will open
as shown below. Click on run Macro.
9. It doesn’t matter which cell you have selected; three cells will be
updated in row with the cell you have selected.
Chapter 6: VBA Excel Objects
If you are familiar with programming languages like Java and C++
then these topics will be very easy for you. VBA Excel object is used
for the same purpose for which we use object in Java or C++. So,
learning VBA Excel objects for you wouldn’t be difficult. The only
thing you need to learn is the syntax for calling the objects. As for my
readers who are novice to this topic, you don’t have to worry as I will
be explaining everything briefly relating to objects and their purpose.
So, keep on reading to grasp this concept like an expert.
Excel objects
The reason for all the explanation was to help you understand Excel
objects properly in an effortless manner. As we said, objects perform
some tasks. There are some objects inside Excel that perform tasks
that are very useful to us.
Excel is an object too!
As mentioned above objects perform tasks for you. Here, the whole Excel
application is an object too. It performs variety of tasks for us. Excel
performs tasks like creating graphs or charts, organizing data, providing the
ability to users to access Excel file from a range of different device, from
different locations!
We also mentioned that an object can contain other objects. Same is
the case for Excel. An Excel is an object which contain other objects.
We shall present a list four objects that are very popular in Excel. We
shall also be explaining in these concepts.
All of the objects are under the Application object. To call an object
that is under Application object, you have to use ‘.’. You cannot call
an object directly using Application object, you can call it with the
reference of previous object which has to be called too.
The 1 inside the Worksheets parenthesis is used when there is only one
worksheet in a workbook.
Now suppose you want to retrieve a value from a cell named “B3”,
then you have to move further down the hierarchy to get this value.
You need to write the following line in VBA to access this value:
Application.Workbooks(“workbook1.xlsx”).Worksheets(1).Range(“A1”).Value
Example of uses of an object
As mentioned earlier, each object has its own methods and properties. The
methods are basically the functions which an object performs. Here we will
give you an example on how to create a new worksheet in Excel using the
object “Worksheets”.
Worksheets.Add().Name = "Hello"
Now press enter. Go to back to Excel and you will see a new
worksheet created under current workbook as shown in the
screenshot given below
Properties of objects
Every object performs some tasks and each object consists of qualities or
attributes that describe what the object is. For example, a car is an object
and its properties are engine, color, model etc.
Similarly, VBA objects have properties which describe them. With the
help of VBA we can modify the properties of settings. Confusing?
This example will clear your concept.
The ‘worksheets’ object has property ‘range’ and the range object has
the property value, written as:
Worksheets(“Book1”).Range(“A”).Value()
Now, value is a property of Range and we can play with its
characteristics. You can set the value of a cell using this property and
you can display this value in a message box using the function
‘MsgBox’.
Value = Worksheets(“book1”).Range(“A”).Value
MsgBox Value
End Sub
Similarly, to set a value of a cell you can write the following code:
Sub setValue()
Now its time we actually start coding for sending an email to some
person/organization.
Sub SendMail()
Dim olApp As Outlook.Application
With olMail
.To = ‘[email protected]’
.Display
‘ ’olMail.Send
End With
End Sub
When you write this code inside VBA and hit run, Excel will take you
through a series of steps for configuring the email from which you
want to send the email. After that email will be sent to the specific
email you typed inside VBA code in front of ‘.To’.
So, it was easy sending an email through VBA? Sending email to
many users is also easy you just add two more lines of code in the
above code and Taddaa! Its done.
We need to add a ‘loop’ to the code. For the readers from ‘non-
programming’ background, loop is just a statement in a code which
allows us to execute a specific section of code repeatedly as many
time as we like.
Coming back to our topic of sending bulk emails, following changing
in the above code can help you send emails to multiple receivers(99 in
our case):
Sub SendMail()
With olMail
.To = Cells(i,1).Value
.Subject = Cells(i,2).Value
.Body = Cells(i,3).Value
.Display
‘ ’.Send
End With
End Sub
In the above code we applied Bold to some of the text to let you know
about the changing or difference between initial code and this code.
Chapter 8: Debugging
As with all the chapters before, we shall begin this chapter by
discussing a couple of terminologies. We shall discuss debugging
Excel later in this chapter in detail. First of we should know what is
debugging and how its effects our coding or to be exact: our computer
program. Mind you, the concept of debugging is not limited to Excel.
It is applied to almost every program in the computer. Why do we
need it? Well, bear with me through this chapter and you will grasp the
concept of ‘Debugging’.
Debugging
Here
is an example of simple breakpoint in program:
The red circle at third line shows that a breakpoint has been set here.
When you run the program, the VBA editor halts program execution
when it reaches breakpoint. After you have checked your program, to
continue the execution, click on small green ‘play’ button to complete
the program’s execution and get normal output as always.
You can set the breakpoint of the program in another way, you can
write one word in the VBA editor Module to halt programs execution.
The word is: ‘Stop’. Write this word anywhere in the program where
you want to set the breakpoint. When the sequential execution of
program will reach this statement, our program will enter into
debugging code.
Moving down the code, statement by statement
When you set a breakpoint, the program halts its execution at the place
where it is set. Suppose you want to move through some section of code
step by step. This can be done by pressing F8. Each time you press F8, you
move to next step. This is very useful and fast way of debugging rather than
setting breakpoints at many points in the program!
Conclusion
If you understood the major concepts behind all the chapters in this
book, you can call yourself the ‘Macro expert’. But we would
encourage you to practice the concepts conveyed in this book. By
practicing, you will better grasp complex concepts. As they say,
‘Practice makes a man perfect’. If you want to make yourself an expert
and perfect candidate for ‘Excel Macro’ jobs then you have to practice
the concepts repeatedly to get a strong grip on them.
In this book, we tried our best to explain concepts at the very basic
level. The purpose of explaining each and every step at the basic level
was to make a layman understand what Macros are and what are their
applications and how to apply them in real life. We tried our best to
cover all the major topics regarding ‘Excel Macros’ in this book.
EXCEL
FORMULAS
AND FUNCTIONS
Spreadsheets have been with us for a long time. The best-known and
most widely used spreadsheet is Microsoft Excel. Excel is easy to use
for most daily number crunching tasks and it comes with formulas and
functions that perform a host of tasks. Tasks such as summing,
manipulating text, averaging, comparing, answering what if
questions…
For example, here is a very simple problem where A2 contains 5.7 and
B2 contains 6.4. The task is to put the products of these two numbers
in into cell C2. See diagram below.
When this is done it leads to the value of the product appearing in the
cell C2. [The word 'TEXT' and the expression fx = A2*B2, which are
shown in the diagram appear automatically. You can ignore them.]
Another simple example is adding the contents of the cells A2, A3,
A4, and putting the results in A5.
Select cell c102 and type, '= SUM(a2:a101) '[this is called the
function declaration].
then press enter and cell a102 has the sum, which in this case was
6086.
A function is a predefined formula, which performs calculations with
the contents of cells.
Parameters
You may notice in the expression, '=SUM(a2:a101)' the interesting
phrase a2:a101. This is the range of the function. The range of a
function is the set of cells on which it acts. The range of the SUM
function is called its parameter, as it can vary. We will have different
ranges to which the SUM function is applied.
There are a vast number of functions in Excel, which you will become
familiar with as you master the use of this amazing tool. This little
book will look at some of the more important functions.
Chapter 2: Text Formulas
Date format
Once you filled the function in press enter and you will find the
correct expression in a2.
You can quickly fill in the rest of the column by using the 'handle' at
the side of a2.
Currency
Another possible use of the TEXT function is to convert a column of
numbers
into currency format.
Note the first number is contained in e2. Suppose the new column will
start at f10. Select f10 and type the function declaration, ' =
TEXT(e2,"$##.##") '
Press enter.
Now use the handle and move down to get the remaining conversions.
TEXT can be used in many ways like the two examples shown.
If we look at the structure or syntax of the TEXT function through a
declaration, '=TEXT(e2,"$##.##")', we see the parameters of the
TEXT function are TEXT( value, format_text ). Value, as the contents
of cells, is values; format_text, as the function acts to change the
format of the value.
Chapter 3: Comparison Formulas
You test whether two specific cells match with the IF function [We
will say more about this later]. Begin a formula with =IF( and enter
the two cell locations, with = between them. Put in a comma then
enter relevant text, in quotes, to show if the cells match. Put in another
comma and then the relevant text, in quotes, if there is a non-match.
Press enter
The comparison operators are as they are in arithmetic and they are: >,
< , < , > , =, ≠, however Excel uses <= for < , >= for > and <> for ≠.
Text concatenation may be a new idea for some of you. There is only
one text concatenation operator and that is & [ampersand]. Here is
how it works, suppose you had the string [word], "nice" in a2 and
"cat" in b2
then = a2 & b2 gives "nicecat".
All this operator does is join words or strings into one word or string.
: is the colon operator and refers to all references in a range from one
cell to another including the endpoints.
Finally, we have the single space operator. This is just an empty space.
It produces references to common cells and ranges.
Example. a2:a4 a3:a5 gives a3, a4. Obviously, a3 and a4 are the only
common cells of the ranges a2, a3, a4 and a3, a4, a5. It is the
equivalent in mathematics of the intersection operator [ ∩ ].
A very important consideration in constructing formulas is the
precedence or order of operators, in order to get the correct result. All
formulas begin with = and if you are dealing with numbers the order is
similar to the order of arithmetical operators as described by
BEDMAS [Brackets → Exponents → Division and
Multiplication → Addition and Subtraction] or PEMDAS
[Brackets → Exponents → Multiplication and Division → Addition
and Subtraction] taught in high school.
When you working with Excel, you must know about what is called
relative vs. absolute cell reference.
Now copy these three cells to a1,b1,c1 and look what happens.
In this diagram, we are using relative references. Now copy the cell
C2 to D3.
You will realize the absolute importance of these ideas when we look
at the VLOOKUP and HLOOKUP functions later.
Chapter 6: SUM
We had a look at the SUM function in chapter 1. If you have forgotten
this have another read. However, here is another look at this
extraordinary function.
The only row, which had A and B cells both less than 50 was row 4.
Here is another example of the same type. Find the rows in which the
C and D cells are both less than 50 in the table below.
Into cell E2 type the function declaration, ' =AND(C2<50,D2<50) '
then press enter.
Now use the handle to complete the task.
In this case, only rows 3 and 10 had C and D cells where the number
was less than 50.
Structure or Syntax of AND
If we look at the structure or syntax of the AND function through a
declaration, ' =AND(C2<50, D2<50)', we see the parameters of the
AND function are AND( logical test, logical test). The parameters are
two logical tests, the combination of whose results give different
results.
Chapter 9: LEN
The LEN function is one of a large number of Excel functions, which
handle strings [words]. The LEN function has a very simple format =
LEN (string). The function returns the number of letters in a string,
which is often in a cell.
There are many more string functions in Excel but we will only look at
one more, which is the MID function.
The string is the string or word, which the function is acting on,
number1 is the number of the letter in the string that you start with and
number2 is the number of the letters in the string that you want,
starting with the letter at number1.
Example. Find the rows in which either the A and B cells are less than
50 in the table below.
The function NOT gives a value of FALSE if the cell contains TRUE
and TRUE if the cell contains FALSE.
You may well ask what effect the NOT function has on cells, which
contain data apart from Boolean. The table below gives the results on
some such cells.
Here is the first example. In the table of data below, we want to add all
grades less than 50, using the functions of Excel.
Into any cell, except those with the data, type the function declaration,
' =SUMIF(D2: D15,"<50", D2: D15) ' then press enter and you get 98.
Interestingly, as the range with the criterion < 50 is the same as the
range we're summing over, we don't need the second D2: D13.
We would get exactly the same result if the function declaration was, '
=SUMIF(D2:D15,"<50") '. Try it and see for yourself.
If the range with the criterion is different from the range we're
summing over this is not true.
Into any cell, except those with the data, type the function declaration,
' =SUMIF(C2:C14,"F",D2:D15) ' then press enter. This time the result
is 334.
The only trouble with SUMIF is that it only allows one criterion. If
you want multiple criteria [plural of criterion] then you have to use
SUMIFS. Once again an example will show what this entails.
Example. Find the sum of the grades of males whose school is 'A'.
Into any cell, except those with the data, type the function declaration,
' =SUMIFS(E2:E15,C2:C15,"M", D2:D15,"A") ' then press enter. This
time the result is 259.
Example. Count all the cells with numbers only in the cells below.
Into any cell, except those with the data, type the function declaration,
' =COUNT(M2: M9, N2: N9) ' then press enter. The result is 6, as
there six cells, which contain numbers.
Now let's use COUNTA. Into any cell, except those with the data, type
the function declaration, ' =COUNTA(M2: M9, N2: N9) ' then press
enter. The result is 15, as there fifteen cells, which contain numbers.
Note that the empty cell is not counted, either by COUNT or
COUNTA.
These two functions have a very simple structure or syntax. Their only
parameter is a range.
Chapter 15: AVERAGEIF and AVERAGEIFs
The AVERAGEIF and AVERAGEIFS functions are very similar to the
SUMIF and SUMIFS functions.
Example. Suppose you wanted to find the average grade of the female
students in the table below.
Into any cell, except those with the data, type the function declaration,
' =AVERAGEIF(C2: C15, "F", E2: E15) ' then press enter. This time
the result is 55.666….
Example. Suppose you wanted to find the average grade of the male
students who went to school B from the table below.
Into any cell, except those with the data, type the function declaration,
' =AVERAGEIFS(E2:E15,C2:C15,"M", D2:D15,"B") ' then press
enter. This time the result is 60.25
Generally, the declaration is, ' =AVERAGEIFs(average_range,
criterion1 range, criterion1, criterion2 range, criterion2,) '. The
meaning of average_range is the range you're going to take the
average of. AVERAGEIFS is for situations where there is more than
one criterion.
Chapter 16: LARGE and SMALL
The LARGE and SMALL functions are very easy to understand and
use. The declaration ' = LARGE(F1: G100, 3)' finds the third largest
number in the range F1: G100.
Example. Find the fifth largest number of the set in the cells below.
Into any cell, except those with the data, type the function declaration,
' =LARGE(J2: K8, 5) ' then press enter. The result is 78.
Example. Find the second smallest number of the set in the cells
below.
Into any cell, except those with the data, type the function declaration,
' =SMALL(J2: J15, 2) ' then press enter. The result is 23.
Chapter 17: COUNTIF and COUNTIFS
Into any cell, except those with the data, type the function declaration,
' =COUNTIF(C2: C15, "F") ' then press enter. The result is 6
Into any cell, except those with the data, type the function declaration,
' =COUNTIFS(C2:C15,"M", D2:D15,"B") ' then press enter. This time
the result is 4.
The next two chapters deal with the VLOOKUP and HLOOKUP
functions. These are very useful but are often misunderstood.
We will need a number of examples to try and make this clear. Here is
the first example.
and we want to put the math grade beside each Family Name in the list
below.
This could be done by the extremely tedious procedure of copying
from the table of grades to this table. If we did this Martelil would
have 50 beside him and so on. Fortunately, the creators of Excel
foresaw this problem and devised the LOOKUP functions.
If you don't know how to order data then make sure to read the last
chapter.
Now another example, which will hopefully help cement these ideas.
Before we began it was necessary to make sure that a check was made
that the data in the lookup column was in ascending order. As it was,
there was no problem.
We can easily calculate the week's pay of the employees by typing, '=
B2*C2', into D2 then pressing enter followed by the handle.
Before finishing this function, let us examine the last parameter, which
takes the value FALSE for an exact match and TRUE for an
approximate match.
Leave the function as it is but change Diane to Diana. The table below
shows what happens.
Here is how you could access this simple table using HLOOKUP. The
problem is to find the number of Honda cars in stock, using the
HLOOKUP function, and write it in the cell B6 to the right of the
word Honda in cell A6.
The reason is that the word 'Ford' is contained in the top row of the
table with 20 below it in row 2.
HLOOKUP searches for the word Honda in the top row of the range
A1: E3. Once this is found, the 2 tells HLOOKUP to take the contents
of row 2, which is beneath Honda and put it in B6. The FALSE tells
HLOOKUP that there must be an exact match. An approximate match,
such as HINDA or HONDO would not be acceptable, whereas it might
for TRUE.
Finally, you may recall that VLOOKUP required the left column to be
in ascending order. For HLOOKUP, this is not necessary for a last
parameter value of FALSE. However, it is necessary that the top row
of the range be in ascending order if the last parameter is TRUE.
Suppose the range we are going to look up from is the table below.
and suppose the lookup is based on ID. You can see that the table has
been ordered by Family.
Here are the steps, after you have selected the range A2: E11.
(1) Click on the DATA tab on your Excel Menu.
(3) Pick Custom Sort [I always use this except for trivial sorts]
(4) Click on Family
We want the results of the female students only with a total over the
three subjects and the results put in descending order, with the highest
total at the top, down to the lowest.
Into H2, type the formula declaration, ' = E2 + F2 + G2' then press
equal. Once this is done use the handle to get the data set below.
Now select A1: H22 and go to Data.
Go to Sort & Filter and do a custom sort based on Gender. Here is
what you should have.
Now select the range A1: H14, which is the range with females and
copy this range [ ctrl-c in a PC or command-c in a Mac]. Paste in some
place, using a special paste with Values. The result is shown below.
Now we need to sort them via total in descending order. Once again
select the range and go to Sort and Filter.
Select Custom Sort and make sure you pick Total and Largest to
Smallest.
We now have the desired table.
Some of you may have wondered about Filter. What is this? Read on
to find out.
Filter
I will not spend too much time on this. Basically, it is a way of
examining a set of data using constraints but leaving the data set
intact.
Here is an example. The data set below is the same one we extracted
the females from before using order. This time we are going to have a
look at the male results in ascending order of Total [smallest to
largest], save the filtered data set elsewhere then restore the data set.
Go to the Sort & Filter tab, as you did before, after clicking on the
Data tab of the Excel menu.
This time click Filter, but NOT the down arrow, after selecting the
whole data set.
You will notice little arrows. Click on the arrow in the Gender column.
Immediately you do, the following window appears.
Fill it in as shown.
Leading to
Finally, close the Gender window and you only have the Male results.
These results are in descending order. However, as it is necessary to
put them in ascending order, you use the little arrow beside Total. A
little window appears in which ascending is an option.
Finally, restoring the original set of data is easy. Just click on the Filter
icon. When you do this the Filter arrows are removed and you have
the original data set restored.
Filtering by Color
While exploring Filter, you may have noticed the option Filter by Cell
Color.
Hitherto, this has been irrelevant, as we have only used Black and
White. However, Excel offers all sorts of color schemes. Two simple
ones for Fill Color and Font Color are shown.
To show the use of Filter by Cell Color, we have colored the data set
we have been using.
Now click on Filter after selecting the data set. This results in the
following.
Now use any little arrow, choose color and finally yellow or red.
If you wish to master it you must know the basics of formulas and
functions inside and out.
Before you proceed further with formulas and functions you must
master the material in the book to the extent that you can do the
problems in every chapter.
Once you have mastered the material in this book you are ready for all
the other things that can be done with EXCEL and the VBA
programming language!
Good Luck.
Welcome to the last page reader, I'm happy to see you here I hope you
had a great time reading my book and if you want to support my work,
leaving an honest review will be highly appreciated. Thank you so
much!
Respectfully,
William B. Skates