100% found this document useful (4 votes)
236 views489 pages

101 Ready To Use Excel Macros

Uploaded by

william.cw.cheuk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
236 views489 pages

101 Ready To Use Excel Macros

Uploaded by

william.cw.cheuk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 489

COPYRIGHT

Copyright © 2019 by MyExcelOnline.com – Version 2019.9

All rights reserved. This publication is protected by copyright, and


permission must be obtained from the publisher prior to any
prohibited reproduction, storage in a retrieval system, or
transmission in any form or by any means, electronic, email,
mechanical, photocopying, recording or likewise.

SPECIAL SALES
For more information about buying this eBook in bulk quantities, or
for special sales opportunities (which may include custom cover
designs, and content particular to your business or training goals),
please send us an email to [email protected]

MYEXCELONLINE ACADEMY COURSE


We are offering you access to our online Excel membership course –
The MyExcelOnline Academy – for only $1 for the first 30 days!

Click on this $1 Trial link to get access to this special reader offer!

CONNECT WITH US
Website, blog & podcast: https://www.myexcelonline.com/

Download Our App: Android or iPhone

Email: [email protected]

2
AUTHOR BIOGRAPHY

John Michaloudis is the Founder and Chief Inspirational Officer of


MyExcelOnline.com.

John is currently living in the North of Spain, is married and has two
beautiful kids. John holds a bachelor’s degree in Commerce (Major
in Accounting) and speaks English/Australian, Greek and Spanish.

John decided to leave the “Corporate World” - during his 15 year


professional stint as an Accountant & Financial Controller in Avon &
General Electric - and start MyExcelOnline, where he could teach the
rest of the world on a much grander scale how to use Excel effectively
via his blog tutorials, podcast shows, webinar trainings and online
courses!

Bryan Hong is a contributor at MyExcelOnline.com. He is currently


living in the Philippines and is married to his wonderful wife Esther.
Bryan is also a Microsoft Certified Systems Engineer with over 10
years of IT and teaching experience!

3
TABLE OF CONTENTS
COPYRIGHT .......................................................................................................... 2
SPECIAL SALES..................................................................................................... 2
MYEXCELONLINE ACADEMY COURSE ........................................................ 2
CONNECT WITH US ............................................................................................ 2
AUTHOR BIOGRAPHY ....................................................................................... 3
TABLE OF CONTENTS ....................................................................................... 4
GETTING STARTED ............................................................................................ 9
How to Use This E-Book ..........................................................................................10
Why VBA? ................................................................................................................11
How to Use Macros .................................................................................................12
Enabling VBA in Excel..............................................................................................20
Insert Button to Run a Macro ...................................................................................22

BASIC MACROS ................................................................................................. 26


Add Custom Footer .................................................................................................27
Add Custom Header ................................................................................................31
Add Date In Footer ..................................................................................................35
Add Date In Header .................................................................................................39
How to Autofit Columns ..........................................................................................43
How to Autofit Rows ...............................................................................................47
How to Insert Multiple Columns ..............................................................................51
How to Insert Multiple Rows ....................................................................................56
How to Insert Numbers ...........................................................................................61
How to Remove Text Wrap ......................................................................................66
Unmerge Cells ........................................................................................................70
Use Calcuator..........................................................................................................73

4
CHART MACROS .............................................................................................. 76
Add Chart Title .......................................................................................................77
Change Chart Type .................................................................................................83
Convert Chart into Image ........................................................................................87
Resize All Charts .....................................................................................................91

FORMULA MACROS ........................................................................................ 96


Add a Degree Symbol to Selection ...........................................................................98
Add letters A-Z ......................................................................................................102
Calculate Square Root ...........................................................................................106
Convert Date into Day ...........................................................................................110
Convert Date into Month .......................................................................................115
Convert Date into Year ..........................................................................................120
Convert Formulas into Values................................................................................125
Convert Negative Numbers to Positive ...................................................................130
Convert Roman Numbers into Modern Numbers ....................................................135
Convert Selection to Lower Case ...........................................................................140
Convert Selection to Proper Case ..........................................................................144
Convert Selection to Sentence Case .......................................................................148
Convert Selection to Upper Case ...........................................................................153
Convert Time into Hour.........................................................................................157
Convert Time into Minutes ....................................................................................161
Convert Time into Seconds ...................................................................................165
Convert UK Dates to US Dates ...............................................................................169
Convert US Dates to UK Dates ...............................................................................173
Extract Number from Text ....................................................................................177
Format Values to Dollars and 2 Decimal Places......................................................182
Get Word Count from Worksheet ...........................................................................186
Increase Cell Values by a Number .........................................................................191
Decrease Cell Values by a Number ........................................................................196
Insert Time Range .................................................................................................201
Multiply all Values by a Number ............................................................................206
Remove a Character from Selection .......................................................................212

5
Remove Apostrophe from Numbers.......................................................................216
Remove Characters at the Start .............................................................................220
Remove Date from Date and Time .........................................................................226
Remove Time from Date and Time ........................................................................230
Remove Decimals from Numbers ..........................................................................234
Replace Blanks with Zeros .....................................................................................237
Trim Extra Spaces from Selection ..........................................................................242

HIGHLIGHTING MACROS ............................................................................ 246


Highlight Active Row & Column .............................................................................247
Highlight All Errors with a Red Color .....................................................................251
Highlight All Named Ranges ..................................................................................255
Highlight Alternate Rows in Selection ....................................................................259
Highlight and Count a Specified Value...................................................................263
Highlight Cells with a Single Space ........................................................................269
Highlight Cells with Comments .............................................................................274
Highlight Custom Text ..........................................................................................278
Highlight Duplicates .............................................................................................283
Highlight Unique Values in Selection .....................................................................288
Highlight Max Value in Selection ...........................................................................291
Highlight Min Value in Selection ............................................................................296
Highlight Negative Values .....................................................................................300
Highlight Top 10 Values of Selection .....................................................................305
Highlight Bottom 10 Values of Selection................................................................310
Highlight Values Greater Than ..............................................................................315
Highlight Values Lesser Than ................................................................................321
Spell check and Highlight Misspellings ..................................................................327

PIVOT TABLE MACROS ................................................................................ 330


Disable Enable Get Pivot Data................................................................................331
Hide Pivot Table Subtotals .....................................................................................337
Refresh All Pivot Tables .........................................................................................342
Remove Autofit Columns on Refresh .....................................................................346

6
PRINTING MACROS ....................................................................................... 351
Print All Comments of a Worksheet .......................................................................352
Print the Selected Area ..........................................................................................356
Print with a Narrow Margin ....................................................................................359

WORKBOOK MACROS .................................................................................. 365


Attach Current Workbook into an Email Message...................................................366
Close All Workbooks and Save Changes ................................................................371
Copy Current Worksheet into a New Workbook .....................................................375
Create a Backup ....................................................................................................379
Get the Count of Unsaved Workbooks ...................................................................383
Set the Active Worksheet .......................................................................................388
Show a Closing Message .......................................................................................391
Show a Welcome Message .....................................................................................394

WORKSHEET MACROS ................................................................................. 397


Delete All Other Worksheets..................................................................................398
Delete Blank Worksheets .......................................................................................401
Hide All Other Worksheets ....................................................................................405
Insert Multiple Worksheets ....................................................................................409
Protect Active Worksheet.......................................................................................414
Unprotect Active Worksheet ..................................................................................418
Protect All Cells With Formulas ..............................................................................422
Protect All Worksheets ..........................................................................................426
Save Each Worksheet as a PDF File.........................................................................432
Sort All Worksheets Alphabetically ........................................................................436
Unhide All Hidden Rows and Columns ...................................................................439
Unhide All Worksheets ..........................................................................................443

7
ADVANCED MACROS ................................................................................... 447
Convert Selected Range into an Image...................................................................448
Convert Text into Speech ......................................................................................451
Create Table of Contents ......................................................................................454
Excel to Powerpoint ..............................................................................................460
Insert a Linked Image ............................................................................................466
Insert a Row After Each Row ..................................................................................470
Save Selected Range as PDF...................................................................................475
Use Goal Seek .......................................................................................................479
Use the Data Entry Form .......................................................................................484

8
Go to Table of Contents

GETTING STARTED
How to Use This E-Book .............................................................. 10
Why VBA? ................................................................................... 11
How to Use Macros..................................................................... 12
Enabling VBA in Excel ................................................................. 20
Insert Button to Run a Macro ...................................................... 22

9 GETTING STARTED
Go back to Getting Started Go to Table of Contents

How to Use This E-Book


Macros are one of the most powerful features in Excel and learning
how & when to use them will make you into an Excel superstar!

There are 101 ready-to-use Macros in this eBook for you to become
more efficient at Excel!

To get the most value out of this eBook, we recommend that you
follow our easy to use step by step guide in each Macro.

Download the Workbooks that pertains to each Macro and practice


with the Macro by running it on the sample data provided.

Each Macro tutorial has 2 workbooks which you have access to:

1. “No Code” - You need to copy & paste the VBA code provided
in this eBook to the VBA Editor and Run the Macro; and
2. “With Code” –You need to simply Run the Macro.

Here is the download link that has all the workbooks covered in
this eBook.

The Table of Contents is interactive & will take you to a Macro


within this eBook with a mouse click!

How to Use This E-Book 10 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Why VBA?
Do you repeat various Excel actions like copy & pasting data,
formatting, hiding and unhiding worksheets, to name a few?

Did you know that you can automate your tasks in Excel with a
couple of mouse clicks?

If you keep on repeating the same thing over and over


again, creating an Excel VBA Macro is perfect for you! It saves you
time so you can do things that you like doing, like going home
early!

VBA stands for Visual Basic for Applications. Visual Basic (VB) is a
programming language from Microsoft used to create your own
custom applications.

VBA on the other hand, is a smaller version of VB that is included in


each Microsoft Office application, Excel being one of them. With
VBA, you do not need to pay somebody to custom program for your
additional functionalities that you need in Excel. You can create your
own by combining VBA and Excel!

A common scenario is when you take 30 minutes each day to


prepare and format a report. You can use VBA Macros to reduce
this work to a single button click! The time savings just stack up
and your boss will be impressed with your efficiency.

Not satisfied with the coverage of Excel functions? You can create
your own Excel user-defined function using VBA. You can then
repeatedly use your user-defined function in the spreadsheet.

Read on and enjoy what the world of VBA has to offer.

Why VBA? 11 GETTING STARTED


Go back to Getting Started Go to Table of Contents

How to Use Macros

The 101 Macros in this book simply need to be copied to the VBA
Editor and you will be able to use them immediately. When the
Macro can be further modified to fit your needs or to expand its
capabilities, we will explain how to in this guide.

A Macro is also called a Procedure.

If this is your first time using a Macro, read the introductory section
here so that you will be more comfortable with the various Macro
lingo.

Here are a few of the most common Macro concepts:

Variables:

We use variables a lot in our code. Variables are containers of your


data that is represented by a name you specify. In other words, they
are a great way to store and manipulate data.

Loops:

Looping is one of the most crucial programming techniques. It


allows us to repetitively do something with just a few lines of code.

Code Comments:

Any line that is preceded by an apostrophe ‘ - turns into a green


line of code in the Visual Basic Editor window.

How to Use Macros 12 GETTING STARTED


Go back to Getting Started Go to Table of Contents

This line is ignored in the code and is used to “document” the code
so that it is easier for you/others to understand what the code does.

Backup your files!

Before using any of the Macros in your Excel files, a best practice is
to back up the Excel file first. This is to provide a safety net if data
gets modified in a different way than you expect. You can safely test
the Macro this way with your current data and load the previous file
if unintended changes take place.

These are the common terms when using Macros:

• Code – this is the VBA text

How to Use Macros 13 GETTING STARTED


Go back to Getting Started Go to Table of Contents

• Visual Basic Editor – this is the window where we write/paste


our VBA code in. You can get to this window by going to
Developer > Code > Visual Basic or shortcut ALT+F11

• Procedures – these are also called Macros and serve as the


containers of our code. Notice that there are no spaces in the
procedure name: AddDateInFooter()

• Modules – these are containers of the Procedures

How to Use Macros 14 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Project – this is a container of Modules. A single Excel workbook is


a project of VBA code

Here is a list of common keywords you will see in Macros. You can
always refer back to this list as you go through the examples in the
book:
Keyword Definition
as Used when defining the data type of a variable
dim Used for declaring variables
Combined with the For keyword (e.g. “for each…”) to access the individual components in
each a collection
else Combined with the then keyword for alternate scenarios
end Used to end a procedure
exit Used to leave a procedure prior to the end statement
for Used to iterate one or more actions a specific number of times
function Defines a block of code that can return a value
if Used for specifying conditions
integer Used to define a number between -32,768 and 32,767
is Compares two object references
long Used to define a number between -2,147,483,648 and 2,147,486,647
next Used with the For keyword to create set of repetitive instructions
on error Used to capture and handle errors properly
resume Used with the On Error keyword to handle errors properly
string Used to define text variables
sub Defines a block of code that does not return a value
then Combined with the If keyword for alternate scenarios
to Used with the For keyword when repeating
with Used to perform multiple operations on a single object

How to Use Macros 15 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Running a Macro

Running a Macro is very straightforward:

Go to Developer > Code > Macros

Macros can be located in:

• This Workbook; or
• All Open Workbooks

Make sure your Macro name is selected from the list.

Click Run.

Then your code will execute from there.

How to Use Macros 16 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Using the Quick Access Toolbar to run a Macro

If you use a specific Macro frequently, then it is a good idea to add


it to the Quick Access Toolbar in Excel for easy access.

Go to Customize Quick Access Toolbar Dropdown > More


Commands

How to Use Macros 17 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Under the Choose commands from drop down, make sure to select
Macros.

Pick your Macro and click Add.

Your Macro should now be added to the Toolbar. Click OK.

How to Use Macros 18 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Click on the Macro icon that is now located on the top or bottom of
your Ribbon and it will now run this Macro!

How to Use Macros 19 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Enabling VBA in Excel


Most Excel workbooks do not have the Developer tab activated.

This is needed in order to execute & create Macros. We can easily


enable it in a few steps! Make sure you have Excel open…

STEP 1: Right click anywhere on your Ribbon and select Customize


the Ribbon:

STEP 2: Make sure the Customize Ribbon is selected. Then select


the Developer option under Main Tabs. Click OK.

Enabling VBA in Excel 20 GETTING STARTED


Go back to Getting Started Go to Table of Contents

After that you should be able to see the Developer tab enabled:

.XLSX vs .XLSM

For a Macro to run, the Workbook’s file extension should be in a


.xlsm format – which is a Macro enabled format.

You can change this under:

File > Save As > Save As Type > Excel Macro-Enabled


Workbook(*.xlsm)

Enabling All Macros

To ensure all Macros in this book will run without any issues, go to
File > Options > Trust Center > Trust Center Settings > Macro
Settings

Ensure Enable all macros is selected. Click OK.

Enabling VBA in Excel 21 GETTING STARTED


Go back to Getting Started Go to Table of Contents

Insert Button to Run a Macro

What does it do?

We can insert a button and configure it to run a specific Macro. It


makes things simpler and the user only needs to click this button
every time they want to execute the Macro.

We will be using the Autofit Columns Macro Workbook to


demonstrate how to create our own button.

The Macro will autofit all of the columns to fit to its contents.

You can use this technique to create buttons to run any Macro.

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK

Insert Button to Run a Macro 22 GETTING STARTED


Go back to Getting Started Go to Table of Contents

STEP 1: Let us select a shape you prefer. Go to Insert >


Illustrations > Shapes > Rounded Rectangle:

Insert Button to Run a Macro 23 GETTING STARTED


Go back to Getting Started Go to Table of Contents

STEP 2: Place the shape anywhere on the sheet that you want.

Double click on the shape to type the text: Autofit All Columns.

You can change the font, font size, and center the text as well.

STEP 3: Right click on your shape and select Assign Macro

Insert Button to Run a Macro 24 GETTING STARTED


Go back to Getting Started Go to Table of Contents

STEP 4: We have one Macro that is already created for you.

Do not worry as we will discuss the Auto Fit All Columns Macro later
in the book.

Select This Workbook from the dropdown, then select the


AutoFitAllColumns Macro. Click OK.

Let us try it out now! Click on your shape/button and see the magic
happen! All of your columns are now autofitted!

Insert Button to Run a Macro 25 GETTING STARTED


Go to Table of Contents

BASIC MACROS
Add Custom Footer .................................................................... 27
Add Custom Header ................................................................... 31
Add Date In Footer ..................................................................... 35
Add Date In Header .................................................................... 39
How to Autofit Columns ............................................................. 43
How to Autofit Rows................................................................... 47
How to Insert Multiple Columns ................................................. 51
How to Insert Multiple Rows ....................................................... 56
How to Insert Numbers .............................................................. 61
How to Remove Text Wrap ......................................................... 66
Unmerge Cells............................................................................ 70
Use Calcuator ............................................................................. 73

26 BASIC MACROS
Go back to Basic Macros Go to Table of Contents

Add Custom Footer

What does it do?

Adds a custom footer with your text

Copy Source Code:


Sub AddCustomFooter()

Dim inputText As String


inputText = InputBox("Enter your text for the custom
footer", "Custom Footer")
'Add your custom text to the right footer
With ActiveSheet.PageSetup
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = inputText
End With
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add Custom Footer 27 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Ever wanted to add a footer to your Excel spreadsheet? You can add
a custom footer using Excel Macros!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Add Custom Footer 28 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

STEP 4: Type in your custom footer, click OK.

Add Custom Footer 29 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

To check if the footer did get added, go to File > Print:

Now you should be able to see your text on your footer!

Add Custom Footer 30 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Add Custom Header

What does it do?

Adds a custom header with your text

Copy Source Code:


Sub AddCustomHeader()

Dim inputText As String


inputText = InputBox("Enter your text for the custom
header", "Custom Header")
'Add your custom text to the center header
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = inputText
.RightHeader = ""
End With
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add Custom Header 31 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Ever wanted to add a header to your Excel spreadsheet? You can add
a custom header using Excel Macros!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Add Custom Header 32 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

STEP 4: Type in your custom header, click OK.

Add Custom Header 33 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

To check if the header did get added, go to File > Print:

Now you should be able to see your text on your header!

Add Custom Header 34 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Add Date In Footer

What does it do?

Add the current date to the footer

Copy Source Code:


Sub AddDateInFooter()

'For this example, we are using the left footer to show


the date
With ActiveSheet.PageSetup
.LeftFooter = "&D"
.CenterFooter = ""
.RightFooter = ""
End With
ActiveWindow.View = xlNormalView

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add Date In Footer 35 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Adding the current date in the footer is very easy using Excel
Macros! You can customize the text even as you see fit if prefer
something else instead of the current date.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Add Date In Footer 36 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

To check if the header did get added, go to File > Print:

Add Date In Footer 37 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Now you should be able to see the current date on your footer!

Add Date In Footer 38 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Add Date In Header

What does it do?

Add the current date to the header

Copy Source Code:


Sub AddDateInHeader()

'For this example, we are using the center header to


show the date
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = "&D"
.RightHeader = ""
End With
ActiveWindow.View = xlNormalView

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add Date In Header 39 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Did you know that you can add the current date in header in Excel?
You can add this via Excel Macros in a single click!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Add Date In Header 40 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

To check if the header did get added, go to File > Print:

Add Date In Header 41 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Now you should be able to see the current date on your header!

Add Date In Header 42 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

How to Autofit Columns

What does it do?

Autofit all columns to fit to its contents

Copy Source Code:


Sub AutoFitAllColumns()
Activate
Cells.Select

'See the magic happen!


Cells.EntireColumn.AutoFit
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

How to Autofit Columns 43 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

My column widths are all over the place and I want to make it look
more presentable. Did you know you can autofit columns using
Macros in Excel?

And with this cool trick, it can be done in just one click!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Make sure Sheet2 is selected as we want to autofit the


columns there because that’s the tab where the data table is stored.

Paste in your code and Select Save. Close the window afterwards.

How to Autofit Columns 44 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

How to Autofit Columns 45 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

With just one click, all of the columns are automatically fitted now!

How to Autofit Columns 46 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

How to Autofit Rows

What does it do?

Autofit all rows to fit to its contents

Copy Source Code:


Sub AutoFitAllRows()
Activate
Cells.Select

'See the magic happen!


Cells.EntireRow.AutoFit
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

How to Autofit Rows 47 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

My row heights are all over the place and I want to make it look
more presentable. Instead of adjusting them one by one, did you
know you can autofit rows using Macros in Excel?

And with this cool trick, it can be done in just one click!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Make sure Sheet2 is selected as we want to autofit the rows


there.

Paste in your code and Select Save. Close the window afterwards.

How to Autofit Rows 48 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

How to Autofit Rows 49 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the rows are automatically fitted now!

How to Autofit Rows 50 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

How to Insert Multiple Columns

What does it do?

Asks for a number of columns, then inserts it to the right of your


selected cell

Copy Source Code:


Sub InsertMultipleColumns()

Dim numColumns As Integer


Dim counter As Integer

'Select the current column


ActiveCell.EntireColumn.Select
On Error GoTo Last
numColumns = InputBox("Enter number of columns to
insert", "Insert Columns")

'Keep on insert columns until we reach the desired


number
For counter = 1 To numColumns
Selection.Insert Shift:=xlToRight,
CopyOrigin:=xlFormatFromRightorAbove
Next counter
Last: Exit Sub
End Sub

How to Insert Multiple Columns 51 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

How to Insert Multiple Columns 52 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Ever wanted to try to insert multiple columns just by typing in a


number? It is possible using Macros in Excel!

Plus you also get to learn some programming tricks along the way,
how cool is that?

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

How to Insert Multiple Columns 53 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

STEP 3: Let us test it out!

Select any cell that you want to insert columns on. Go to Developer
> Code > Macros

Make sure your Macro is selected. Click Run.

How to Insert Multiple Columns 54 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

We want to insert 3 columns. Type in 3.

With that, you are now able to insert multiple columns using
Macros!

How to Insert Multiple Columns 55 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

How to Insert Multiple Rows

What does it do?

Asks for a number of rows, then inserts it at the bottom of your


selected cell

Copy Source Code:


Sub InsertMultipleRows()

Dim numRows As Integer


Dim counter As Integer

'Select the current row


ActiveCell.EntireRow.Select
On Error GoTo Last
numRows = InputBox("Enter number of rows to insert",
"Insert Rows")

'Keep on inserting rows until we reach the desired


number
For counter = 1 To numRows
Selection.Insert Shift:=xlToDown,
CopyOrigin:=xlFormatFromRightorAbove
Next counter
Last:Exit Sub
End Sub

How to Insert Multiple Rows 56 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

How to Insert Multiple Rows 57 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Did you know you could insert multiple rows using Macros in
Excel?

With just a loop and providing a number, you can do this in a single
click!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Make sure Sheet1 is selected, paste in your code


and Select Save. Close the window afterwards.

How to Insert Multiple Rows 58 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

STEP 3: Let us test it out!

Select any cell that you want to insert rows on. Go to Developer >
Code > Macros

Make sure your Macro is selected. Click Run.

How to Insert Multiple Rows 59 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

We want to insert 3 rows. Type in 3.

With that, you are now able to insert multiple rows using Macros!

How to Insert Multiple Rows 60 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

How to Insert Numbers

What does it do?

Asks for a max number, then generates numbers from 1 to the max
number

Copy Source Code:


Sub InsertNumbers()

Dim maxNumber As Integer


Dim counter As Integer

On Error GoTo Last


maxNumber = InputBox("Enter the Max Value", "Generate 1
to n")
'Generate all the numbers
For counter = 1 To maxNumber
ActiveCell.Value = counter
'Move one cell below
ActiveCell.Offset(1, 0).Activate
Next counter
Last: Exit Sub
End Sub

How to Insert Numbers 61 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

How to Insert Numbers 62 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

I wanted to insert consecutive numbers in a cool way. And the way I


found was to insert numbers using Macros in Excel!

We get to learn to use a loop as well to do this!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Make sure Sheet1 is selected, paste in your code


and Select Save. Close the window afterwards.

How to Insert Numbers 63 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

STEP 3: Let us test it out!

Select any cell that you want to insert numbers on. Go to Developer
> Code > Macros

Make sure your Macro is selected. Click Run.

How to Insert Numbers 64 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

We want to insert 10 numbers. Type in 10.

With that, you are now able to insert consecutive numbers using
Macros!

How to Insert Numbers 65 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

How to Remove Text Wrap

What does it do?

Removes text wrap in all cells and then autofit all of the cells

Copy Source Code:


Sub RemoveWrapAndAutofitCells()
Activate
Cells.Select

'Remove the Text Wrap


Selection.WrapText = False

'Autofit all of the cells afterwards


Cells.EntireRow.AutoFit
Cells.EntireColumn.AutoFit
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

How to Remove Text Wrap 66 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Ever wanted to remove all the text wrapping, but the hassle of your
cells spilling over is stopping you? Have no fear, Macros are here to
save the day! You can remove text wrap using Macros in
Excel then autofit the cells as well!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

How to Remove Text Wrap 67 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

How to Remove Text Wrap 68 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells now have text wrap removed!

How to Remove Text Wrap 69 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Unmerge Cells

What does it do?

Unmerge the selection of cells

Copy Source Code:


Sub UnmergeAllCells()
'Unmerge all cells in one go!
Selection.UnMerge
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Unmerge Cells 70 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Excel provides us a way to unmerge all cells through its interface.


Did you know that you can do the same thing with Excel Macros? Let
us try out this exercise!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Make sure you have selected your merged cells for unmerging. Go
to Developer > Code > Macros

Unmerge Cells 71 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells are now unmerged!

Unmerge Cells 72 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Use Calculator

What does it do?

Launch the Calculator from Excel

Copy Source Code:


Sub UseCalculator()

'Open the Calculator for quick calculations


Application.ActivateMicrosoftApp Index:=0

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Use Calculator 73 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Inside Excel, there is that cool functionality of launching the


calculator from there, and you can do that with Excel Macros! You
can now perform some quick calculations using the calculator.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Use Calculator 74 BASIC MACROS


Go back to Basic Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you have launched the calculator inside Excel!

Use Calculator 75 BASIC MACROS


Go to Table of Contents

CHART MACROS
Add Chart Title........................................................................... 77
Change Chart Type..................................................................... 83
Convert Chart into Image ........................................................... 87
Resize All Charts ........................................................................ 91

76 CHART MACROS
Go back to Chart Macros Go to Table of Contents

Add Chart Title

What does it do?

Adds a title to the selected chart based on user input

Copy Source Code:


'Make sure you have selected your chart first
Sub AddChartTitle()

Dim titleText As Variant

On Error GoTo Last


'Get the Chart Title from the user
titleText = InputBox("Please enter the chart title",
"Chart Title Input")

'Now set the title on the selected chart


ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = titleText
Last: Exit Sub

End Sub

Add Chart Title 77 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add Chart Title 78 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Did you know that you can programmatically make changes to Excel
Charts? Yes you can! Let us try updating a chart by adding the chart
title using Excel Macros!

This is our starting chart:

STEP 1: Go to Developer > Code > Visual Basic

Add Chart Title 79 CHART MACROS


Go back to Chart Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the chart. Make sure your chart is
selected. Go to Developer > Code > Macros

Add Chart Title 80 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Type in the title you want for your chart. Click OK.

Add Chart Title 81 CHART MACROS


Go back to Chart Macros Go to Table of Contents

With just that, you have modified the chart title!

Add Chart Title 82 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Change Chart Type

What does it do?

Change the chart type to your specified type

Copy Source Code:


'Select your chart first before running this
Sub ChangeChartType()

'This is the clustered column chart, you can change the


type
'Other chart types are listed at:
https://docs.microsoft.com/en-
us/office/vba/api/Excel.XlChartType
ActiveChart.ChartType = xlColumnClustered

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Change Chart Type 83 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Macros encompass a lot of functionalities, and one of them is


changing the properties of Charts! Let us try to change the chart
type using Excel Macros!

This is our original bar chart. Let us change it to a Clustered


Column Chart:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save.

You can change the chart type in the code to the type you prefer.
The list of chart types are listed here.

Change Chart Type 84 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Close the window afterwards.

STEP 3: Let us test it out!

Open the sheet containing the chart. Make sure your chart is
selected. Go to Developer > Code > Macros

Change Chart Type 85 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your chart type is now changed!

Change Chart Type 86 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Convert Chart into Image

What does it do?

Converts your selected chart into an image

Copy Source Code:


'Make sure you have selected your chart first
Sub ConvertChartIntoImage()

ActiveChart.ChartArea.Copy
ActiveSheet.Range("A1").Select
'Converts the Chart into an Image
'Then it gets pasted on Cell A1 of the active sheet
ActiveSheet.Pictures.Paste.Select
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Chart into Image 87 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Wanted to save your chart as in image to use elsewhere? You can


use Excel Macros to convert your selected chart into an image!

This is our chart that we want to convert:

STEP 1: Go to Developer > Code > Visual Basic

Convert Chart into Image 88 CHART MACROS


Go back to Chart Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the chart. Make sure your chart is
selected. Go to Developer > Code > Macros

Convert Chart into Image 89 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your chart is now converted into an image!

Convert Chart into Image 90 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Resize All Charts

What does it do?

Resizes all charts to a specific height and width

Copy Source Code:


'Make sure to change the Width and Height values below
Sub ResizeAllCharts()

Dim counter As Integer

'Loop through all of the charts


For counter = 1 To ActiveSheet.ChartObjects.Count
'Change the Height and Width values based on your
requirements
With ActiveSheet.ChartObjects(counter)
.Height = 400
.Width = 400
End With
Next counter

End Sub

Resize All Charts 91 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Resize All Charts 92 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Have a lot of charts and want to keep them organized to a


consistent size? Excel Macros can resize all charts with a single
click!

These are our charts:

STEP 1: Go to Developer > Code > Visual Basic

Resize All Charts 93 CHART MACROS


Go back to Chart Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. You can change the
Height and Weight if you prefer a different size than 400. Close
the window afterwards.

STEP 3: Let us test it out!

Open the sheet containing the charts. Go to Developer > Code >
Macros

Resize All Charts 94 CHART MACROS


Go back to Chart Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your charts are now resized!

Resize All Charts 95 CHART MACROS


Go to Table of Contents

FORMULA MACROS
Add a Degree Symbol to Selection .............................................. 98
Add letters A-Z ......................................................................... 102
Calculate Square Root .............................................................. 106
Convert Date into Day .............................................................. 110
Convert Date into Month .......................................................... 115
Convert Date into Year ............................................................. 120
Convert Formulas into Values ................................................... 125
Convert Negative Numbers to Positive ...................................... 130
Convert Roman Numbers into Modern Numbers ....................... 135
Convert Selection to Lower Case ............................................... 140
Convert Selection to Proper Case .............................................. 144
Convert Selection to Sentence Case .......................................... 148
Convert Selection to Upper Case............................................... 153
Convert Time into Hour ............................................................ 157
Convert Time into Minutes ....................................................... 161
Convert Time into Seconds ....................................................... 165
Convert UK Dates to US Dates .................................................. 169
Convert US Dates to UK Dates .................................................. 173
Extract Number from Text ........................................................ 177
Format Values to Dollars and 2 Decimal Places ......................... 182
Get Word Count from Worksheet .............................................. 186
Increase Cell Values by a Number ............................................. 191
Decrease Cell Values by a Number............................................ 196
Insert Time Range .................................................................... 201

96 FORMULA MACROS
Go to Table of Contents

Multiply all Values by a Number ............................................... 206


Remove a Character from Selection .......................................... 212
Remove Apostrophe from Numbers .......................................... 216
Remove Characters at the Start................................................. 220
Remove Date from Date and Time ............................................ 226
Remove Time from Date and Time............................................ 230
Remove Decimals from Numbers .............................................. 234
Replace Blanks with Zeros ........................................................ 237
Trim Extra Spaces from Selection ............................................. 242

97 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Add a Degree Symbol to Selection

What does it do?

Adds a degree symbol to each number in your selection

Copy Source Code:


Sub AddDegreeSymbolToSelection()
Dim rng As Range
'Loop through the entire selection
For Each rng In Selection
'Set the active cell
rng.Select
'For each number, add the degree symbol at the end
If ActiveCell <> "" Then
If IsNumeric(ActiveCell.Value) Then
ActiveCell.Value = ActiveCell.Value & "°"
End If
End If
Next
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add a Degree Symbol to Selection 98 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Have numbers that are degrees but you are having difficulty
inserting the degree symbol to each? Excel Macros can modify your
numbers and you will add a degree symbol to your selection in a
single click!

You will learn here on how you can customize text and modify it
using Macros.

This is our list of numbers:

STEP 1: Go to Developer > Code > Visual Basic

Add a Degree Symbol to Selection 99 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Add a Degree Symbol to Selection 100 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all your numbers have the degree symbol
added to it!

Add a Degree Symbol to Selection 101 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Add letters A-Z

What does it do?

Adds the letters A to Z

Copy Source Code:


Sub AddLettersAtoZ()
Dim counter As Integer
'Let us use the ascii codes of the alphabet - A(65) to
Z(90)
For counter = 65 To 90
ActiveCell.Value= Chr(counter)
'Move to one cell down
ActiveCell.Offset(1, 0).Select
Next counter
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Add letters A-Z 102 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Excel Macros is very powerful and allows you to do a lot of fun


things. Let us try to use loops and add letters A-Z with just a single
click!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Add letters A-Z 103 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Add letters A-Z 104 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, all of the letters A-Z are added in a single
click!

Add letters A-Z 105 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Calculate Square Root

What does it do?

Calculate the square root of your selected numbers

Copy Source Code:


'Make sure you have a range of numbers selected
Sub CalculateSquareRoot()
Dim rng As Range
'Loop through all of the cells
For Each rng In Selection
'If it is a number, then get the square root
If WorksheetFunction.IsNumber(rng) Then
rng.Value= Sqr(rng)
Else
End If
Next rng
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Calculate Square Root 106 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Excel Macros are capable of doing a lot of things, and mathematical


calculations is one of them! Let us use Excel Macros to calculate the
square root of your selected numbers!

Here are the numbers that we want to get the square root of:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Calculate Square Root 107 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your numbers are
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Calculate Square Root 108 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, you have calculated the square root of all
your numbers!

Calculate Square Root 109 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Date into Day

What does it do?

Convert your selected date into day values

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertDateIntoDay()

Dim cell As Range


Selection.Value = Selection.Value

'Check each cell


For Each cell In Selection
'If it is a date, then extract the day from it
If IsDate(cell) = True Then
With cell
.Value = Day(cell)
.NumberFormat = "0"
End With
End If
Next cell

End Sub

Convert Date into Day 110 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Date into Day 111 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Macros are also capable of processing dates and times. Let us see
how we can convert date into day values using Excel Macros!

These are our dates to convert:

STEP 1: Go to Developer > Code > Visual Basic

Convert Date into Day 112 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Date into Day 113 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your dates are now converted to days!

Convert Date into Day 114 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Date into Month

What does it do?

Convert your selected date into month values

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertDateIntoMonth()

Dim cell As Range


Selection.Value = Selection.Value

'Check each cell


For Each cell In Selection
'If it is a date, then extract the month from it
If IsDate(cell) = True Then
With cell
.Value = Month(cell)
.NumberFormat = "0"
End With
End If
Next cell

End Sub

Convert Date into Month 115 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Date into Month 116 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Macros are also capable of processing dates and times. Let us see
how we can convert date into month values using Excel Macros!

These are our dates to convert:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Convert Date into Month 117 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Convert Date into Month 118 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, all of your dates are now converted to
months!

Convert Date into Month 119 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Date into Year

What does it do?

Convert your selected date into year values

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertDateIntoYear()

Dim cell As Range


Selection.Value = Selection.Value

'Check each cell


For Each cell In Selection
'If it is a date, then extract the year from it
If IsDate(cell) = True Then
With cell
.Value = Year(cell)
.NumberFormat = "0"
End With
End If
Next cell

End Sub

Convert Date into Year 120 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Date into Year 121 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Macros are also capable of processing dates and times. Let us see
how we can convert date into year values using Excel Macros!

These are our dates to convert:

STEP 1: Go to Developer > Code > Visual Basic

Convert Date into Year 122 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Date into Year 123 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your dates are now converted to years!

Convert Date into Year 124 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Formulas into Values

What does it do?

Converts formulas into values in your selection

Copy Source Code:


Sub ConvertFormulasIntoValues()

Dim rng As Range


Dim formulaCell As Range
Set rng = Selection

'Check each cell in the range if it has a formula


For Each formulaCell In rng
If formulaCell.HasFormula Then
formulaCell.Formula = formulaCell.Value
End If
Next formulaCell

End Sub

Convert Formulas into Values 125 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Formulas into Values 126 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Whenever we have a lot of cells with formulas, then want to change


them to permanent values, we need to use the Paste Special. What if
I told you, you can do this in a single click for all formula cells in
your selection?

That's right, Excel Macros can convert formulas into values in one
step!

Here is our list of formula cells:

To have a better look, you can see it uses the RANDBETWEEN


formula. Let us change these to values only!

Convert Formulas into Values 127 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your formula cells
are highlighted. Go to Developer > Code > Macros

Convert Formulas into Values 128 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the formula cells are now converted to
values! The values also changed because of the nature of the
RANDBETWEEN formula, as it changes along with any change done
to the workbook.

Convert Formulas into Values 129 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Negative Numbers to


Positive

What does it do?

Converts your selected numbers to positive

Copy Source Code:


'Make sure you have a selection of negative numbers
ready
Sub ConvertNegativeNumbersToPositive()

Dim rng As range

Selection.Value = Selection.Value

'Loop through the cells


For Each rng In Selection
'If it is a number, then convert it into a positive
value
If WorksheetFunction.IsNumber(rng) Then rng.Value =
Abs(rng)
Next rng

End Sub

Convert Negative Numbers to Positive 130 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Negative Numbers to Positive 131 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Have a range of numbers where you want to convert them to all


positive? We can use Excel Macros to convert negative numbers to
positive with one click!

These are our selection of negative numbers:

STEP 1: Go to Developer > Code > Visual Basic

Convert Negative Numbers to Positive 132 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your negative
numbers are highlighted. Go to Developer > Code > Macros

Convert Negative Numbers to Positive 133 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your numbers are now converted to
positive!

Convert Negative Numbers to Positive 134 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Roman Numbers into


Modern Numbers

What does it do?

Converts your selected Roman Numbers Into Arabic

Copy Source Code:


'Make sure you have a selection of roman numbers ready
Sub ConvertRomanNumbersIntoArabic()

Dim rng As Range

Selection.Value = Selection.Value

'Loop through all of the cells


For Each rng In Selection
If Not WorksheetFunction.IsNonText(rng) Then
'This is where the magic happens, it converts it to
arabic numbers
rng.Value= WorksheetFunction.Arabic(rng)
End If
Next rng

End Sub

Convert Roman Numbers into Modern Numbers


135 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Roman Numbers into Modern Numbers


136 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Ever seen Roman Numbers that you want to simply convert to


normal numbers? Excel Macros can do the hard work for you and
convert Roman Numbers into Arabic with one click!

These are the Roman Numbers that we want to convert to Arabic:

STEP 1: Go to Developer > Code > Visual Basic

Convert Roman Numbers into Modern Numbers


137 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your Roman
Numbers are highlighted. Go to Developer > Code > Macros

Convert Roman Numbers into Modern Numbers


138 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the Roman Numbers are now converted
correctly!

Convert Roman Numbers into Modern Numbers


139 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Convert Selection to Lower Case

What does it do?

Converts selected text to lower case

Copy Source Code:


'Make sure you have selected a range first
Sub ConvertSelectionToLowerCase()
Dim rng As Range
For Each rng In Selection
'Check if this is text first, then convert into lower
case
If Application.WorksheetFunction.IsText(rng) Then
rng.Value = LCase(rng)
End If
Next
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Selection to Lower Case 140 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

When it comes to cleaning up text, Excel Macros can make short


work of it. You can create Macros to convert selection to lower
case with one click!

This is our text. Let us do some clean up!

STEP 1: Go to Developer > Code > Visual Basic

Convert Selection to Lower Case 141 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Selection to Lower Case 142 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells now converted to lower case!

Convert Selection to Lower Case 143 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Selection to Proper Case

What does it do?

Converts selected text to proper case

Copy Source Code:


'Make sure you have selected a range first
Sub ConvertSelectionToProperCase()
Dim rng As Range
For Each rng In Selection
'Check if this is text first, then convert into proper
case
If Application.WorksheetFunction.IsText(rng) Then
rng.Value = Application.WorksheetFunction.Proper(rng)
End If
Next
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Selection to Proper Case 144 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

When it comes to cleaning up text, Excel Macros can make short


work of it. You can create Macros to convert selection to proper
case with one click!

This is our text. Let us do some clean up!

STEP 1: Go to Developer > Code > Visual Basic

Convert Selection to Proper Case 145 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Selection to Proper Case 146 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells now converted to proper case!

Convert Selection to Proper Case 147 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Selection to Sentence Case

What does it do?

Converts selected text to sentence case

Copy Source Code:


'Make sure you have selected a range first
'Assumption is each cell is a single sentence
Sub ConvertSelectionToSentenceCase()

Dim rng As Range

For Each rng In Selection


'Check if this is text first, then convert into
sentence case
'Make the first letter capitalized, then the rest of
the text as small letters
If Application.WorksheetFunction.IsText(rng) Then
rng.Value= UCase(Left(rng, 1)) & LCase(Right(rng,
Len(rng) -1))
End If
Next

End Sub

Convert Selection to Sentence Case 148 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Selection to Sentence Case 149 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

When it comes to cleaning up text, Excel Macros can make short


work of it. You can create Macros to convert selection to sentence
case with one click!

This is our text. Let us do some clean up!

STEP 1: Go to Developer > Code > Visual Basic

Convert Selection to Sentence Case 150 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Selection to Sentence Case 151 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells now converted to sentence
case!

Convert Selection to Sentence Case 152 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Selection to Upper Case

What does it do?

Converts selected text to upper case

Copy Source Code:


'Make sure you have selected a range first
Sub ConvertSelectionToUpperCase()
Dim rng As Range
For Each rng In Selection
'Check if this is text first, then convert into upper
case
If Application.WorksheetFunction.IsText(rng) Then
rng.Value = UCase(rng)
End If
Next
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Selection to Upper Case 153 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

When it comes to cleaning up text, Excel Macros can make short


work of it. You can create Macros to convert selection to upper
case with one click!

This is our text. Let us do some clean up!

STEP 1: Go to Developer > Code > Visual Basic

Convert Selection to Upper Case 154 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Selection to Upper Case 155 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells now converted to upper case!

Convert Selection to Upper Case 156 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Time into Hour

What does it do?

Convert your selected time into hour values

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertTimeIntoHour()
Dim cell As Range
Selection.Value = Selection.Value
'Check each cell
For Each cell In Selection
'Extract the hour from it
With cell
.Value = Hour(cell)
.NumberFormat = "0"
End With
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Time into Hour 157 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Macros are also capable of processing dates and times. Let us see
how we can convert time into hour values using Excel Macros!

These are our times to convert:

STEP 1: Go to Developer > Code > Visual Basic

Convert Time into Hour 158 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Time into Hour 159 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your times are now converted to hours!

Convert Time into Hour 160 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Time into Minutes

What does it do?

Convert your selected time into minute values

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertTimeIntoMinutes()
Dim cell As Range
Selection.Value = Selection.Value
'Check each cell
For Each cell In Selection
'Extract the minutes from it
With cell
.Value = Minute(cell)
.NumberFormat = "0"
End With
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Time into Minutes 161 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Macros are also capable of processing dates and times. Let us see
how we can convert time into minute values using Excel Macros!

These are our times to convert:

STEP 1: Go to Developer > Code > Visual Basic

Convert Time into Minutes 162 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Time into Minutes 163 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your times are now converted to
minutes!

Convert Time into Minutes 164 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert Time into Seconds

What does it do?

Convert your selected time into second values

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertTimeIntoSeconds()
Dim cell As Range
Selection.Value = Selection.Value
'Check each cell
For Each cell In Selection
'Extract the second from it
With cell
.Value = Second(cell)
.NumberFormat = "0"
End With
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Time into Seconds 165 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Macros are also capable of processing dates and times. Let us see
how we can convert time into second values using Excel Macros!

These are our times to convert:

STEP 1: Go to Developer > Code > Visual Basic

Convert Time into Seconds 166 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert Time into Seconds 167 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your times are now converted to
seconds!

Convert Time into Seconds 168 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert UK Dates to US Dates

What does it do?

Convert your selected dates from UK Date Format to US Date Format

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertUkDatesToUsDates()

Selection.NumberFormat = "MMM-DD-YY"

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert UK Dates to US Dates 169 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Do you recall having a scenario where your dates in Excel are using
the incorrect format? You can convert UK dates to US dates using
Macros in Excel!

With this tutorial we will be converting from UK format (e.g.


31/12/2020) to US format (e.g. 12/31/2020).

Here are our dates in UK Format:

STEP 1: Go to Developer > Code > Visual Basic

Convert UK Dates to US Dates 170 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert UK Dates to US Dates 171 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your dates are now in the US format!

Convert UK Dates to US Dates 172 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Convert US Dates to UK Dates

What does it do?

Convert your selected dates from US Date Format to UK Date Format

Copy Source Code:


'Make sure you have selected a range of cells first
Sub ConvertUsDatesToUkDates()

Selection.NumberFormat = "DD-MMM-YY"

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert US Dates to UK Dates 173 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Do you recall having a scenario where your dates in Excel are using
the incorrect format? You can convert US dates to UK dates using
Macros in Excel!

With this tutorial we will be converting from US format (e.g.


12/31/2020) to UK format (e.g. 31/12/2020).

Here are our dates in US Format:

STEP 1: Go to Developer > Code > Visual Basic

Convert US Dates to UK Dates 174 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Convert US Dates to UK Dates 175 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your dates are now in the UK format!

Convert US Dates to UK Dates 176 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Extract Number from Text

What does it do?

Creates a custom formula that extracts the numeric part from text

Copy Source Code:


'Create your own formula to retrieve the numeric
portion of your text
'Assumption is there is only one numeric portion in the
text

Function GetNumericPart(CellRef As String)

Dim LengthOfText As Integer

LengthOfText = Len(CellRef)

'loop through each character, then append the numeric


parts together
Result = ""
For ctr = 1 To LengthOfText
If IsNumeric(Mid(CellRef, ctr, 1)) _
Then Result = Result & Mid(CellRef, ctr, 1)
Next ctr

GetNumericPart = Result

End Function

Extract Number from Text 177 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Extract Number from Text 178 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Want to create your own formula definition? You can do that using
Excel Macros! Let us create a formula that extracts the number
from text. The assumption here is there is only one number in your
text to extract.

This is our text. Let us create our formula!

STEP 1: Go to Developer > Code > Visual Basic

Extract Number from Text 179 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Right click on Sheet1 and go to Insert > Module.

Paste in your code and Select Save. Close the window afterwards.

Extract Number from Text 180 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Type in your new custom
formula: =GetNumericPart(B8)

Do the same for the rest of the cells. And you have extracted the
numeric part using Macros!

Extract Number from Text 181 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Format Values to Dollars and 2


Decimal Places

What does it do?

Format your selected values to dollars with 2 decimal places

Copy Source Code:


'Make sure you have a selection of numbers ready
Sub FormatValuesToDollars()
Dim rng As range
Selection.Value = Selection.Value
'Loop through the cells
For Each rng In Selection
'If it is a number, then format it to a dollar value
with 2 decimal places
If WorksheetFunction.IsNumber(rng) Then
rng.NumberFormat = "$#,###.00"
Next rng
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Format Values to Dollars and 2 Decimal Places


182 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Have a bunch of values that you want to format as dollar values?


You can do that easily through Excel Macros! You will be able
format values to dollar with 2 decimal places.

These are our values:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Format Values to Dollars and 2 Decimal Places


183 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Format Values to Dollars and 2 Decimal Places


184 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

With just one click, all of your numbers are now formatted as
dollars with 2 decimal places!

Format Values to Dollars and 2 Decimal Places


185 FORMULA MACROS
Go back to Formula Macros Go to Table of Contents

Get Word Count from Worksheet

What does it do?

Displays the word count

Copy Source Code:


Sub GetWordCountFromWorksheet()

Dim totalCount As Long


Dim count As Long
Dim range As Range
Dim trimmedText As String

'Loop through all of the cells


For Each range In ActiveSheet.UsedRange.Cells
trimmedText =
Application.WorksheetFunction.Trim(range.Text)
count = 0

'Count the number of words


If trimmedText <> vbNullString Then
count = Len(trimmedText) - Len(Replace(trimmedText, "
", "")) + 1
End If

totalCount = totalCount + count


Next range

MsgBox "There are a total of " & Format(totalCount,


"#,##0") & " words in the your worksheet"

End Sub

Get Word Count from Worksheet 186 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Get Word Count from Worksheet 187 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Wanted to count the number of words inside your spreadsheet?


Excel Macros will get the word count for you!

This is our data table, let's check the number of words!

STEP 1: Go to Developer > Code > Visual Basic

Get Word Count from Worksheet 188 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Get Word Count from Worksheet 189 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you now have displayed your word count!

Get Word Count from Worksheet 190 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Increase Cell Values by a Number

What does it do?

Add all selected values by a number

Copy Source Code:


'Make sure you have a range of values selected
Sub AddAllValuesByANumber()

Dim rng As Range


Dim num As Integer

num = InputBox("Enter your number to add to all",


"Enter your number")

'Loop through all of the values


For Each rng In Selection
'For each number, add it with the user input
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng + num
Else
End If
Next rng

End Sub

Increase Cell Values by a Number 191 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Increase Cell Values by a Number 192 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Let us have some fun and try to perform mathematical operations


on a range of numbers. Let us try using Excel Macros to add all
values by a number!

These are our numbers:

STEP 1: Go to Developer > Code > Visual Basic

Increase Cell Values by a Number 193 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your values are
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Increase Cell Values by a Number 194 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Enter 5 to add all of them by 5. Click OK.

With just one click, all of the values are now added by 5!

Increase Cell Values by a Number 195 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Decrease Cell Values by a Number

What does it do?

Subtract all selected values by a number

Copy Source Code:


'Make sure you have a range of values selected
Sub SubtractAllValuesByANumber()

Dim rng As Range


Dim num As Integer

num = InputBox("Enter your number to subtract from


all", "Enter your number")

'Loop through all of the values


For Each rng In Selection
'For each number, subtract it from the user input
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng - num
Else
End If
Next rng

End Sub

Decrease Cell Values by a Number 196 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Decrease Cell Values by a Number 197 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Let us have some fun and try to perform mathematical operations


on a range of numbers. Let us try using Excel Macros to subtract all
values by a number!

These are our numbers:

STEP 1: Go to Developer > Code > Visual Basic

Decrease Cell Values by a Number 198 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your values are
highlighted. Go to Developer > Code > Macros

Decrease Cell Values by a Number 199 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Enter 5 to subtract all of them by 5. Click OK.

With just one click, all of the values are now subtracted by 5!

Decrease Cell Values by a Number 200 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Insert Time Range

What does it do?

Insert a time range by the hour from 1am to 12 midnight

Copy Source Code:


Sub InsertTimeRange()

Dim counter As Integer

'Insert the time range from 00:00 to 23:00


For counter = 1 To 24
ActiveCell.FormulaR1C1 = counter & ":00"
ActiveCell.NumberFormat = "[$-409]h:mm AM/PM;@"
'Move on to the next row
ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select
Next counter

End Sub

Insert Time Range 201 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Insert Time Range 202 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Want to create a quick schedule and insert hourly times to your


spreadsheet? You can use Excel Macros and looping to quickly
insert a time range from 1am all the way to 12 midnight!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Insert Time Range 203 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Insert Time Range 204 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, all hours are now generated!

Insert Time Range 205 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Multiply all Values by a Number

What does it do?

Multiply all selected values by a number

Copy Source Code:


'Make sure you have a range of values selected
Sub MultiplyAllValuesByANumber()

Dim rng As Range


Dim num As Integer

num = InputBox("Enter your multiplier", "Enter your


multiplier")

'Loop through all of the values


For Each rng In Selection
'For each number, multiply it with the user input
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng * num
Else
End If
Next rng

End Sub

Multiply all Values by a Number 206 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Multiply all Values by a Number 207 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Let us have some fun and try to perform mathematical operations


on a range of numbers. Let us try using Excel Macros to multiply all
values by a number!

These are our numbers:

STEP 1: Go to Developer > Code > Visual Basic

Multiply all Values by a Number 208 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your values are
highlighted. Go to Developer > Code > Macros

Multiply all Values by a Number 209 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Enter 5 as the multiplier to multiply all of them by 5. Click OK.

Multiply all Values by a Number 210 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, all of the values are now multiplied by 5!

Multiply all Values by a Number 211 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Remove a Character from Selection

What does it do?

Remove your specified character from the selection of text

Copy Source Code:


Sub RemoveCharacterFromSelection()

Dim range As Range


Dim characters As String
'Get the characters to be removed from the user
characters = InputBox("Input the characters to remove",
"Input Characters to be removed")
'Replace it with blank
For Each range In Selection
range.Replace What:=characters, Replacement:=""
Next

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove a Character from Selection 212 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Excel has a feature of Find and Replace if you want to remove a


character then replace it with a blank value. You can create your
own functionality using Excel Macros! Let us aim to remove a
character from a selection of text using Macros.

We have this list of ID Numbers, let us aim to remove the dashes ( - )


from them:

STEP 1: Go to Developer > Code > Visual Basic

Remove a Character from Selection 213 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your id numbers are
highlighted. Go to Developer > Code > Macros

Remove a Character from Selection 214 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Type in the dash ( - ) to have it removed. Click OK.

With just one click, you have removed all of the dashes!

Remove a Character from Selection 215 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Remove Apostrophe from Numbers

What does it do?

Removes apostrophe in front of numbers in your selection

Copy Source Code:


'If you have an apostrophe before your numbers, use
this to remove them
'Make sure you have selected a range of numbers
Sub RemoveApostropheFromNumbers()

Selection.Value = Selection.Value

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove Apostrophe from Numbers 216 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Sometimes we receive spreadsheets where the numbers have an


apostrophe in front of them so that it gets treated as text. But what
if we do not want that? Excel Macros will remove apostrophe from
numbers in a single click!

Here are our numbers with apostrophes in front of them:

STEP 1: Go to Developer > Code > Visual Basic

Remove Apostrophe from Numbers 217 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your numbers are
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Remove Apostrophe from Numbers 218 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, all of the apostrophes are now removed!

Remove Apostrophe from Numbers 219 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Remove Characters at the Start

What does it do?

Removes the number of characters at the start as specified by the


user

Copy Source Code:


Sub RemoveCharactersAtTheStart()

Dim range As Range


Dim num As Integer

'Get the characters to be removed from the user


num = InputBox("Input the number of characters to
remove at the start", "Num of characters")

'Loop through all of the text


For Each range In Selection
'Use Right to remove the first x characters
range = Right(range, Len(range) - num)
Next range

End Sub

Remove Characters at the Start 220 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove Characters at the Start 221 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Want to quickly truncate the first number of characters of your


choosing? Excel Macros can remove characters at the start of your
selection of text!

This is the text that we want to modify. We want to remove the first
2 characters of these Part Numbers:

STEP 1: Go to Developer > Code > Visual Basic

Remove Characters at the Start 222 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your part numbers
are highlighted. Go to Developer > Code > Macros

Remove Characters at the Start 223 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

We want to remove the first 2 characters. Type in 2 and Click OK.

Remove Characters at the Start 224 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

With just one click, the first 2 characters are now all removed!

Remove Characters at the Start 225 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Remove Date from Date and Time

What does it do?

Removes the date component from your date time

Copy Source Code:


'Make sure you have a range of cells selected
Sub RemoveDateFromDateTime()
Dim cell As Range
'Loop through all of the cells
For Each cell In Selection
If IsDate(cell) = True Then
cell.Value = cell.Value - VBA.Fix(cell.Value)
End If
Next
'Change it to a time format
Selection.NumberFormat = "hh:mm:ss am/pm"
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove Date from Date and Time 226 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Have a bunch of date times, and you want to keep the time only?
You can remove date from the date and time using Excel Macros
in a single click!

Here is our list of dates and times:

STEP 1: Go to Developer > Code > Visual Basic

Remove Date from Date and Time 227 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your date times are
highlighted. Go to Developer > Code > Macros

Remove Date from Date and Time 228 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the dates from the date times are now
removed!

Remove Date from Date and Time 229 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Remove Time from Date and Time

What does it do?

Removes the time component from your dates

Copy Source Code:


'Make sure you have a range of cells selected
Sub RemoveTimeFromDateTime()
Dim cell As Range
'Loop through all of the cells
For Each cell In Selection
If IsDate(cell) = True Then
cell.Value = VBA.Int(cell.Value)
End If
Next
'Change it to a date format
Selection.NumberFormat = "mmm-dd-yy"
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove Time from Date and Time 230 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Wanted to make your date times simpler by removing the time


component? Excel Macros make it possible to remove the time
from dates easily!

This is our list of dates with times:

STEP 1: Go to Developer > Code > Visual Basic

Remove Time from Date and Time 231 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your date times are
highlighted. Go to Developer > Code > Macros

Remove Time from Date and Time 232 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the times from the dates are now
removed!

Remove Time from Date and Time 233 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Remove Decimals from Numbers

What does it do?

Removes the decimal component from your selected numbers

Copy Source Code:


'Make sure you have a selection ready
Sub RemoveDecimalsFromNumbers()
Dim rng As Range
'Loop through the selection
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
'Convert it to an integer to remove the decimal portion
rng.Value= Int(rng)
rng.NumberFormat= "0"
Else
End If
Next rng
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove Decimals from Numbers 234 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Have a lot of numbers and you want to completely remove the


decimal portions? Excel Macros can remove decimals from
numbers in a single click!

Here are our numbers:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Remove Decimals from Numbers 235 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your numbers are
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

With just one click, all of the decimal components are now
removed!

Remove Decimals from Numbers 236 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Replace Blanks with Zeros

What does it do?

Replaces blanks with zeros in your selection

Copy Source Code:


'Make sure you have a selection ready
Sub ReplaceBlanksWithZeros()

Dim range As Range

Selection.Value= Selection.Value

'Loop through all the cells


For Each range In Selection
'If it is a blank or one space, then replace it with 0
If range = "" Or range = " " Then
range.Value= "0"
Else
End If
Next range

End Sub

Replace Blanks with Zeros 237 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Replace Blanks with Zeros 238 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

It is so common for me to have a column of numbers with blanks.


But it would be more readable for me to replace blanks with zeros
instead. Excel Macros can do this for us!

This is our list of values, see that the Sales column has blanks:

STEP 1: Go to Developer > Code > Visual Basic

Replace Blanks with Zeros 239 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your sales column is
highlighted. Go to Developer > Code > Macros

Replace Blanks with Zeros 240 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the blanks are now replaced with zeros!

Replace Blanks with Zeros 241 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Trim Extra Spaces from Selection

What does it do?

Removes spaces at the start and end from your selection

Copy Source Code:


Sub RemoveExtraSpacesFromSelection()
Dim range As Range
Dim cell As Range
Set range = Selection
'loop through each cell and trim them
For Each cell In range
If Not IsEmpty(cell) Then
cell = Trim(cell)
End If
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Trim Extra Spaces from Selection 242 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

If you want to quickly remove extra spaces at the start and end of
your text, Excel Macros will do that for you! It is very similar to the
TRIM formula as well.

These are our text that we want to clean up:

STEP 1: Go to Developer > Code > Visual Basic

Trim Extra Spaces from Selection 243 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your text is
highlighted. Go to Developer > Code > Macros

Trim Extra Spaces from Selection 244 FORMULA MACROS


Go back to Formula Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the unneeded extra spaces are all
removed!

Trim Extra Spaces from Selection 245 FORMULA MACROS


Go to Table of Contents

HIGHLIGHTING MACROS
Highlight Active Row & Column ................................................ 247
Highlight All Errors with a Red Color ........................................ 251
Highlight All Named Ranges ..................................................... 255
Highlight Alternate Rows in Selection ....................................... 259
Highlight and Count a Specified Value ...................................... 263
Highlight Cells with a Single Space ........................................... 269
Highlight Cells with Comments ................................................ 274
Highlight Custom Text ............................................................. 278
Highlight Duplicates ................................................................. 283
Highlight Unique Values in Selection ........................................ 288
Highlight Max Value in Selection .............................................. 291
Highlight Min Value in Selection ............................................... 296
Highlight Negative Values ........................................................ 300
Highlight Top 10 Values of Selection ........................................ 305
Highlight Bottom 10 Values of Selection ................................... 310
Highlight Values Greater Than .................................................. 315
Highlight Values Lesser Than ................................................... 321
Spell check and Highlight Misspellings ..................................... 327

246 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Active Row & Column

What does it do?

Highlights the Active Row and Column By the Double Click

Copy Source Code:


Private Sub Worksheet_BeforeDoubleClick(ByVal Target As
range, Cancel As Boolean)

Dim selection As String

'Generate the Range that contains the current column


and row
selection = Target.Cells.Address & "," & _
Target.Cells.EntireColumn.Address & "," & _
Target.Cells.EntireRow.Address

'Select that range


Range(selection).Select
End Sub

Highlight Active Row & Column 247 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Active Row & Column 248 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

We have a cool trick to show you using Macros, you can highlight
the active row and column by double clicking!

Do take note that this will override your original double click
behavior.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Highlight Active Row & Column 249 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 3: Let us test it out!

Just double click anywhere, and it will highlight the active row and
column!

Highlight Active Row & Column 250 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight All Errors with a Red Color

What does it do?

Highlight all of the errors

Copy Source Code:


Sub HighlightAllErrors()
Dim cell As Range
For Each cell In ActiveSheet.UsedRange
'Check if it is an error, then change the style to be
Bad
If WorksheetFunction.IsError(cell) Then
cell.Style = "Bad"
End If
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight All Errors with a Red Color 251 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Have a lot of errors in your worksheet but having a hard time


finding them? Excel Macros will make short work of this and we can
highlight all errors!

Here is our initial set of data, you can see there are a lot of errors in
there:

STEP 1: Go to Developer > Code > Visual Basic

Highlight All Errors with a Red Color 252 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Highlight All Errors with a Red Color 253 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells with errors are now
highlighted!

Highlight All Errors with a Red Color 254 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight All Named Ranges

What does it do?

Highlight all Named Ranges

Copy Source Code:


Sub HighlightAllNamedRanges()

Dim RangeName As Name


Dim SelectedRange As Range
On Error Resume Next
'Loop through all named ranges
For Each RangeName In ActiveWorkbook.Names
Set SelectedRange = RangeName.RefersToRange
'Highlight with the color yellow
SelectedRange.Interior.ColorIndex = 27
Next RangeName
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight All Named Ranges 255 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

If you have a lot of named ranges in your worksheet, and you want
to see which ones are there quickly? You can quickly highlight all
named ranges using Excel Macros!

For our example, these columns over here have named ranges
defined.

Here are the named ranges, you can quickly view them via Formulas
> Defined Names > Name Manager:

Highlight All Named Ranges 256 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Highlight All Named Ranges 257 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the named ranges are now highlighted!

Highlight All Named Ranges 258 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Alternate Rows in


Selection

What does it do?

Highlights alternate rows in your selection

Copy Source Code:


Sub HighlightAlternateRowsInSelection()
Dim range As Range
For Each range In Selection.Rows
'Check if it's the alternate row by using modulo, set
it to the style of note
If range.Row Mod 2 = 1 Then
range.Style = "Note"
Else
End If
Next range
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Alternate Rows in Selection 259 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

When it comes to highlighting alternate rows in your data, it's a


cumbersome process! One way is to use the table formatting option
in Excel, but you can also use Excel Macros to highlight alternate
rows for you!

And you have full control on how it will look like!

Here is our initial set of data:

STEP 1: Go to Developer > Code > Visual Basic

Highlight Alternate Rows in Selection 260 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Highlight Alternate Rows in Selection 261 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

With just one click, the alternate rows of your selection are now
highlighted!

Highlight Alternate Rows in Selection 262 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight and Count a Specified


Value

What does it do?

Highlight and show the count of a specified value

Copy Source Code:


Sub HighlightAndCountSpecifiedValue()

Dim cell As Range


Dim counter As Integer
Dim specificValue As Variant

'Get the specific value from the user


specificValue = InputBox("Enter Value To Highlight",
"Enter Value")

For Each cell In ActiveSheet.UsedRange

'If it matches the specified value, then change the


style to be Note
If cell = specificValue Then
cell.Style = "Note"
counter = counter + 1
End If
Next cell

'Show the total count to the user


MsgBox "There are a total of " & counter &" "&
specificValue & " in this worksheet."

End Sub

Highlight and Count a Specified Value 263 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight and Count a Specified Value 264 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Let us try something fun using Excel Macros. We want to highlight a


specified value from the user, then show the count as well! You
will learn how to show a message back as well to your Excel user.

This is our initial set of data:

STEP 1: Go to Developer > Code > Visual Basic

Highlight and Count a Specified Value 265 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Highlight and Count a Specified Value 266 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Type in the value to highlight and count. Let us type in Ian Wright.
Click OK.

Highlight and Count a Specified Value 267 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

With just one click, all of the Ian Wright values are now
highlighted and you see the count as well!

Highlight and Count a Specified Value 268 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Cells with a Single Space

What does it do?

Highlights all cells with a single space

Copy Source Code:


Sub HighlightTheSingleSpaces()

Dim range As Range

For Each range In ActiveSheet.UsedRange


'Check if it's a single space, then change the style to
be Note
If range.Value = " " Then
range.Style = "Note"
End If
Next range

End Sub

Highlight Cells with a Single Space 269 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Cells with a Single Space 270 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

If you had a spreadsheet with a lot of single spaces, it is very


annoying because it is hard to see. You can use Excel Macros to
highlight cells with a single space easily!

This is our initial set of data, the ones enclosed in red are the ones
with a single space (although it is not visible at an initial glance).

Double click in the empty cells and press CTRL + A which will
highlight the single space.

STEP 1: Go to Developer > Code > Visual Basic

Highlight Cells with a Single Space 271 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Highlight Cells with a Single Space 272 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells with a single space are now
highlighted!

Highlight Cells with a Single Space 273 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Cells with Comments

What does it do?

Highlights all cells with comments

Copy Source Code:


Sub HighlightCellsWithComments()
'Select the cells with comments
Selection.SpecialCells(xlCellTypeComments).Select
'Set all the cells' style to the Note style
Selection.Style= "Note"
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Cells with Comments 274 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Have a lot of comments in your spreadsheet and want to find all of


them? Excel Macros can highlight all cells with comments for you!

This is our initial set of data, you can see the ones with the red
triangle on the right corner are the ones with comments inserted:

STEP 1: Go to Developer > Code > Visual Basic

Highlight Cells with Comments 275 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Highlight Cells with Comments 276 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells with comments are now
highlighted!

Highlight Cells with Comments 277 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Custom Text

What does it do?

Highlights any text that you specify

Copy Source Code:


Sub HighlightCustomText()

'Get the Custom Text


Dim txt As String
txt = InputBox("Enter the Custom Text", "Enter Text")

Dim rng As Range

'Loop through all values in the selection


For Each rng In Selection

'If the value is the same as the custom text, then set
the font color to red
If rng.Value = txt Then
rng.Font.Color = RGB(255, 0, 0)
End If
Next

End Sub

Highlight Custom Text 278 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Custom Text 279 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Excel has search text functionality, however we can also use Excel
Macros to highlight custom text! That's right, you can use it to
highlight any text that you specify!

Here is our initial set of data:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Highlight Custom Text 280 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Highlight Custom Text 281 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

For the text, let's type in Ian Wright. Click OK.

With just one click, all Ian Wright values are now highlighted!

Highlight Custom Text 282 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Duplicates

What does it do?

Highlights all cells with duplicate values in a selected range

Copy Source Code:


Sub HighlightDuplicates()

Dim cells As Range


Dim cell As Range
Set cells = selection

'Loop through each cell in your selected range looking


for duplicates
For Each cell In cells

'Highlight with a color of your choice, if that cell


has duplicate values
If WorksheetFunction.CountIf(cells, cell.Value) > 1
Then
'Change the ColorIndex into a color you prefer
cell.Interior.ColorIndex = 36
End If
Next cell

End Sub

Highlight Duplicates 283 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Duplicates 284 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Want to learn how to highlight cells that are duplicates and learn
Macros at the same time? Let me show you how to highlight
duplicates using Macros in Excel!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Highlight Duplicates 285 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 3: Let us test it out! Make sure to have your cells selected.

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Highlight Duplicates 286 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

With just one click, all of the duplicate cells now have been
highlighted!

Highlight Duplicates 287 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Unique Values in Selection

What does it do?

Highlights distinct values in your selection

Copy Source Code:


Sub HighlightUniqueValuesInSelection()
'Set the range as the current selection
Dim range As Range
Set range = Selection
range.FormatConditions.Delete
'Color the unique values with green
Dim uniqueVals As UniqueValues
Set uniqueVals = range.FormatConditions.AddUniqueValues
uniqueVals.DupeUnique = xlUnique
uniqueVals.Interior.Color = RGB(0, 255, 0)
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Unique Values in Selection 288 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Want to find the values in your list that are unique? It is very easy to
do with Excel Macros, you can highlight unique values in your
selected range in a click!

Here is our initial set of data:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Highlight Unique Values in Selection 289 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

With just one click, all of the unique values are now highlighted!

Highlight Unique Values in Selection 290 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Max Value in Selection

What does it do?

Highlights the largest value in your selection

Copy Source Code:


Sub HighlightMaxValue()

Dim cell As Range


For Each cell In Selection

'If it matches the highest value, then change the style


to be Note
If cell = WorksheetFunction.Max(Selection) Then
cell.Style = "Note"
End If
Next cell

End Sub

Highlight Max Value in Selection 291 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Max Value in Selection 292 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Have a lot of values and want to find the largest value easily? Excel
Macro will do the heavy lifting for you by highlighting the max
value in your selection of values!

This is our initial set of data:

STEP 1: Go to Developer > Code > Visual Basic

Highlight Max Value in Selection 293 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Highlight Max Value in Selection 294 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your cell with the largest value is now
highlighted!

Highlight Max Value in Selection 295 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Min Value in Selection

What does it do?

Highlights the smallest value in your selection

Copy Source Code:


Sub HighlightMinValue()
Dim cell As Range
For Each cell In Selection
'If it matches the smallest value, then change the
style to be Note
If cell = WorksheetFunction.Min(Selection) Then
cell.Style = "Note"
End If
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Min Value in Selection 296 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Wanted to find the minimum value in a range of values? Excel


Macros can easily highlight the min value in your selection for
you!

These are our set of values, let us go find the smallest one!

STEP 1: Go to Developer > Code > Visual Basic

Highlight Min Value in Selection 297 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Highlight Min Value in Selection 298 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your cell with the smallest value is now
highlighted!

Highlight Min Value in Selection 299 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Negative Values

What does it do?

Highlights negative values in your selected range

Copy Source Code:


Sub HighlightNegativeValues()

Dim NumberToCheck As Range

'Loop through all numbers in the selection


For Each NumberToCheck In Selection
If WorksheetFunction.IsNumber(NumberToCheck) Then
'If it's lesser than 0, then set the font color to red
If NumberToCheck.Value < 0 Then
NumberToCheck.Font.Color= RGB(255, 0, 0)
End If
End If
Next

End Sub

Highlight Negative Values 300 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Negative Values 301 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Have a bunch of negative values that you want to highlight? You


can do that easily through Excel Macros!

These are our values:

STEP 1: Go to Developer > Code > Visual Basic

Highlight Negative Values 302 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Highlight Negative Values 303 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the negative values are now marked as
color red!

Highlight Negative Values 304 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Top 10 Values of


Selection

What does it do?

Highlights the top 10 values of your selection

Copy Source Code:


Sub HighlightTopTenValues()

Selection.FormatConditions.AddTop10
Selection.FormatConditions(Selection.FormatConditions.C
ount).SetFirstPriority
With Selection.FormatConditions(1)
.TopBottom = xlTop10Top
.Rank = 10
.Percent = False
End With

'Set the font color to red


With Selection.FormatConditions(1).Font
.ColorIndex = 3
.TintAndShade = 0
End With

'Set the highlight color to yellow


With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ColorIndex = 27
.TintAndShade = 0
End With

Selection.FormatConditions(1).StopIfTrue = False
End Sub

Highlight Top 10 Values of Selection 305 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Top 10 Values of Selection 306 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Want to learn how to highlight the top 10 values using Macros? We


have just the code for you! This one uses Format Conditions to the
fullest to achieve this highlighting for you.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Highlight Top 10 Values of Selection 307 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 3: Let us test it out! Select the data that you want its top 10
values to be highlighted.

Go to Developer > Code > Macros

Highlight Top 10 Values of Selection 308 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your top 10 values are now highlighted!

Highlight Top 10 Values of Selection 309 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Bottom 10 Values of


Selection

What does it do?

Highlights the bottom 10 values of your selection

Copy Source Code:


Sub HighlightBottomTenValues()

Selection.FormatConditions.AddTop10
Selection.FormatConditions(Selection.FormatConditions.C
ount).SetFirstPriority
With Selection.FormatConditions(1)
.TopBottom = xlTop10Bottom
.Rank = 10
.Percent = False
End With

'Set the font color to red


With Selection.FormatConditions(1).Font
.ColorIndex = 3
.TintAndShade = 0
End With

'Set the highlight color to yellow


With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ColorIndex = 27
.TintAndShade = 0
End With

Selection.FormatConditions(1).StopIfTrue = False
End Sub

Highlight Bottom 10 Values of Selection 310 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Bottom 10 Values of Selection 311 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Want to learn how to highlight the bottom 10 values using


Macros? We have just the code for you! This one uses Format
Conditions to the fullest to achieve this highlighting for you.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Highlight Bottom 10 Values of Selection 312 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 3: Let us test it out! Select the data that you want its bottom
10 values to be highlighted.

Go to Developer > Code > Macros

Highlight Bottom 10 Values of Selection 313 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your bottom 10 values are now highlighted!

Highlight Bottom 10 Values of Selection 314 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Values Greater Than

What does it do?

Highlights values greater than your specified value

Copy Source Code:


Sub HighlightValuesGreaterThan()

'Get the Greater Than Value


Dim value As Long
value = InputBox("Enter Greater Than Value", "Enter
Greater Than Value")

Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue,
Operator:=xlGreater, Formula1:=value
Selection.FormatConditions(Selection.FormatConditions.C
ount).SetFirstPriority

'Set the font to black and highlighting color as yellow


With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
.Interior.Color = RGB(255, 255, 0)
End With

End Sub

Highlight Values Greater Than 315 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Values Greater Than 316 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

You will be surprised on how much you can do with Macros. It can
highlight values in your selected range that are greater than a
value you specify.

These are our values:

STEP 1: Go to Developer > Code > Visual Basic

Highlight Values Greater Than 317 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Highlight Values Greater Than 318 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Enter the greater than value, we will enter 50000. Click OK.

Highlight Values Greater Than 319 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

With just one click, all of the values greater than 50,000 are now
highlighted!

Highlight Values Greater Than 320 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Highlight Values Lesser Than

What does it do?

Highlights values lesser than your specified value

Copy Source Code:


Sub HighlightValuesLesserThan()

'Get the Lesser Than Value


Dim value As Long
value = InputBox("Enter Lesser Than Value", "Enter
Lesser Than Value")

Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue,
Operator:=xlLess, Formula1:=value
Selection.FormatConditions(Selection.FormatConditions.C
ount).SetFirstPriority

'Set the font to black and highlighting color as yellow


With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
.Interior.Color = RGB(255,255, 0)
End With
End Sub

Highlight Values Lesser Than 321 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Highlight Values Lesser Than 322 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Want to try something new with Macros? You can highlight values
in your selected range that are lesser than a value you specify.

These are our values:

STEP 1: Go to Developer > Code > Visual Basic

Highlight Values Lesser Than 323 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Highlight Values Lesser Than 324 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Enter the lesser than value, we will enter 50000. Click OK.

Highlight Values Lesser Than 325 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

With just one click, all of the values lesser than 50,000 are now
highlighted!

Highlight Values Lesser Than 326 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Spell check and Highlight


Misspellings

What does it do?

Highlights the cells with incorrect spelling

Copy Source Code:


Sub HighlightMisspellings()
Dim cell As range
For Each cell In ActiveSheet.UsedRange
'Check the spelling and if it's wrong, then change the
style to be Bad
If Not Application.CheckSpelling(word:=cell.Text) Then
cell.Style = "Bad"
End If
Next cell
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Spell check and Highlight Misspellings 327 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Excel has spell checking functionality, and we can take this to the
next level by using Excel Macros to spell check then highlight
misspellings for you!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Spell check and Highlight Misspellings 328 HIGHLIGHTING MACROS


Go back to Highlighting Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the cells with incorrect spellings are
now highlighted!

Spell check and Highlight Misspellings 329 HIGHLIGHTING MACROS


Go to Table of Contents

PIVOT TABLE MACROS


Disable Enable Get Pivot Data ................................................... 331
Hide Pivot Table Subtotals ........................................................ 337
Refresh All Pivot Tables ............................................................ 342
Remove Autofit Columns on Refresh ........................................ 346

330 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Disable Enable Get Pivot Data

What does it do?

Disable / Enable Get Pivot Data

Copy Source Code:


Sub EnableGetPivotData()
Application.GenerateGetPivotData = True
End Sub

Sub DisableGetPivotData()
Application.GenerateGetPivotData = False
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Disable Enable Get Pivot Data 331 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

When you wanted to reference a cell in a Pivot Table, a


GETPIVOTDATA formula shows up instead. If you want to have just a
normal cell reference show up, you can disable/enable get pivot
data using Excel Macros!

Here is our pivot table:

Disable Enable Get Pivot Data 332 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

If we try to create a formula involving one of the cells inside the


Pivot Table, you will see the GETPIVOTDATA Formula. Let us
change this behavior using Macros!

STEP 1: Go to Developer > Code > Visual Basic

Disable Enable Get Pivot Data 333 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. This will create two
options for you to choose either to enable or disable. Close the
window afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Disable Enable Get Pivot Data 334 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Make sure your disable Macro is selected. Click Run.

Try referencing a cell inside the pivot table again. It is now a normal
cell reference.

Disable Enable Get Pivot Data 335 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

With just one click, we have disabled get pivot data!

Disable Enable Get Pivot Data 336 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Hide Pivot Table Subtotals

What does it do?

Hide the Pivot Table subtotals

Copy Source Code:


'Select a cell first from your pivot table
Sub HidePivotTableSubtotals()

Dim pTable As PivotTable


Dim pField As PivotField

On Error Resume Next

'Get the pivot table first


Set pTable =
ActiveSheet.PivotTables(ActiveCell.PivotTable.name)

'Check if a pivot table is found


If pTable Is Nothing Then
MsgBox "Please select a cell first from your Pivot
Table."
Exit Sub
End If

'For each subtotal, make it hidden


For Each pField In pTable.PivotFields
pField.Subtotals(1) = True
pField.Subtotals(1) = False
Next pField

End Sub

Hide Pivot Table Subtotals 337 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Hide Pivot Table Subtotals 338 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Excel Macros encompass a lot of functionality, and modifying Pivot


Tables is one of them! Let us hide pivot table subtotals using Excel
Macros!

This is our Pivot Table and we want to hide these subtotals:

STEP 1: Go to Developer > Code > Visual Basic

Hide Pivot Table Subtotals 339 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your pivot table is
selected. Go to Developer > Code > Macros

Hide Pivot Table Subtotals 340 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your Pivot Table subtotals are now hidden!

Hide Pivot Table Subtotals 341 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Refresh All Pivot Tables

What does it do?

Refresh all Pivot Tables

Copy Source Code:


Sub RefreshAllPivotTables()

Dim pCache As PivotCache

'With just one loop, refresh all pivot tables!


For Each pCache In ActiveWorkbook.PivotCaches
pCache.Refresh
Next pCache

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Refresh All Pivot Tables 342 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

It is so frequent that whenever I update my data, I forget to refresh


my Pivot Tables. We can now refresh all pivot tables using Excel
Macros!

This is our data:

These are the two pivot tables using this data source:

Now let's make change to have one big sales value! Let us see if the
pivot tables will reflect these values.

Refresh All Pivot Tables 343 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Refresh All Pivot Tables 344 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of your pivot tables are now refreshed!

Refresh All Pivot Tables 345 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Remove Autofit Columns on Refresh

What does it do?

Removes the Autofit Columns setting of all Pivot Tables whenever


you refresh the Pivot Tables

Copy Source Code:


Sub RemoveAutofitColumnsOnRefresh()

Dim pvtTable As PivotTable

For Each pvtTable In ActiveSheet.PivotTables


pvtTable.HasAutoFormat = False
Next pvtTable

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Remove Autofit Columns on Refresh 346 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

It is so frequent that whenever I update my data, I lose the


formatting of my Pivot Table column widths and they become
autofitted.

We can now remove the autofit columns setting of all pivot


tables using Excel Macros!

This is our data:

To demonstrate, let us try to refresh all pivot tables and see if the
columns get autofitted. Go to Data > Connections > Refresh All

Remove Autofit Columns on Refresh 347 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

You can see our columns got autofitted (Column E stands out).

Let us turn this off with Excel Macros! Now press the undo button
to undo the change we made.

STEP 1: Go to Developer > Code > Visual Basic

Remove Autofit Columns on Refresh 348 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Remove Autofit Columns on Refresh 349 PIVOT TABLE MACROS


Go back to Pivot Table Macros Go to Table of Contents

Now let us refresh all the pivot tables. Go to Data > Connections >
Refresh All

All of your pivot tables are now refreshed and have kept their
original column widths!

Remove Autofit Columns on Refresh 350 PIVOT TABLE MACROS


Go to Table of Contents

PRINTING MACROS
Print All Comments of a Worksheet .......................................... 352
Print the Selected Area ............................................................. 356
Print with a Narrow Margin ....................................................... 359

351 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Print All Comments of a Worksheet

What does it do?

Prints all comments of a specific worksheet to the last page

Copy Source Code:


Sub PrintCommentsToLastPage()
'Print all comments to the last page
With ActiveSheet.PageSetup
.printComments= xlPrintSheetEnd
End With
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Print All Comments of a Worksheet 352 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Want to quickly collate the comments in your spreadsheet? Excel


Macros will do the hard work for you, by printing all comments of
a worksheet to the last page!

We've added a couple of comments to these cells below. Let us see


how it will look like!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Print All Comments of a Worksheet 353 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Print All Comments of a Worksheet 354 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Go to File > Print

Scroll to the last page. You can now see the following information
for the comments: Cell location, comment and the author of the
comment!

Print All Comments of a Worksheet 355 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Print the Selected Area

What does it do?

Prints out the selected area

Copy Source Code:


Sub PrintTheSelectedArea()

'Print out a copy of your selected area


Selection.PrintOut Copies:=1

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Print the Selected Area 356 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Did you know that you could print out a specific area in your
spreadsheet? Yes that's right, you can use Excel Macro to just print
the selected area you have chosen! You get to save some printer ink
in the process as well!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Print the Selected Area 357 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

STEP 3: Let us test it out! Select the area that you only want to
print.

Open the sheet containing the data. Make sure your data is
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

With this, you have printed out the selected area only!

Print the Selected Area 358 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Print with a Narrow Margin

What does it do?

Prints out with narrow margins then shows the print dialog

Copy Source Code:


Sub PrintWithNarrowMargin()

'Set the Margins to be narrow and print it out


With ActiveSheet.PageSetup
.HeaderMargin= Application.InchesToPoints(0.3)
.FooterMargin= Application.InchesToPoints(0.3)
.LeftMargin= Application.InchesToPoints(0.25)
.RightMargin= Application.InchesToPoints(0.25)
.TopMargin= Application.InchesToPoints(0.75)
.BottomMargin= Application.InchesToPoints(0.75)
End With

Application.Dialogs(xlDialogPrint).Show

End Sub

Print with a Narrow Margin 359 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Print with a Narrow Margin 360 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

In Excel we can opt to print out with very narrow margins through
its interface. We can do the same thing with Excel Macros, you can
print with a narrow margin, or even customize the margin values
so that it will be constant every time!

This is our data table:

STEP 1: Go to Developer > Code > Visual Basic

Print with a Narrow Margin 361 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Print with a Narrow Margin 362 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

The Print Dialog is shown. Click OK once settings are good.

Print with a Narrow Margin 363 PRINTING MACROS


Go back to Printing Macros Go to Table of Contents

With just one click, you have now printed out with narrow
margins!

Print with a Narrow Margin 364 PRINTING MACROS


Go to Table of Contents

WORKBOOK MACROS
Attach Current Workbook into an Email Message ...................... 366
Close All Workbooks and Save Changes .................................... 371
Copy Current Worksheet into a New Workbook ......................... 375
Create a Backup ....................................................................... 379
Get the Count of Unsaved Workbooks ...................................... 383
Set the Active Worksheet .......................................................... 388
Show a Closing Message .......................................................... 391
Show a Welcome Message ........................................................ 394

365 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Attach Current Workbook into an


Email Message

What does it do?

Attach your current workbook into an Outlook email message

Copy Source Code:


Sub AttachWorkbookIntoEmailMessage()

Dim OutlookApp As Object


Dim OutlookMail As Object
Set OutlookApp = CreateObject("Outlook.Application")
Set OutlookMail = OutlookApp.CreateItem(0)

'Let us create the email message and display it


'Make sure to change the parameters below
With OutlookMail
.To = "[email protected]"
.Subject = "Have a look at this workbook"
.Body = "Hey John, Could you help out on this?"
.Attachments.Add ActiveWorkbook.FullName
.Display
End With

Set OutlookMail = Nothing


Set OutlookApp = Nothing

End Sub

Attach Current Workbook into an Email Message


366 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Attach Current Workbook into an Email Message


367 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

Want to quickly attach your Excel workbook into an email


message with a single click? You can do this with Excel Macros!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save.

You can change the following fields - To, Subject and Body
depending on your preferences. These are marked in yellow.

Close the window afterwards.

Attach Current Workbook into an Email Message


368 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Attach Current Workbook into an Email Message


369 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

With just one click, your Excel Workbook is now attached to the
email message!

Attach Current Workbook into an Email Message


370 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

Close All Workbooks and Save


Changes

What does it do?

Close all workbooks and save changes for all of them

Copy Source Code:


Sub CloseAllWorkbooksAndSaveChanges()
Dim workbook As Workbook
'Loop through all workbooks and close them
For Each workbook In Workbooks
workbook.Close SaveChanges:=True
Next workbook
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK 1- NO CODE

DOWNLOAD EXCEL WORKBOOK 1- WITH CODE

DOWNLOAD EXCEL WORKBOOK 2- NO CODE

DOWNLOAD EXCEL WORKBOOK 2 - WITH CODE

Close All Workbooks and Save Changes 371 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Is it a regular occurrence for you to have many Excel workbooks at


the same time due to multitasking? We can close all workbooks
and save changes for all of them using Excel Macros!

To demonstrate this, we have two workbooks currently open:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Make sure to select ThisWorkbook.

Paste in your code and Select Save. Close the window afterwards.

Close All Workbooks and Save Changes 372 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Close All Workbooks and Save Changes 373 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

With just one click, all of your workbooks are now saved and
closed!

Close All Workbooks and Save Changes 374 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Copy Current Worksheet into a New


Workbook
What does it do?

Copies your active worksheet into an entirely new workbook

Copy Source Code:


Sub CopyCurrentWorksheetToNewWorkbook()
'Copy the Current Worksheet
ThisWorkbook.ActiveSheet.Copy
Before:=Workbooks.Add.Worksheets(1)
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Copy Current Worksheet into a New Workbook


375 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

Have a worksheet that you want to copy into a new worksheet? You
can accomplish that with a single line of Excel Macro code! It will
copy the current worksheet into a new workbook.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Copy Current Worksheet into a New Workbook


376 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data, this is the one we want to copy
to a new worksheet.

Go to Developer > Code > Macros

Copy Current Worksheet into a New Workbook


377 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, your active worksheet was copied to a new
workbook!

Copy Current Worksheet into a New Workbook


378 WORKBOOK MACROS
Go back to Workbook Macros Go to Table of Contents

Create a Backup

What does it do?

Creates a backup copy of the spreadsheet in the specified folder

Copy Source Code:


Sub CreateBackup()

'Create a backup copy on the specified folder with the


date today included
'Remember to change the folder directory as well
ThisWorkbook.SaveCopyAs Filename:="C:\ChangeMe\" &
Format(Date, "mmddyyyy") & "-" & ThisWorkbook.name

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Create a Backup 379 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Have an important spreadsheet that requires frequent backups and


snapshots? You can create a backup using Excel Macros with a
single click!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save.

Make sure to change the directory into a folder that exists for you:

You can see we have changed this to C:\Data\

Close the window afterwards.

Create a Backup 380 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out! You can see that we have no files yet in
the directory:

Go to Developer > Code > Macros

Create a Backup 381 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you have generated a backup of your current
workbook!

Create a Backup 382 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Get the Count of Unsaved


Workbooks

What does it do?

Gets the count of unsaved workbooks

Copy Source Code:


Sub GetCountOfUnsavedWorkbooks()

Dim workbook As Workbook


Dim counter As Integer

For Each workbook In Workbooks


'Count the unsaved workbooks
If workbook.Saved = False Then
counter = counter + 1
End If
Next workbook

MsgBox "You have " & counter & " unsaved workbook(s)"

End Sub

Get the Count of Unsaved Workbooks 383 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK 1 - NO CODE

DOWNLOAD EXCEL WORKBOOK 1 - WITH CODE

DOWNLOAD EXCEL WORKBOOK 2 - NO CODE

DOWNLOAD EXCEL WORKBOOK 2 - WITH CODE

Get the Count of Unsaved Workbooks 384 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Have many workbooks open and need a quick survey of unsaved


files? Excel Macros will get the count of unsaved workbooks for
you!

We have 2 workbooks open that have unsaved changes:

Get the Count of Unsaved Workbooks 385 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

STEP 1: In any one of the workbooks, go to Developer > Code >


Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Get the Count of Unsaved Workbooks 386 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you now have the number of unsaved
workbooks!

Get the Count of Unsaved Workbooks 387 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Set the Active Worksheet

What does it do?

Activates the worksheet designated in your Excel Macro when you


open the Excel file.

Copy Source Code:


'Ensure this is saved inside the Workbook
Sub Workbook_Open()
'This activates when you open the workbook.
'Change the sheet name to your desired sheet.
Sheets("Europe").Activate
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Set the Active Worksheet 388 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Want to try something cool when your users open your workbook?
Set a default worksheet to open using Excel Macros!

This is our list of worksheets, we want it to default to Europe when


we open the workbook.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Make sure it is saved
in ThisWorkbook.

You can change the Sheet Name in the code (e.g. "Europe") if you
want a different default worksheet.

Close the window afterwards.

Set the Active Worksheet 389 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out! Close your workbook. Then open it up.

Your Macro will execute once you open the workbook. Now you can
see your new default worksheet!

Set the Active Worksheet 390 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Show a Closing Message

What does it do?

Shows a closing message once the Excel Workbook is closed

Copy Source Code:


'Ensure this is saved inside the Workbook
Sub Workbook_BeforeClose(Cancel As Boolean)

MsgBox "Thanks for downloading this and view more


tutorials at MyExcelOnline.com"

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Show a Closing Message 391 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

We have a cool trick to try out using Excel Macros, we can show a
closing message to thank your user once they close the
spreadsheet.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Make sure it is saved
in ThisWorkbook.

You can change the text to show in the closing message as well.

Close the window afterwards.

Show a Closing Message 392 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out! Close your workbook.

Your Macro will execute once you close the workbook. Now you can
see your closing message!

Show a Closing Message 393 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Show a Welcome Message

What does it do?

Shows a welcome message whenever you open the workbook

Copy Source Code:


'Ensure this is saved inside the Workbook
Sub Workbook_Open()

MsgBox "Thanks for downloading this and view more


tutorials at MyExcelOnline.com"

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Show a Welcome Message 394 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

Want to try something cool when your users open your workbook?
Show a welcome message using Excel Macros!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Make sure it is saved
in ThisWorkbook.

You can change the text to show in the welcome message as well.

Close the window afterwards.

Show a Welcome Message 395 WORKBOOK MACROS


Go back to Workbook Macros Go to Table of Contents

STEP 3: Let us test it out! Close your workbook. Then open it up:

Your Macro will execute once you open the workbook. Now you can
see your welcome message!

Show a Welcome Message 396 WORKBOOK MACROS


Go to Table of Contents

WORKSHEET MACROS
Delete All Other Worksheets ..................................................... 398
Delete Blank Worksheets .......................................................... 401
Hide All Other Worksheets........................................................ 405
Insert Multiple Worksheets ....................................................... 409
Protect Active Worksheet .......................................................... 414
Unprotect Active Worksheet ..................................................... 418
Protect All Cells With Formulas ................................................. 422
Protect All Worksheets ............................................................. 426
Save Each Worksheet as a PDF File ............................................ 432
Sort All Worksheets Alphabetically ............................................ 436
Unhide All Hidden Rows and Columns ...................................... 439
Unhide All Worksheets ............................................................. 443

397 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Delete All Other Worksheets

What does it do?

Deletes all other worksheets except the active worksheet

Copy Source Code:


Sub DeleteAllOtherWorksheets()

Dim worksheet As Worksheet


'Loop through the worksheets
For Each worksheet In ThisWorkbook.Worksheets
'Delete the sheet if it's not the active sheet
If worksheet.name <> ThisWorkbook.ActiveSheet.name Then
Application.DisplayAlerts = False
worksheet.Delete
Application.DisplayAlerts = True
End If

Next worksheet
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Delete All Other Worksheets 398 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Wanted to delete all other worksheets in a single click? You can do


that using Macros in Excel!

These are the worksheets in the file:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Delete All Other Worksheets 399 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 3: Let us test it out!

Select the worksheet that you do not want to be deleted. Go


to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

With just one click, all of the other worksheets are now deleted!

Delete All Other Worksheets 400 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Delete Blank Worksheets

What does it do?

Deletes all worksheets that are blank

Copy Source Code:


Sub DeleteBlankWorksheets()
Dim wsheet As Worksheet
On Error Resume Next
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'Loop through all worksheets and delete the blank ones
For Each wsheet In Application.Worksheets
If
Application.WorksheetFunction.CountA(wsheet.UsedRange)
= 0 Then
wsheet.Delete
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Delete Blank Worksheets 401 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Want to do some cleanup and delete the empty worksheets in your


workbook? Excel Macros will make this happen in a click and delete
blank worksheets!

These are our worksheets, the ones enclosed in red are blank
worksheets:

STEP 1: Go to Developer > Code > Visual Basic

Delete Blank Worksheets 402 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Delete Blank Worksheets 403 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the blank worksheets are now deleted!

Delete Blank Worksheets 404 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Hide All Other Worksheets

What does it do?

Hide all other worksheets except the active worksheet

Copy Source Code:


Sub HideAllOtherWorksheets()

Dim worksheet As Worksheet

'Loop through the worksheets


For Each worksheet In ThisWorkbook.Worksheets
'Hide the sheet if it's not the active sheet
If worksheet.Name <> ThisWorkbook.ActiveSheet.Name Then
worksheet.Visible = xlSheetHidden
End If
Next worksheet

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Hide All Other Worksheets 405 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Want to hide all worksheets except your active one? You can hide all
other worksheets using Macros in Excel!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Hide All Other Worksheets 406 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 3: Let us test it out! These are all of our worksheets that we
want to hide.

Open the sheet containing the data. Go to Developer > Code >
Macros

Hide All Other Worksheets 407 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the other worksheets are all hidden!

Hide All Other Worksheets 408 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Insert Multiple Worksheets

What does it do?

Insert multiple worksheets based on the user input of the number of


sheets

Copy Source Code:


Sub InsertMultipleWorksheets()

Dim numOfSheets As Integer

'Get the number of sheets from the user


numOfSheets = InputBox("Enter number of sheets to
insert", "Enter number of sheets")
'Add the additional sheets after the current active
sheet
Sheets.Add After:=ActiveSheet, Count:=numOfSheets

End Sub

Insert Multiple Worksheets 409 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Insert Multiple Worksheets 410 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Have multiple blank worksheets to insert? You can insert multiple


worksheets using Excel Macros!

We only have one worksheet so far, let us work out our magic!

STEP 1: Go to Developer > Code > Visual Basic

Insert Multiple Worksheets 411 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Insert Multiple Worksheets 412 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Let us try out adding 5 worksheets. Click OK.

With just one click, you have inserted multiple worksheets!

Insert Multiple Worksheets 413 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Protect Active Worksheet


What does it do?

Protects the active worksheet with the password specified by the


user

Copy Source Code:


Sub ProtectActiveWorksheet()
Dim pword As String
'Get the password from the user
pword = InputBox("Enter a Password to Protect the
Worksheet")
'Protect the Active Worksheet
ActiveSheet.Protect pword, True, True
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Protect Active Worksheet 414 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Wanted to protect your active worksheet programmatically? We will


show you how to protect the active worksheet using Macros in
Excel!

Here are our worksheets:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Protect Active Worksheet 415 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 3: Let us test it out!

Select your sheet to protect. For our example let us select


the Americas worksheet.

Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Protect Active Worksheet 416 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Type in the password to protect the worksheet. Click OK.

Try editing your worksheet. You can verify that the worksheet is
now protected!

Protect Active Worksheet 417 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Unprotect Active Worksheet

What does it do?

Unprotect the active worksheet

Copy Source Code:


Sub UnprotectActiveWorksheet()

Dim pword As String

'Get the password from the user


pword = InputBox("Enter a Password to Unprotect the
Worksheet")

'Unprotect the Active Worksheet


ActiveSheet.Unprotect pword
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Unprotect Active Worksheet 418 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Ever wondered how to unprotect the active worksheet using code?


Let us show you how to unprotect the active worksheet with Excel
Macros!

This is our worksheet, same as from the previous example


worksheet of the Protect Active Worksheet tutorial.

It is locked at the moment, with the same password: MyExcelOnline.

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Unprotect Active Worksheet 419 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the protected sheet. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

Unprotect Active Worksheet 420 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Type in the password to unlock the sheet. Click OK.

Now your sheet is now unprotected! We can now try editing the
sheet.

421 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Protect All Cells With Formulas

What does it do?

Locks all of the cells with formulas

Copy Source Code:


Sub ProtectAllCellsWithFormulas()
'Lock all of the cells with formulas in one go
With ActiveSheet
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect AllowDeletingRows:=True
End With
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Protect All Cells With Formulas 422 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

We usually have a lot of cells with formulas in our worksheets.


Wanted to protect these separately? You can protect all cells with
formulas using Excel Macros!

These are our cells with formulas:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Protect All Cells With Formulas 423 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Protect All Cells With Formulas 424 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

With just one click, all of the cells with formulas are now
protected!

Protect All Cells With Formulas 425 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Protect All Worksheets

What does it do?

Protects all worksheets with the user-given password

Copy Source Code:


Sub ProtectAllWorksheets()

Dim worksheet As Worksheet


Dim pword As String

'Get the password from the user


pword = InputBox("Enter a Password to Protect All
Worksheets", "Password")

'Loop through the worksheets and protect all of them


For Each worksheet In ActiveWorkbook.Worksheets
worksheet.Protect Password:=pword
Next worksheet

End Sub

Protect All Worksheets 426 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Protect All Worksheets 427 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

You can protect all worksheets using Macros in Excel! You will ask
the user for the password then use it to protect all of the
worksheets in the file.

This is our list of worksheets:

STEP 1: Go to Developer > Code > Visual Basic

Protect All Worksheets 428 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Go to Developer > Code > Macros

Protect All Worksheets 429 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Type in a password and click OK.

Protect All Worksheets 430 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

With just one click, all of your worksheets are now protected!

Protect All Worksheets 431 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Save Each Worksheet as a PDF File

What does it do?

Save each worksheet as a PDF file

Copy Source Code:


Sub SaveEachWorksheetAsPdfFile()

Dim worksheet As Worksheet

'Loop through all of the worksheets


'Remember to change the folder directory as well
For Each worksheet In Worksheets
worksheet.ExportAsFixedFormat xlTypePDF, "C:\ChangeMe\"
& worksheet.Name & ".pdf"
Next worksheet

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Save Each Worksheet as a PDF File 432 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Want to export and save each worksheet as a PDF file? You can
do that with a single click using Excel Macros!

We want to export these worksheets into pdf files:

STEP 1: Go to Developer > Code > Visual Basic

Save Each Worksheet as a PDF File 433 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save.

Remember to change the directory on where you want to save the


pdf files. Close the window afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Save Each Worksheet as a PDF File 434 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Let us check the folder, and you will see these worksheets:

Let us open one of the files, and it is exactly the same as the one in
the workbook!

Save Each Worksheet as a PDF File 435 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Sort All Worksheets Alphabetically

What does it do?

Sort all worksheets by name alphabetically

Copy Source Code:


Sub SortAllWorksheetsByName()

Dim i As Integer
Dim j As Integer
'We use two loops to sort the sheets in ascending order
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name)
Then
Sheets(j).Move After:=Sheets(j + 1)
End If
Next j
Next i
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Sort All Worksheets Alphabetically 436 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Have a lot of worksheets but the worksheet names are arranged in a


random order? It will be a pain moving the sheets one by one to sort
them out! You can sort all worksheets by name using Macros in
Excel!

This is our worksheet ordering:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Sort All Worksheets Alphabetically 437 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

With just one click, all of the worksheets are now sorted
alphabetically!

Sort All Worksheets Alphabetically 438 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Unhide All Hidden Rows and


Columns

What does it do?

Shows all hidden rows and columns

Copy Source Code:


Sub UnhideAllHiddenRowsAndColumns()
'Unhide all hidden rows and columns
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Unhide All Hidden Rows and Columns 439 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

We usually hide either rows or columns if we use them as helper


cells to calculate something. If we lose track of which ones we have
hidden, we can quickly unhide all hidden rows and columns using
Excel Macros!

This is our original table:

Now let us hide 2 rows and 1 column:

STEP 1: Go to Developer > Code > Visual Basic

Unhide All Hidden Rows and Columns 440 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Unhide All Hidden Rows and Columns 441 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, all of the hidden rows and columns are now
shown!

Unhide All Hidden Rows and Columns 442 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Unhide All Worksheets


What does it do?

Unhide all worksheets

Copy Source Code:


Sub UnhideAllWorksheets()
Dim worksheet As Worksheet
'Loop through all worksheets and set them to visible
For Each worksheet In ActiveWorkbook.Worksheets
worksheet.Visible = xlSheetVisible
Next worksheet
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Unhide All Worksheets 443 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Want to unhide all worksheets with just a single click? You


can unhide all worksheets using Macros in Excel!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out! This is the only tab we are seeing at the
moment.

Unhide All Worksheets 444 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

Open the sheet containing the data. Go to Developer > Code >
Macros

Make sure your Macro is selected. Click Run.

Unhide All Worksheets 445 WORKSHEET MACROS


Go back to Worksheet Macros Go to Table of Contents

With just one click, all of the hidden worksheets are now shown!

Unhide All Worksheets 446 WORKSHEET MACROS


Go to Table of Contents

ADVANCED MACROS
Convert Selected Range into an Image ...................................... 448
Convert Text into Speech ......................................................... 451
Create Table of Contents .......................................................... 454
Excel to Powerpoint .................................................................. 460
Insert a Linked Image ............................................................... 466
Insert a Row After Each Row ..................................................... 470
Save Selected Range as PDF ...................................................... 475
Use Goal Seek .......................................................................... 479
Use the Data Entry Form ........................................................... 484

447 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Convert Selected Range into an


Image

What does it do?

Converts your selected range into an image

Copy Source Code:


'Make sure you have a selected range first
Sub ConvertSelectedRangeIntoAnImage()

Selection.Copy
'Paste the selection as an image
ActiveSheet.Pictures.Paste.Select

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Selected Range into an Image 448 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Did you know that even Excel Macros you can create screenshots
with it? That's right, let us use Excel Macros to convert your
selected range into an image!

This is our target, we want to convert this header into an image!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Convert Selected Range into an Image 449 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the header. Make sure the header is
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

With just one click, you have now created a screenshot using
Macros! You can even rotate it or resize it now.

Convert Selected Range into an Image 450 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Convert Text into Speech

What does it do?

Reads your selection out aloud

Copy Source Code:


'Make sure you have a selection of text
Sub ConvertTextIntoSpeech()
'Hear your words spoken out load!
Selection.Speak
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Convert Text into Speech 451 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Did you know that Excel can actually talk? That's right, we can use
Excel Macros to convert text into speech. We can instruct Excel to
read text aloud to us!

These are our sentences that we want to hear read aloud:

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Convert Text into Speech 452 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your sentences are
highlighted. Go to Developer > Code > Macros

Make sure your Macro is selected. Click Run.

With just one click, you can hear your text being read aloud! Make
sure your sounds are turned on

Convert Text into Speech 453 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Create Table of Contents

What does it do?

Creates a table of contents for all of the worksheets

Copy Source Code:


Sub CreateTableOfContents()

Dim counter As Long

On Error Resume Next


Application.DisplayAlerts = False
'If this worksheet already exists, let us redo this
Worksheets("Table of Contents").Delete
Application.DisplayAlerts = True
On Error GoTo 0

'Let us add a new worksheet as our Table of Contents


ThisWorkbook.Sheets.Add
Before:=ThisWorkbook.Worksheets(1)
ActiveSheet.Name = "Table of Contents"

'Let us enumerate all of the worksheets in our ToC


For counter = 1 To Sheets.Count
'This will add one hyperlink for the specific sheet
ActiveSheet.Hyperlinks.Add _
Anchor:=ActiveSheet.Cells(counter, 1), _
Address:="", _
SubAddress:="'" & Sheets(counter).Name & "'!A1", _
ScreenTip:=Sheets(counter).Name, _
TextToDisplay:=Sheets(counter).Name

Next counter

End Sub

Create Table of Contents 454 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Create Table of Contents 455 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

This is one of the most fun and coolest Macros that you can use. If
you have a lot of worksheets, it is very annoying to scroll left to
right to find out what other worksheets you have. We can use Excel
Macros to create a table of contents for easy navigation!

This is our list of worksheets:

STEP 1: Go to Developer > Code > Visual Basic

Create Table of Contents 456 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet. Go to Developer > Code > Macros

Create Table of Contents 457 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, a new worksheet "Table of Contents" was


created!

Create Table of Contents 458 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Try clicking the Americas link and it takes you straight to the
Americas worksheet!

Create Table of Contents 459 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Excel to Powerpoint

What does it do?

Copies your selected range into a new Powerpoint file

Copy Source Code:


'Prerequisites:
'You need to add a reference to Powerpoint Library with
these steps:
'1. Go to Tools > References
'2. Look for Microsoft PowerPoint 16.0 Object
Library, and check it.
'3. Click OK
'Make sure to have a selected range before running this
Sub CopyToPowerPoint()

Dim pptApp As PowerPoint.Application


Dim pres As PowerPoint.Presentation
Dim sld As PowerPoint.Slide
Dim rng As Range

'Copy Range from Excel


Set rng = Selection
rng.Copy

'Get the Powerpoint Application


On Error Resume Next
Set pptApp = GetObject(,
"PowerPoint.Application")
On Error GoTo 0

'If it does not exist yet, then open Powerpoint


If pptApp Is Nothing Then
Set pptApp = New PowerPoint.Application
End If

Excel to Powerpoint 460 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

'Create your new presentation and setup the initial


slide, 11 = ppLayoutTitleOnly
Set pres = pptApp.Presentations.Add
Set sld = pres.Slides.Add(1, 11)

'Now let us paste inside the slide, 2 =


ppPasteEnhancedMetafile
sld.Shapes.PasteSpecial DataType:=2

pptApp.Visible = True
pptApp.Activate
Application.CutCopyMode = False

Set pptApp = Nothing


Set pres = Nothing
Set sld = Nothing

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Excel to Powerpoint 461 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Did you know that you can use Excel Macros to copy anything from
your spreadsheet into a Powerpoint presentation? Yes you can!

This is what we want to copy into a new Powerpoint file:

STEP 1: Go to Developer > Code > Visual Basic

Go to Tools > References

Excel to Powerpoint 462 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Look for Microsoft PowerPoint 16.0 Object Library and tick it.
Click OK.

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Excel to Powerpoint 463 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 3: Let us test it out!

Let us pick a specific section from our spreadsheet:

Go to Developer > Code > Macros

Excel to Powerpoint 464 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you now have your selected range copied into
Powerpoint!

Excel to Powerpoint 465 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Insert a Linked Image

What does it do?

Creates a linked image based on your selection

Copy Source Code:


'Make sure you have a selected range first
Sub InsertALinkedImage()

Selection.Copy
'Paste the selection as an image
ActiveSheet.Pictures.Paste(Link:=True).Select

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Insert a Linked Image 466 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Did you know that you can create a linked image in Excel?

Let us use Excel Macros to create our own linked image!

Let us try creating a linked image based on the MyExcelOnline logo.

(You can do this on any part of the spreadsheet, not just logos!

STEP 1: Go to Developer > Code > Visual Basic

Insert a Linked Image 467 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing our target. Make sure the logo cells are
highlighted. Go to Developer > Code > Macros

Insert a Linked Image 468 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you have created a linked image! Double click
on it and it will highlight the logo!

Insert a Linked Image 469 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Insert a Row After Each Row

What does it do?

Inserts a row after every row in your selection

Copy Source Code:


'Make sure you have a selection ready before running
this
Sub InsertRowsAlternately()

Dim rowCnt As Integer


Dim counter As Integer

rowCnt= Selection.EntireRow.Count

For counter = 1 To rowCnt


'Insert a blank row
ActiveCell.EntireRow.Insert
'Jump to the next row
ActiveCell.Offset(2, 0).Select
Next counter

End Sub

Insert a Row After Each Row 470 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Insert a Row After Each Row 471 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Wanted to insert alternate blank rows in your table? It's a pain to do


that manually, so let us insert a row after every row using Excel
Macros!

This is our table of data:

STEP 1: Go to Developer > Code > Visual Basic

Insert a Row After Each Row 472 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure your table is
highlighted. Go to Developer > Code > Macros

Insert a Row After Each Row 473 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you have now inserted blank rows after each
row!

Insert a Row After Each Row 474 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Save Selected Range as PDF

What does it do?

Save selected range as a PDF file

Copy Source Code:


'Make sure you have something selected
Sub SaveSelectedRangeAsPdf

'The generated PDF will be opened as well


Selection.ExportAsFixedFormat Type:=xlTypePDF,
OpenAfterPublish:=True

End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Save Selected Range as PDF 475 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Excel Macros are incredibly flexible and you will be surprised with
its bag of tricks! One of them is you can save any selected range
as PDF. That's right, any section in the spreadsheet that you have
selected gets saved into a PDF!

STEP 1: Go to Developer > Code > Visual Basic

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Save Selected Range as PDF 476 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 3: Let us test it out!

Let us pick a specific section from our data table:

Go to Developer > Code > Macros

Save Selected Range as PDF 477 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you now have your selected range saved into
a PDF!

Save Selected Range as PDF 478 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Use Goal Seek

What does it do?

Executes Goal Seek in Excel

Copy Source Code:


'Make sure the worksheet is selected to execute the
Goal Seek on
Sub GoalSeekVBA()

Dim TargetGoal As Long


'Get the target value from the user
TargetGoal = InputBox("Enter the target value", "Enter
Goal")

'Make sure to change the cell that you want to be


changed with the goal
ActiveSheet.Range("E9").GoalSeek _
Goal:=TargetGoal, _
ChangingCell:=Range("A9")
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Use Goal Seek 479 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Ever heard of the Goal Seek feature in Excel? It is a very nice feature
where it takes out the guesswork for you and determines the input
value needed to achieve a specific goal. For example, you have a
goal / result in mind, but you are unsure what the starting amount
should be for an investment. Let us use Excel Macros to execute the
Goal Seek feature!

This is our scenario. We have a formula calculating our target goal:

• The initial amount is $5000


• Interest rate is 4%
• Number of years is 10
• Monthly additional investment is $1000
• With these parameters, after 10 years, your investment will be
equivalent to $154,703.97

Let us now assume that, given we want to achieve a goal of


$250,000. What will our initial amount be?

Take note of the following:

• Initial Amount - Cell A9


• Total Amount (Goal) - Cell E9

STEP 1: Go to Developer > Code > Visual Basic

Use Goal Seek 480 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

Do take note that we are referencing these two cells in the code:

• Initial Amount - Cell A9


• Total Amount (Goal) - Cell E9

What goal seek will do, is it will adjust the initial amount (Cell A9),
to achieve the target goal that you specify (Cell E9) which is
$250,000.

STEP 3: Let us test it out!

Open the sheet containing the data. Go to Developer > Code >
Macros

Use Goal Seek 481 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

Type in the target value of $250,000. See how the initial amount will
change.

Use Goal Seek 482 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

With just one click, Goal Seek computed that you need an initial
amount of $68,921.35 to achieve your goal of $250,000!

Use Goal Seek 483 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Use the Data Entry Form

What does it do?

Loads the data form to allow you to populate data to the table

Copy Source Code:


Sub UseDataEntryForm()
'Show the default data entry form
ActiveSheet.ShowDataForm
End Sub

Final Result:

Exercise Workbook:

DOWNLOAD EXCEL WORKBOOK - NO CODE

DOWNLOAD EXCEL WORKBOOK - WITH CODE

Use the Data Entry Form 484 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Have a lot of details to encode in your table? You can use Excel
Macros to open the data entry form for you with one click!

This is our table that we want to populate data on:

STEP 1: Go to Developer > Code > Visual Basic

Use the Data Entry Form 485 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

STEP 2: Paste in your code and Select Save. Close the window
afterwards.

STEP 3: Let us test it out!

Open the sheet containing the data. Make sure the correct sheet is
selected. Go to Developer > Code > Macros

Use the Data Entry Form 486 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Make sure your Macro is selected. Click Run.

With just one click, you now have the data form loaded up! Let us
try populating a couple of records then click Close.

Use the Data Entry Form 487 ADVANCED MACROS


Go back to Advanced Macros Go to Table of Contents

Here is now how the updated table looks like!

Use the Data Entry Form 488 ADVANCED MACROS


489

You might also like