All about excel macros

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 More…Less

If you have tasks in Microsoft Excel that you do repeatedly, you can record a macro to automate those tasks. A macro is an action or a set of actions that you can run as many times as you want. When you create a macro, you are recording your mouse clicks and keystrokes. After you create a macro, you can edit it to make minor changes to the way it works.

Suppose that every month, you create a report for your accounting manager. You want to format the names of the customers with overdue accounts in red, and also apply bold formatting. You can create and then run a macro that quickly applies these formatting changes to the cells you select.

How?

Icon image

Before you record a macro    

Macros and VBA tools can be found on the Developer tab, which is hidden by default, so the first step is to enable it. For more information, see Show the Developer tab.

Developer tab on the ribbon

Icon image

Record a macro    

  1. In the Code group on the Developer tab, click Record Macro.

  2. Optionally, enter a name for the macro in the Macro name box, enter a shortcut key in the Shortcut key box, and a description in the Description box, and then click OK to start recording.

    Record Macro

  3. Perform the actions you want to automate, such as entering boilerplate text or filling down a column of data.

  4. On the Developer tab, click Stop Recording.

    Stop Recording

Icon image

Take a closer look at the macro    

You can learn a little about the Visual Basic programming language by editing a macro.

To edit a macro, in the Code group on the Developer tab, click Macros, select the name of the macro, and click Edit. This starts the Visual Basic Editor.

See how the actions that you recorded appear as code. Some of the code will probably be clear to you, and some of it may be a little mysterious.

Experiment with the code, close the Visual Basic Editor, and run your macro again. This time, see if anything different happens!

Next steps

  • To learn more about creating macros, see Create or delete a macro.

  • To learn about how to run a macro, see Run a macro.

How?

Icon image

Before you record a macro    

Make sure the Developer tab is visible on the ribbon. By default, the Developer tab is not visible, so do the following:

  1. Go to Excel > Preferences… > Ribbon & Toolbar.

  2. In the Customize the Ribbon category, in the Main Tabs list, select the Developer check box, and then click Save.

Icon image

Record a macro    

  1. On the Developer tab, click Record Macro.

  2. Optionally, enter a name for the macro in the Macro name box, enter a shortcut key in the Shortcut key box, and a description in the Description box, and then click OK to start recording.

  3. Perform the actions you want to automate, such as entering boilerplate text or filling down a column of data.

  4. On the Developer tab, in the Code group, click Stop Recording.

Icon image

Take a closer look at the macro    

You can learn a little about the Visual Basic programming language by editing a macro.

To edit a macro, in the Developer tab, click Macros, select the name of the macro, and click Edit. This starts the Visual Basic Editor.

See how the actions that you recorded appear as code. Some of the code will probably be clear to you, and some of it may be a little mysterious.

Experiment with the code, close the Visual Basic Editor, and run your macro again. This time, see if anything different happens!

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

What is MACRO in Excel?

A macro in excel is a series of instructions in the form of code that helps automate manual tasks, thereby saving time. Excel executes those instructions in a step-by-step manner on the given data.  For example, it can be used to automate repetitive tasks such as summation, cell formatting, information copying, etc. thereby rapidly replacing repetitious operations with a few clicks.

There are two methods to create the macros – The first is when you can record the macro, where Excel records every step automatically and then repeats it. The second is coding with VBAVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more, which requires good subject knowledge

Before recording a macro, the user has to activate the Developer tab in Excel. The Developer tabEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more is a built-in option in Excel to create macros, generate VBA applications, design forms, import or export XML files, etc. Since it is disabled in Excel by default, it has to be enabled before creating and recording the macrosRecording macros is a method whereby excel stores the tasks performed by the user. Every time a macro is run, these exact actions are performed automatically. Macros are created in either the View tab (under the “macros” drop-down) or the Developer tab of Excel.
read more
.

Table of contents
  • What is MACRO in Excel?
    • Enable the Developer tab
    • Examples of Macros in Excel
    • Example #1
    • Example #2
    • Adding the Macro Button
    • How to View the Code of Macros?
    • Creating Macro by Writing VBA Code
    • How to Save the Recorded Macro in Excel?
    • How to Enable “Macro Security Settings”?
    • Frequently Asked Questions (FAQs)
    • Recommended Articles

Let us learn the method to enable the Developer tab in Excel.

Enable the Developer tab

Below are the steps to activate the Developer tab in the Excel toolbar.

  1. Click on “options” in the File menu (as shown in the succeeding image).

    Activate developer Tab step 1

  2. On clicking the “options”, the “Excel options” window will pop up.

    Activate developer Tab step 2

  3. Select “customize ribbon” in the “Excel options” which provides a list of options in a dialog box.
    Under “customize the ribbon”, select “main tabs”. Among the list of checkboxes, select “developer” and click “ok”.

    Activate developer Tab step 3

  4. The worksheet displays the Developer tab, as highlighted in the succeeding image.

    Activate developer Tab step 4

  5. The user can view options like “visual basic”, “macros”, “record macro”, etc. on the ribbon of Developer tab (as displayed in the image below).

    Activate developer Tab step 5

Examples of Macros in Excel

Let us understand how to add macros in excel with the help of the following example.

Example #1

A list of data with different names is available in the table below. Some names have “.” symbol. We want to replace the “.” symbol with “_” by using macros in Excel.

You can download this Macro Excel Template here – Macro Excel Template

Macro Example 1

The steps to add an excel macro are listed as follows:

  • Click the “record macro” option in the Developer tab.

Macro Example 1-1

  • The “record macro” window will pop out. Name the macro “ReplaceDotin the “macro name” box. To assign a keyboard shortcutAn Excel shortcut is a technique of performing a manual task in a quicker way.read more, type “Ctrl+q” in the “shortcut key” box.

Select the option “This Workbook” in the “store macro in” box, which will ensure the macro is stored in the particular workbook.

It is optional to fill the “description” box explaining the task. Finally, click the “ok” button.

Macro Example 1-2

  • The “ReplaceDot” macro will start recording the user actions in Excel. The user will observe the “stop recording” button appearing in the Developer tab.

Macro Example 1-3

  • Let us now start replacing the “.(dot)” in the names with “_(underscore)” by using the “find and replace” option. Enter “.” in the “find” and “ _” in the “replace” option, respectively. Then click the “replace all” button.

Note: Use the shortcut key “Ctrl+H” to use “find and replace” option.

Shortcut key to Find

Macro Example 1-4

  • The “replace all” option replaces all the “.” (dots) with the “_” (underscores). The number of replacements and the resulting output is shown in the succeeding image.

Macro Example 1-5

  • The final output is displayed in the below image.

Macro Example 1-6

  • In the end, click the “stop recording” button on the Developer tab to stop the macro recording.

Example #2

We want to run the same task for a new list of names (displayed in the below image). We will run the macro “ReplaceDot,” created in the Developer ribbon.

Macro Example 1-7

  • Select the “enable macro” option from the Developer ribbon to view the list of macros created in the Macro window. The users can choose and run the macros based on their requirement.

The succeeding image shows the result of macros running on the new list of names.

Macro Example 1-8

Adding the Macro Button

Let us assign a button to the macro instead of choosing the “enableTo enable macros simply means to run or execute a macro in a particular file in order to save the time spent on repetitive actions. To enable macros, select “enable all macros” from the “trust center” of the File tab (in the “options” button).
read more
macroTo enable macros simply means to run or execute a macro in a particular file in order to save the time spent on repetitive actions. To enable macros, select “enable all macros” from the “trust center” of the File tab (in the “options” button).
read more
” option.

There are many groups like Add-ins, Controls, and XML under the Developer ribbon.

Macro Example 1-9

  • The user can choose the type of button to be created. Select the first button from “form controls” in the Controls tab.

Macro Example 1-10

  • Drag the selected button anywhere in the Excel sheet. The “assign macro” dialogue box opens. The macros to be assigned are listed in the “macro name” box.
  • Select the macro “ReplaceDot,” appearing in the list and click “ok”. 

Macro Example 1-11

  • A button appears in the worksheet. Right click the button and use “edit text” option to change the button text as “Button 3.” It is created on the right-hand side of the sheet, as shown in the below image.

Macro Example 1-12

  • Select the new name list to implement the same task by running macros, as indicated in the previous section.

Macro Example 1-13

  • Click the “Button 3” to run the assigned macro “ReplaceDot”.

Macro Example 1-14

  • To change the button name, use the “edit text” option to replace the text “Button 3” with “ReplaceDot”.

Macro Example 1-15

Using the above steps, we can create, record, and assign the macro for various tasks and automate it.

How to View the Code of Macros?

The users can view the code for a recorded macro. Excel generates the code based on the steps carried out while recording the macro.

We can access the code using the shortcut “Alt+F11” or by editing the macro that was created earlier.

Let us view the code for the “ReplaceDot” macro using the following steps:

  • Open the worksheet that contains the “ReplaceDot” macro. In the View tab, click the option “macros”. Select the “ReplaceDot” macro from the list and click the “edit” button.

Macro Example 1-16

  • The “Microsoft Visual Basic for Applications” will be launched.  The user can write or edit the code using this application. The below image shows the code of the “ReplaceDot” macro.

Macro Example 1-17

Creating Macro by Writing VBA Code

Before writing the VBA code, let us understand the “head” and “tail” of macros, which are the “sub” and “end sub.”

Macro Example 2-1

The user places the lines of VBA codes in the keyword “sub”. It executes the instructions in the code. The “end sub” keyword stops the execution of the “sub.”

Generally, there are two types of macros.

  1. “System Defined Function” –  It performs actions like creating a link of all the worksheet names, deleting all worksheets and so on.
  2. “User-Defined Function” – To create a User Defined Function User Defined Function in VBA is a group of customized commands created to give out a certain result. It is a flexibility given to a user to design functions similar to those already provided in Excel.read more(UDF) in macro, the user uses the “function and end function” as the “head” and “tail” of the codes.

Note: A function returns a value, whereas the sub does not.

A macro is written on the Visual Basic EditorThe Visual Basic for Applications Editor is a scripting interface. These scripts are primarily responsible for the creation and execution of macros in Microsoft software.read more (VBE) of the “Microsoft Visual Basic for Applications”.

Let us learn the steps to write a simple macro in the VBA.

  • Click the “module 1” in the “module” properties displayed on the left-hand side panel of the VBE window, and start writing the macro.

Macro Example 2

  • Begin with “sub” followed by the macro name and end with “end sub”. The code is written between the “sub” and “end sub.”

The below image shows the “sub” and “end sub” for the macro named “simplemacro ( )”.

Macro Example 2-1

  • Write code to display text in the message box. The “MsgBoxVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more” displays an input text message. All text in VBAText is a worksheet function in excel but it can also be used in VBA while using the range property. It is similar to the worksheet function and it takes the same number of arguments. These arguments are the values which needs to be converted.read more should be enclosed in double quotes.

For example,  the code:  MsgBox “Good Morning” (shown in the below image) displays the message “Good Morning” in the text box.

Macro Example 2-2

  • The output is displayed in the succeeding image.

Macro Example 2-3

Hence, the same macro can be assigned buttons to automate the task.

How to Save the Recorded Macro in Excel?

After recording, the user saves the macro to reuse in any other worksheet in the future.

Let us follow the below-mentioned steps to save the macro:

  • In the macro-enabled workbook,  click “save as.”
  • Select the “Excel macro-enabled workbook” option in the “save as type” box while saving the file.
  • Finally, save the macros with the “.xlsm” file extension.

Save Macro

The guidelines for saving the macro names are stated as follows:

  • Make sure that the name of recorded macros should start with letters (alphabets) or underscore.
  • Use letters, numeric, and underscore characters.
  • Avoid space, symbols, or punctuation marks.
  • Maintain a maximum length of about 80 characters.

Note: When the user saves a macro’s name with space, Excel issues a warning (as shown in the succeeding image).

Macro Warning

How to Enable “Macro Security Settings”?

In this section, let us learn to enable the “Macros security settings”.

When a user opens a workbook containing macros, a security warning – “Macros have been disabled” is displayed under the ribbon.  Choose the “enable content” option in the box.

Macro Security Warning

To eliminate the security warning, we need to change the “trust center settings” by using the following steps:

  • Under the “trust center settings” in the File options, click “macro settings”.
  • Choose the button, “Disable all macros with notification.”
  • The security is enabled in the “Macro Security” of the Developer ribbon.

Macro Security

Note 1: The user can create absolute macros (functioning from cell A1) that help to reuse the macro in other worksheets.

Note 2: The usage of directional keys (rather than a mouse) for navigation in macros is reliable to add, delete, and change the data in the worksheet.

Frequently Asked Questions (FAQs)

1. What are macros in Excel?

Macros are a set of simple programs or instructions to automate the common and repetitive tasks performed in the Excel worksheet. It can be recorded, saved, and run multiple times as per the user’s requirement.

It is a time-saving tool involved in preparing data reports and manipulating data carried out frequently in a worksheet.

2. How to enable macros in Excel?

The users can eliminate the security warning in the worksheet and enable macros by using the following steps:
• Click “options” in the File tab.
• Select “trust center” in the “options” window.
• Choose the option “trust center settings”.
• Click “macro settings” on the left side of the navigation pane.
• Select “enable all macros” and click “ok”.

3. What is the difference between macro and VBA?

The difference between macro and VBA is stated as follows.
• Macros are programming codes that function in the Excel worksheet to perform automated and repetitive tasks. It saves the user’s time and extends the efficiency of Excel.
• Visual Basic for Applications (VBA) is a programming language of Excel used for creating macros.

Recommended Articles

This has been a tutorial to Macros in Excel. Here we discuss how to add Macros in Excel along with , along with practical examples and a downloadable template. You may also look at these useful functions in Excel –

  • Excel Open XMLXML (Extensible Markup Language) is a text-based mark-up language that stores & organizes data in a human & machine-readable format. As it follows a specific script, you need to fulfill a particular set of prerequisites for importing the data into Excel or opening Excel Data into this format. read more
  • VBA MacrosVBA Macros are the lines of code that instruct the excel to do specific tasks, i.e., once the code is written in Visual Basic Editor (VBE), the user can quickly execute the same task at any time in the workbook. It thus eliminates the repetitive, monotonous tasks and automates the process.read more
  • MsgBox in Excel VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more


Download Article


Download Article

This wikiHow teaches you how to enable, create, run, and save macros in Microsoft Excel. Macros are miniature programs which allow you to perform complex tasks, such as calculating formulas or creating charts, within Excel. Macros can save significant amounts of time when applied to repetitive tasks, and thanks to Excel’s «Record Macro» feature, you don’t have to know anything about programming in order to create a macro.

Things You Should Know

  • Macros make it easy to automatic tasks in Microsoft Excel.
  • To create macros yourself, you’ll need to enable macros in the Developer menu of Excel.
  • Saving a macro-enabled spreadsheet is a little different than saving a spreadsheet without macros.
  1. Image titled Use Macros in Excel Step 1

    1

    Open Excel. Double-click the Excel app icon, which resembles a white «X» on a green box, then click Blank workbook.

    • If you have a specific file which you want to open in Excel, double-click that file to open it instead.
  2. Image titled Use Macros in Excel Step 2

    2

    Click File. It’s in the upper-left side of the Excel window.

    • On a Mac, click Excel in the upper-left corner of the screen to prompt a drop-down menu.

    Advertisement

  3. Image titled Use Macros in Excel Step 3

    3

    Click Options. You’ll find this on the left side of the Excel window.

    • On a Mac, you’ll click Preferences… in the drop-down menu.
  4. Image titled Use Macros in Excel Step 4

    4

    Click Customize Ribbon. It’s on the left side of the Excel Options window.[1]

    • On a Mac, click instead Ribbon & Toolbar in the Preferences window.
  5. Image titled Use Macros in Excel Step 5

    5

    Check the «Developer» box. This box is near the bottom of the «Main Tabs» list of options.

  6. Image titled Use Macros in Excel Step 6

    6

    Click OK. It’s at the bottom of the window. You can now use macros in Excel.

    • On a Mac, you’ll click Save here instead.
  7. Advertisement

  1. Image titled Use Macros in Excel Step 7

    1

    Enter any necessary data. If you opened a blank workbook, enter any data which you want to use before proceeding.

    • You can also close Excel and open a specific Excel file by double-clicking it.
  2. Image titled Use Macros in Excel Step 8

    2

    Click the Developer tab. It’s at the top of the Excel window. Doing so opens a toolbar here.

  3. Image titled Use Macros in Excel Step 9

    3

    Click Record Macro. It’s in the toolbar. A pop-up window will appear.

  4. Image titled Use Macros in Excel Step 10

    4

    Enter a name for the macro. In the «Macro name» text box, type in the name for your macro. This will help you identify the macro later.

  5. Image titled Use Macros in Excel Step 11

    5

    Create a shortcut key combination if you like. Press the Shift key along with another letter key (e.g., the E key) to create the keyboard shortcut. You can use this keyboard shortcut to run the macro later.

    • On a Mac, the shortcut key combination will end up being Option+ Command and your key (e.g., Option+ Command+T).
  6. Image titled Use Macros in Excel Step 12

    6

    Click the «Store macro in» drop-down box. It’s in the middle of the window. Doing so prompts a drop-down menu.

  7. Image titled Use Macros in Excel Step 13

    7

    Click This Workbook. This option is in the drop-down menu. Your macro will be stored inside your spreadsheet, making it possible for anyone who has the spreadsheet to access the macro.

  8. Image titled Use Macros in Excel Step 14

    8

    Click OK. It’s at the bottom of the window. Doing this saves your macro settings and begins recording.

  9. Image titled Use Macros in Excel Step 15

    9

    Perform the macro’s steps. Any step you perform between clicking OK and clicking Stop Recording while be added to the macro. For example, if you wanted to create a macro which turns two columns’ worth of data into a chart, you would do the following:

    • Click and drag your mouse across the data to select it.
    • Click Insert
    • Select a chart shape.
    • Click the chart that you want to use.
  10. Image titled Use Macros in Excel Step 16

    10

    Click Stop Recording. It’s in the Developer toolbar. This will save your macro.

  11. Advertisement

  1. 1

    Understand why you have to save the spreadsheet with macros enabled. If you don’t save your spreadsheet as a macro-enabled spreadsheet (XLSM format), the macro won’t be saved as part of the spreadsheet, meaning that other people on different computers won’t be able to use your macro if you send the workbook to them.

  2. Image titled Use Macros in Excel Step 18

    2

    Click File. It’s in the upper-left corner of the Excel window (Windows) or the screen (Mac). Doing so will prompt a drop-down menu.

  3. Image titled Use Macros in Excel Step 19

    3

    Click Save As. This option is on the left side of the window (Windows) or in the drop-down menu (Mac).

  4. Image titled Use Macros in Excel Step 20

    4

    Double-click This PC. It’s in the column of save locations near the left side of the window. A «Save As» window will open.

    • Skip this step on a Mac.
  5. Image titled Use Macros in Excel Step 21

    5

    Enter a name for your Excel file. In the «Name» text box, type in the name for your Excel spreadsheet.

  6. Image titled Use Macros in Excel Step 22

    6

    Change the file format to XLSM. Click the «Save as type» drop-down box, then click Excel Macro-Enabled Workbook in the resulting drop-down menu.[2]

    • On a Mac, you’ll replace the «xlsx» at the end of the file’s name with xlsm.
  7. Image titled Use Macros in Excel Step 23

    7

    Select a save location. Click a folder in which you want to save the Excel file (e.g., Desktop).

    • On a Mac, you must first click the «Where» drop-down box.
  8. Image titled Use Macros in Excel Step 24

    8

    Click Save. It’s at the bottom of the window. Doing so will save your Excel spreadsheet to your selected location, and your macro will be saved along with it.

  9. Advertisement

  1. Image titled Use Macros in Excel Step 25

    1

    Open the macro-enabled spreadsheet. Double-click the spreadsheet that has the macro in it to open the spreadsheet in Excel.

  2. Image titled Use Macros in Excel Step 26

    2

    Click Enable Content. It’s in a yellow bar at the top of the Excel window. This will unlock the spreadsheet and allow you to use the macro.

    • If you don’t see this option, skip this step.
  3. Image titled Use Macros in Excel Step 27

    3

    Click the Developer tab. This option is at the top of the Excel window.

    • You can also just press the key combination you set for the macro. If you do so, the macro will run, and you can skip the rest of this method.
  4. Image titled Use Macros in Excel Step 28

    4

    Click Macros. You’ll find it in the Developer tab’s toolbar. A pop-up window will open.

  5. Image titled Use Macros in Excel Step 29

    5

    Select your macro. Click the name of the macro which you want to run.

  6. Image titled Use Macros in Excel Step 30

    6

    Click Run. It’s on the right side of the window. Your macro will begin running.

  7. 7

    Wait for the macro to finish running. Depending on how large your macro is, this can take several seconds.

  8. Advertisement

Add New Question

  • Question

    Can I use a macro that I create in other spreadsheets and future spreadsheets on the same pc?

    Community Answer

    Yes, you can use a macro that you crate in other spreadsheets and future spreadsheets on the same pc.

  • Question

    How can I write macros that will change a spreadsheet as soon as I create it?

    Community Answer

    You will first need a basic understanding of VBA. There are many tutorials on this.

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

  • Macros are generally useful for automating tasks which you must perform often, such as calculating payroll at the end of the week.

Thanks for submitting a tip for review!

Advertisement

  • Although most macros are benign, some macros can maliciously change or delete information on your computer. Never open a macro from a source which you don’t trust.

Advertisement

About This Article

Article SummaryX

1. Enable Developer options in Excel.
2. Click the Developer tab.
3. Click Record Macro.
4. Enter the macro name and details.
5. Click OK.
6. Perform the macro’s steps.
7. Click Stop Recording.

Did this summary help you?

Thanks to all authors for creating a page that has been read 710,278 times.

Is this article up to date?

Macro codes can save you a ton of time.

You can automate small as well as heavy tasks with VBA codes.

And do you know?

With the help of macros…

…you can break all the limitations of Excel which you think Excel has.

And today, I have listed some of the useful codes examples to help you become more productive in your day to day work.

You can use these codes even if you haven’t used VBA before that.

But here’s the first thing to know:

What is a Macro Code?

In Excel, macro code is a programming code which is written in VBA (Visual Basic for Applications) language.

The idea behind using a macro code is to automate an action which you perform manually in Excel, otherwise.

For example, you can use a code to print only a particular range of cells just with a single click instead of selecting the range -> File Tab -> Print -> Print Select -> OK Button.

How to use a Macro Code in Excel

Before you use these codes, make sure you have your developer tab on your Excel ribbon to access VB editor. Once you activate developer tab you can use below steps to paste a VBA code into VB editor.

List of Top 100 macro Examples (CODES) for VBA beginners

I have added all the codes into specific categories so that you can find your favorite codes quickly. Just read the title and click on it to get the code.

note

  • This is my Ultimate VBA Library which I update on monthly basis with new codes and Don’t forget to check the VBA Examples Sectionꜜ at the end of this list.
  • VBA is one of the Advanced Excel Skills.
  • To manage all of these codes make sure to read about Personal Macro Workbook to use these codes in all the workbooks.
  • I have tested all of these codes in different versions of Excel (2007, 2010, 2013, 2016, and 2019). If you found any error in any of these codes, make sure to share with me.

Basic Codes

These VBA codes will help you to perform some basic tasks in a flash which you frequently do in your spreadsheets.

1. Add Serial Numbers

Sub AddSerialNumbers()
Dim i As Integer
On Error GoTo Last
i = InputBox("Enter Value", "Enter Serial Numbers")
For i = 1 To i
ActiveCell.Value = i
ActiveCell.Offset(1, 0).Activate
Next i
Last:Exit Sub
End Sub

This macro code will help you to automatically add serial numbers in your Excel sheet which can be helpful for you if you work with large data.

To use this code you need to select the cell from where you want to start the serial numbers and when you run this it shows you a message box where you need to enter the highest number for the serial numbers and click OK. And once you click OK, it simply runs a loop and add a list of serial numbers to the cells downward.

2. Insert Multiple Columns

Sub InsertMultipleColumns()
Dim i As Integer
Dim j As Integer
ActiveCell.EntireColumn.Select
On Error GoTo Last
i = InputBox("Enter number of columns to insert", "Insert Columns")
For j = 1 To i
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromRightorAbove
Next j
Last: Exit Sub
End Sub

This code helps you to enter multiple columns in a single click. When you run this code it asks you the number columns you want to add and when you click OK, it adds entered number of columns after the selected cell. If you want to add columns before the selected cell, replace the xlToRight to xlToLeft in the code.

3. Insert Multiple Rows

Sub InsertMultipleRows()
Dim i As Integer
Dim j As Integer
ActiveCell.EntireRow.Select
On Error GoTo Last
i = InputBox("Enter number of columns to insert", "Insert Columns")
For j = 1 To i
Selection.Insert Shift:=xlToDown, CopyOrigin:=xlFormatFromRightorAbove
Next j
Last: Exit Sub
End Sub

With this code, you can enter multiple rows in the worksheet. When you run this code, you can enter the number of rows to insert and make sure to select the cell from where you want to insert the new rows. If you want to add rows before the selected cell, replace the xlToDown to xlToUp in the code.

4. Auto Fit Columns

Sub AutoFitColumns()
Cells.Select
Cells.EntireColumn.AutoFit
End Sub

This code quickly auto fits all the columns in your worksheet. So when you run this code, it will select all the cells in your worksheet and instantly auto-fit all the columns.

5. Auto Fit Rows

Sub AutoFitRows()
Cells.Select
Cells.EntireRow.AutoFit
End Sub

You can use this code to auto-fit all the rows in a worksheet. When you run this code it will select all the cells in your worksheet and instantly auto-fit all the row.

6. Remove Text Wrap

Sub RemoveTextWrap()
Range("A1").WrapText = False
End Sub

This code will help you to remove text wrap from the entire worksheet with a single click. It will first select all the columns and then remove text wrap and auto fit all the rows and columns. There’s also a shortcut that you can use (Alt + H +‌W) for but if you add this code to Quick Access Toolbar it’s convenient than a keyboard shortcut.

7. Unmerge Cells

Sub UnmergeCells()
Selection.UnMerge
End Sub

This code simply uses the unmerge options which you have on the HOME‌ tab. The benefit of using this code is you can add it to the QAT and unmerge all the cell in the selection. And if you want to un-merge a specific range you can define that range in the code by replacing the word selection.

8. Open Calculator

Sub OpenCalculator()
Application.ActivateMicrosoftApp Index:=0
End Sub

In Windows, there is a specific calculator and by using this macro code you can open that calculator directly from Excel. As I mentioned that it’s for windows and if you run this code in the MAC version of VBA you’ll get an error.

9. Add Header/Footer Date

Sub DateInHeader()
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = "&D"
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub

This macro adds a date to the header when you run it. It simply uses the tag «&D» for adding the date. You can also change it to the footer or change the side by replacing the «» with the date tag. And if you want to add a specific date instead of the current date you can replace the «&D» tag with that date from the code.

10. Custom Header/Footer

Sub CustomHeader()
Dim myText As String
myText = InputBox("Enter your text here", "Enter Text")
With ActiveSheet.PageSetup
.LeftHeader = ""
.CenterHeader = myText
.RightHeader = ""
.LeftFooter = ""
.CenterFooter = ""
.RightFooter = ""
End With
End Sub

When you run this code, it shows an input box that asks you to enter the text which you want to add as a header, and once you enter it click OK.

If you see this closely you have six different lines of code to choose the place for the header or footer. Let’s say if you want to add left-footer instead of center header simply replace the “myText” to that line of the code by replacing the «» from there.

Formatting Codes

These VBA codes will help you to format cells and ranges using some specific criteria and conditions.

11. Highlight Duplicates from Selection

Sub HighlightDuplicateValues()
Dim myRange As Range
Dim myCell As Range
Set myRange = Selection
For Each myCell In myRange
If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then
myCell.Interior.ColorIndex = 36
End If
Next myCell
End Sub

This macro will check each cell of your selection and highlight the duplicate values.  You can also change the color from the code.

12. Highlight the Active Row and Column

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim strRange As String
strRange = Target.Cells.Address & "," & _
Target.Cells.EntireColumn.Address & "," & _
Target.Cells.EntireRow.Address
Range(strRange).Select
End Sub

I really love to use this macro code whenever I have to analyze a data table. Here are the quick steps to apply this code.

  1. Open VBE (ALT + F11).
  2. Go to Project Explorer (Ctrl + R, If hidden).
  3. Select your workbook & double click on the name of a particular worksheet in which you want to activate the macro.
  4. Paste the code into it and select the “BeforeDoubleClick” from event drop down menu.
  5. Close VBE and you are done.

Remember that, by applying this macro you will not able to edit the cell by double click.

13. Highlight Top 10 Values

Sub TopTen()
Selection.FormatConditions.AddTop10
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.TopBottom = xlTop10Top
.Rank = 10
.Percent = False
End With
With Selection.FormatConditions(1).Font
.Color = -16752384
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13561798
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub

Just select a range and run this macro and it will highlight top 10 values with the green color.

14. Highlight Named Ranges

Sub HighlightRanges()
Dim RangeName As Name
Dim HighlightRange As Range
On Error Resume Next
For Each RangeName In ActiveWorkbook.Names
Set HighlightRange = RangeName.RefersToRange
HighlightRange.Interior.ColorIndex = 36
Next RangeName
End Sub

If you are not sure about how many named ranges you have in your worksheet then you can use this code to highlight all of them.

15. Highlight Greater than Values

Sub HighlightGreaterThanValues()
Dim i As Integer
i = InputBox("Enter Greater Than Value", "Enter Value")
Selection.FormatConditions.Delete
Selection.FormatConditions.Add Type:=xlCellValue, _
Operator:=xlGreater, Formula1:=i
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
.Interior.Color = RGB(31, 218, 154)
End With
End Sub

Once you run this code it will ask you for the value from which you want to highlight all greater values.

16. Highlight Lower Than Values

Sub HighlightLowerThanValues()
Dim i As Integer
i = InputBox("Enter Lower Than Value", "Enter Value")
Selection.FormatConditions.Delete
Selection.FormatConditions.Add _
Type:=xlCellValue, _
Operator:=xlLower, _
Formula1:=i
Selection.FormatConditions(Selection.FormatConditions.Count).S
tFirstPriority
With Selection.FormatConditions(1)
.Font.Color = RGB(0, 0, 0)
.Interior.Color = RGB(217, 83, 79)
End With
End Sub

Once you run this code it will ask you for the value from which you want to highlight all lower values.

17. Highlight Negative Numbers

Sub highlightNegativeNumbers()
Dim Rng As Range
For Each Rng In Selection
If WorksheetFunction.IsNumber(Rng) Then
If Rng.Value < 0 Then
Rng.Font.Color= -16776961
End If
End If
Next
End Sub

Select a range of cells and run this code. It will check each cell from the range and highlight all cells the where you have a negative number.

18. Highlight Specific Text

Sub highlightValue()
Dim myStr As String
Dim myRg As range
Dim myTxt As String
Dim myCell As range
Dim myChar As String
Dim I As Long
Dim J As Long
On Error Resume Next
If ActiveWindow.RangeSelection.Count > 1 Then
myTxt = ActiveWindow.RangeSelection.AddressLocal
Else
myTxt = ActiveSheet.UsedRange.AddressLocal
End If
LInput: Set myRg = _
Application.InputBox _
("please select the data range:", "Selection Required", myTxt, , , , , 8)
If myRg Is Nothing Then
Exit Sub
If myRg.Areas.Count > 1 Then
MsgBox "not support multiple columns"
GoTo LInput
End If
If myRg.Columns.Count <> 2 Then
MsgBox "the selected range can only contain two columns "
GoTo LInput
End If
For I = 0 To myRg.Rows.Count - 1
myStr = myRg.range("B1").Offset(I, 0).Value
With myRg.range("A1").Offset(I, 0)
.Font.ColorIndex = 1
For J = 1 To Len(.Text)
Mid(.Text, J, Len(myStr)) = myStrThen
.Characters(J, Len(myStr)).Font.ColorIndex = 3
Next
End With
Next I
End Sub

Suppose you have a large data set and you want to check for a particular value. For this, you can use this code. When you run it, you will get an input box to enter the value to search for.

19. Highlight Cells with Comments

Sub highlightCommentCells()
Selection.SpecialCells(xlCellTypeComments).Select
Selection.Style= "Note"
End Sub

To highlight all the cells with comments use this macro.

20. Highlight Alternate Rows in the Selection

Sub highlightAlternateRows()
Dim rng As Range
For Each rng In Selection.Rows
If rng.Row Mod 2 = 1 Then
rng.Style = "20% -Accent1"
rng.Value = rng ^ (1 / 3)
Else
End If
Next rng
End Sub

By highlighting alternate rows you can make your data easily readable, and for this, you can use below VBA code. It will simply highlight every alternate row in selected range.

21. Highlight Cells with Misspelled Words

Sub HighlightMisspelledCells()
Dim rng As Range
For Each rng In ActiveSheet.UsedRange
If Not Application.CheckSpelling(word:=rng.Text) Then
rng.Style = "Bad"
End If
Next rng
End Sub

If you find hard to check all the cells for spelling error then this code is for you. It will check each cell from the selection and highlight the cell where is a misspelled word.

22. Highlight Cells With Error in the Entire Worksheet

Sub highlightErrors()
Dim rng As Range
Dim i As Integer
For Each rng In ActiveSheet.UsedRange
If WorksheetFunction.IsError(rng) Then
i = i + 1
rng.Style = "bad"
End If
Next rng
MsgBox _
"There are total " & i _
& " error(s) in this worksheet."
End Sub

To highlight and count all the cells in which you have an error, this code will help you. Just run this code and it will return a message with the number error cells and highlight all the cells.

23. Highlight Cells with a Specific Text in Worksheet

Sub highlightSpecificValues()
Dim rng As range
Dim i As Integer
Dim c As Variant
c = InputBox("Enter Value To Highlight")
For Each rng In ActiveSheet.UsedRange
If rng = c Then
rng.Style = "Note"
i = i + 1
End If
Next rng
MsgBox "There are total " & i & " " & c & " in this worksheet."
End Sub

This code will help you to count the cells which have a specific value which you will mention and after that highlight all those cells.

24. Highlight all the Blank Cells Invisible Space

Sub blankWithSpace()
Dim rng As Range
For Each rng In ActiveSheet.UsedRange
If rng.Value = " " Then
rng.Style = "Note"
End If
Next rng
End Sub

Sometimes there are some cells which are blank but they have a single space and due to this, it’s really hard to identify them. This code will check all the cell in the worksheet and highlight all the cells which have a single space.

25. Highlight Max Value In The Range

Sub highlightMaxValue()
Dim rng As Range
For Each rng In Selection
If rng = WorksheetFunction.Max(Selection) Then
rng.Style = "Good"
End If
Next rng
End Sub

It will check all the selected cells and highlight the cell with the maximum value.

26. Highlight Min Value In The Range

Sub Highlight_Min_Value()

Dim rng As Range

For Each rng In Selection
	If rng = WorksheetFunction.Min(Selection) Then
		rng.Style = "Good"
	End If
Next rng

End Sub

It will check all the selected cells and highlight the cell with the Minimum value.

27. Highlight Unique Values

Sub highlightUniqueValues()
Dim rng As Range
Set rng = Selection
rng.FormatConditions.Delete
Dim uv As UniqueValues
Set uv = rng.FormatConditions.AddUniqueValues
uv.DupeUnique = xlUnique
uv.Interior.Color = vbGreen
End Sub

This codes will highlight all the cells from the selection which has a unique value.

28. Highlight Difference in Columns

Sub columnDifference()
Range("H7:H8,I7:I8").Select
Selection.ColumnDifferences(ActiveCell).Select
Selection.Style= "Bad"
End Sub

Using this code you can highlight the difference between two columns (corresponding cells).

29. Highlight Difference in Rows

Sub rowDifference()
Range("H7:H8,I7:I8").Select
Selection.RowDifferences(ActiveCell).Select
Selection.Style= "Bad"
End Sub

And by using this code you can highlight difference between two row (corresponding cells).

Printing Codes

These macro codes will help you to automate some printing tasks which can further save you a ton of time. 

30. Print Comments

Sub printComments()
With ActiveSheet.PageSetup
.printComments = xlPrintSheetEnd
End With
End Sub

Use this macro to activate settings to print cell comments in the end of the page. Let’s say you have 10 pages to print, after using this code you will get all the comments on 11th last page.

31. Print Narrow Margin

Sub printNarrowMargin()
With ActiveSheet.PageSetup
.LeftMargin = Application
.InchesToPoints (0.25)
.RightMargin = Application.InchesToPoints(0.25)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.HeaderMargin = Application.InchesToPoints(0.3)
.FooterMargin = Application.InchesToPoints(0.3)
End With
ActiveWindow.SelectedSheets.PrintOut _
Copies:=1, _
Collate:=True, _
IgnorePrintAreas:=False
End Sub

Use this VBA code to take a print with a narrow margin. When you run this macro it will automatically change margins to narrow.

32. Print Selection

Sub printSelection()
Selection.PrintOut Copies:=1, Collate:=True
End Sub

This code will help you print selected range. You don’t need to go to printing options and set printing range. Just select a range and run this code.

33. Print Custom Pages

Sub printCustomSelection()
Dim startpage As Integer
Dim endpage As Integer
startpage = _
InputBox("Please Enter Start Page number.", "Enter Value")
If Not WorksheetFunction.IsNumber(startpage) Then
MsgBox _
"Invalid Start Page number. Please try again.", "Error"
Exit Sub
End If
endpage = _
InputBox("Please Enter End Page number.", "Enter Value")
If Not WorksheetFunction.IsNumber(endpage) Then
MsgBox _
"Invalid End Page number. Please try again.", "Error"
Exit Sub
End If
Selection.PrintOut From:=startpage, _
To:=endpage, Copies:=1, Collate:=True
End Sub

Instead of using the setting from print options you can use this code to print custom page range. Let’s say you want to print pages from 5 to 10. You just need to run this VBA code and enter start page and end page.

Worksheet Codes

These macro codes will help you to control and manage worksheets in an easy way and save your a lot of time.

34. Hide all but the Active Worksheet

Sub HideWorksheet()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> ThisWorkbook.ActiveSheet.Name Then
ws.Visible = xlSheetHidden
End If
Next ws
End Sub

Now, let’s say if you want to hide all the worksheets in your workbook other than the active worksheet. This macro code will do this for you.

35. Unhide all Hidden Worksheets

Sub UnhideAllWorksheet()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws
End Sub

And if you want to un-hide all the worksheets which you have hide with previous code, here is the code for that.

36. Delete all but the Active Worksheet

Sub DeleteWorksheets()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name <> ThisWorkbook.ActiveSheet.name Then
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End If
Next ws
End Sub

If you want to delete all the worksheets other than the active sheet, this macro is useful for you. When you run this macro it will compare the name of the active worksheet with other worksheets and then delete them.

37. Protect all Worksheets Instantly

Sub ProtectAllWorskeets()
Dim ws As Worksheet
Dim ps As String
ps = InputBox("Enter a Password.", vbOKCancel)
For Each ws In ActiveWorkbook.Worksheets
ws.Protect Password:=ps
Next ws
End Sub

If you want to protect your all worksheets in one go here is a code for you. When you run this macro, you will get an input box to enter a password. Once you enter your password, click OK. And make sure to take care about CAPS.

38. Resize All Charts in a Worksheet

Sub Resize_Charts()
Dim i As Integer
For i = 1 To ActiveSheet.ChartObjects.Count
With ActiveSheet.ChartObjects(i)
.Width = 300
.Height = 200
End With
Next i
End Sub

Make all chart same in size. This macro code will help you to make all the charts of the same size. You can change the height and width of charts by changing it in macro code.

39. Insert Multiple Worksheets

Sub InsertMultipleSheets()
Dim i As Integer
i = _
InputBox("Enter number of sheets to insert.", _
"Enter Multiple Sheets")
Sheets.Add After:=ActiveSheet, Count:=i
End Sub

You can use this code if you want to add multiple worksheets in your workbook in a single shot. When you run this macro code you will get an input box to enter the total number of sheets you want to enter.

40. Protect Worksheet

Sub ProtectWS()
ActiveSheet.Protect "mypassword", True, True
End Sub

If you want to protect your worksheet you can use this macro code. All you have to do just mention your password in the code.

41. Un-Protect Worksheet

Sub UnprotectWS()
ActiveSheet.Unprotect "mypassword"
End Sub

If you want to unprotect your worksheet you can use this macro code. All you have to do just mention your password which you have used while protecting your worksheet.

42. Sort Worksheets

Sub SortWorksheets()
Dim i As Integer
Dim j As Integer
Dim iAnswer As VbMsgBoxResult
iAnswer = MsgBox("Sort Sheets in Ascending Order?" & Chr(10) _
& "Clicking No will sort in Descending Order", _
vbYesNoCancel + vbQuestion + vbDefaultButton1, "Sort Worksheets")
For i = 1 To Sheets.Count
For j = 1 To Sheets.Count - 1
If iAnswer = vbYes Then
If UCase$(Sheets(j).Name) > UCase$(Sheets(j + 1).Name) Then
Sheets(j).Move After:=Sheets(j + 1)
End If
ElseIf iAnswer = vbNo Then
If UCase$(Sheets(j).Name) < UCase$(Sheets(j + 1).Name) Then Sheets(j).Move After:=Sheets(j + 1)
End If
End If
Next j
Next i
End Sub

This code will help you to sort worksheets in your workbook according to their name.

43. Protect all the Cells With Formulas

Sub lockCellsWithFormulas()
With ActiveSheet
.Unprotect
.Cells.Locked = False
.Cells.SpecialCells(xlCellTypeFormulas).Locked = True
.Protect AllowDeletingRows:=True
End With
End Sub

To protect cell with formula with a single click you can use this code.

44. Delete all Blank Worksheets

Sub deleteBlankWorksheets()
Dim Ws As Worksheet
On Error Resume Next
Application.ScreenUpdating= False
Application.DisplayAlerts= False
For Each Ws In Application.Worksheets
If Application.WorksheetFunction.CountA(Ws.UsedRange) = 0 Then
Ws.Delete
End If
Next
Application.ScreenUpdating= True
Application.DisplayAlerts= True
End Sub

Run this code and it will check all the worksheets in the active workbook and delete if a worksheet is blank.

45. Unhide all Rows and Columns

Sub UnhideRowsColumns()
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
End Sub

Instead of unhiding rows and columns on by one manually you can use this code to do this in a single go.

46. Save Each Worksheet as a Single PDF

Sub SaveWorkshetAsPDF()
Dimws As Worksheet
For Each ws In Worksheets
ws.ExportAsFixedFormat _
xlTypePDF, _
"ENTER-FOLDER-NAME-HERE" & _
ws.Name & ".pdf"
Next ws
End Sub

This code will simply save all the worksheets in a separate PDF file. You just need to change the folder name from the code.

47. Disable Page Breaks

Sub DisablePageBreaks()
Dim wb As Workbook
Dim wks As Worksheet
Application.ScreenUpdating = False
For Each wb In Application.Workbooks
For Each Sht In wb.Worksheets
Sht.DisplayPageBreaks = False
Next Sht
Next wb
Application.ScreenUpdating = True
End Sub

To disable page breaks use this code. It will simply disable page breaks from all the open workbooks.

Workbook Codes

These codes will help you to perform workbook level tasks in an easy way and with minimum efforts. 

48. Create a Backup of a Current Workbook

Sub FileBackUp()
ThisWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & _
"" & Format(Date, "mm-dd-yy") & " " & _
ThisWorkbook.name
End Sub

This is one of the most useful macros which can help you to save a backup file of your current workbook.

It will save a backup file in the same directory where your current file is saved and it will also add the current date with the name of the file.

49. Close all Workbooks at Once

Sub CloseAllWorkbooks()
Dim wbs As Workbook
For Each wbs In Workbooks
wbs.Close SaveChanges:=True
Next wb
End Sub

Use this macro code to close all open workbooks. This macro code will first check all the workbooks one by one and close them. If any of the worksheets is not saved, you’ll get a message to save it.

50. Copy Active Worksheet into a New Workbook

Sub CopyWorksheetToNewWorkbook()
ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)
End Sub

Let’s say if you want to copy your active worksheet in a new workbook, just run this macro code and it will do the same for you. It’s a super time saver.

51. Active Workbook in an Email

Sub Send_Mail()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.to = "Sales@FrontLinePaper.com"
.Subject = "Growth Report"
.Body = "Hello Team, Please find attached Growth Report."
.Attachments.Add ActiveWorkbook.FullName
.display
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub

Use this macro code to quickly send your active workbook in an e-mail. You can change the subject, email, and body text in code and if you want to send this mail directly, use «.Send» instead of «.Display».

52. Add Workbook to a Mail Attachment

Sub OpenWorkbookAsAttachment()
Application.Dialogs(xlDialogSendMail).Show
End Sub

Once you run this macro it will open your default mail client and attached active workbook with it as an attachment.

53. Welcome Message

Sub auto_open()
MsgBox _
"Welcome To ExcelChamps & Thanks for downloading this file."
End Sub

You can use auto_open to perform a task on opening a file and all you have to do just name your macro «auto_open».

54. Closing Message

Sub auto_close()
MsgBox "Bye Bye! Don't forget to check other cool stuff on
excelchamps.com"
End Sub

You can use close_open to perform a task on opening a file and all you have to do just name your macro «close_open».

55. Count Open Unsaved Workbooks

Sub VisibleWorkbooks()
Dim book As Workbook
Dim i As Integer
For Each book In Workbooks
If book.Saved = False Then
i = i + 1
End If
Next book
MsgBox i
End Sub

Let’s you have 5-10 open workbooks, you can use this code to get the number of workbooks which are not saved yet.

Pivot Table Codes

These codes will help you to manage and make some changes in pivot tables in a flash.

56. Hide Pivot Table Subtotals

Sub HideSubtotals()
Dim pt As PivotTable
Dim pf As PivotField
On Error Resume Next
Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.Name)
If pt Is Nothing Then
MsgBox "You must place your cursor inside of a PivotTable."
Exit Sub
End If
For Each pf In pt.PivotFields
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
End Sub

If you want to hide all the subtotals, just run this code. First of all, make sure to select a cell from your pivot table and then run this macro.

57. Refresh All Pivot Tables

Sub vba_referesh_all_pivots()
Dim pt As PivotTable
For Each pt In ActiveWorkbook.PivotTables
pt.RefreshTable
Next pt
End Sub

A super quick method to refresh all pivot tables. Just run this code and all of your pivot tables in your workbook will be refresh in a single shot.

58. Create a Pivot Table

Follow this step by step guide to create a pivot table using VBA.

59. Auto Update Pivot Table Range

Sub UpdatePivotTableRange()
Dim Data_Sheet As Worksheet
Dim Pivot_Sheet As Worksheet
Dim StartPoint As Range
Dim DataRange As Range
Dim PivotName As String
Dim NewRange As String
Dim LastCol As Long
Dim lastRow As Long
'Set Pivot Table & Source Worksheet
Set Data_Sheet = ThisWorkbook.Worksheets("PivotTableData3")
Set Pivot_Sheet = ThisWorkbook.Worksheets("Pivot3")
'Enter in Pivot Table Name
PivotName = "PivotTable2"
'Defining Staring Point & Dynamic Range
Data_Sheet.Activate
Set StartPoint = Data_Sheet.Range("A1")
LastCol = StartPoint.End(xlToRight).Column
DownCell = StartPoint.End(xlDown).Row
Set DataRange = Data_Sheet.Range(StartPoint, Cells(DownCell, LastCol))
NewRange = Data_Sheet.Name & "!" & DataRange.Address(ReferenceStyle:=xlR1C1)
'Change Pivot Table Data Source Range Address
Pivot_Sheet.PivotTables(PivotName). _
ChangePivotCache ActiveWorkbook. _
PivotCaches.Create(SourceType:=xlDatabase, SourceData:=NewRange)
'Ensure Pivot Table is Refreshed
Pivot_Sheet.PivotTables(PivotName).RefreshTable
'Complete Message
Pivot_Sheet.Activate
MsgBox "Your Pivot Table is now updated."
End Sub

If you are not using Excel tables then you can use this code to update pivot table range.

60. Disable/Enable Get Pivot Data

Sub activateGetPivotData()
Application.GenerateGetPivotData = True
End Sub
Sub deactivateGetPivotData()
Application.GenerateGetPivotData = False
End Sub

To disable/enable GetPivotData function you need to use Excel option. But with this code you can do it in a single click.

Charts Codes

Use these VBA codes to manage charts in Excel and save your lot of time. 

61. Change Chart Type

Sub ChangeChartType()
ActiveChart.ChartType = xlColumnClustered
End Sub

This code will help you to convert chart type without using chart options from the tab. All you have to do just specify to which type you want to convert.

Below code will convert selected chart to a clustered column chart. There are different codes for different types, you can find all those types from here.

62. Paste Chart as an Image

Sub ConvertChartToPicture()
ActiveChart.ChartArea.Copy
ActiveSheet.Range("A1").Select
ActiveSheet.Pictures.Paste.Select
End Sub

This code will help you to convert your chart into an image. You just need to select your chart and run this code.

63. Add Chart Title

Sub AddChartTitle()
Dim i As Variant
i = InputBox("Please enter your chart title", "Chart Title")
On Error GoTo Last
ActiveChart.SetElement (msoElementChartTitleAboveChart)
ActiveChart.ChartTitle.Text = i
Last:
Exit Sub
End Sub

First of all, you need to select your chart and the run this code. You will get an input box to enter chart title.

Advanced Codes

Some of the codes which you can use to preform advanced task in your spreadsheets.

64. Save Selected Range as a PDF

Sub HideSubtotals()
Dim pt As PivotTable
Dim pf As PivotField
On Error Resume Next
Set pt = ActiveSheet.PivotTables(ActiveCell.PivotTable.name)
If pt Is Nothing Then
MsgBox "You must place your cursor inside of a PivotTable."
Exit Sub
End If
For Each pf In pt.PivotFields
pf.Subtotals(1) = True
pf.Subtotals(1) = False
Next pf
End Sub

If you want to hide all the subtotals, just run this code. First of all, make sure to select a cell from your pivot table and then run this macro.

65. Create a Table of Content

Sub TableofContent()
Dim i As Long
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Table of Content").Delete
Application.DisplayAlerts = True
On Error GoTo 0
ThisWorkbook.Sheets.Add Before:=ThisWorkbook.Worksheets(1)
ActiveSheet.Name = "Table of Content"
For i = 1 To Sheets.Count
With ActiveSheet
.Hyperlinks.Add _
Anchor:=ActiveSheet.Cells(i, 1), _
Address:="", _
SubAddress:="'" & Sheets(i).Name & "'!A1", _
ScreenTip:=Sheets(i).Name, _
TextToDisplay:=Sheets(i).Name
End With
Next i
End Sub

Let’s say you have more than 100 worksheets in your workbook and it’s hard to navigate now.

Don’t worry this macro code will rescue everything. When you run this code it will create a new worksheet and create a index of worksheets with a hyperlink to them.

66. Convert Range into an Image

Sub PasteAsPicture()
Application.CutCopyMode = False
Selection.Copy
ActiveSheet.Pictures.Paste.Select
End Sub

Paste selected range as an image. You just have to select the range and once you run this code it will automatically insert a picture for that range.

67. Insert a Linked Picture

Sub LinkedPicture()
Selection.Copy
ActiveSheet.Pictures.Paste(Link:=True).Select
End Sub

This VBA code will convert your selected range into a linked picture and you can use that image anywhere you want.

68. Use Text to Speech

Sub Speak()
Selection.Speak
End Sub

Just select a range and run this code. Excel will speak all the text what you have in that range, cell by cell.

69. Activate Data Entry Form

Sub DataForm()
ActiveSheet.ShowDataForm
End Sub

There is a default data entry form which you can use for data entry.

70. Use Goal Seek

Sub GoalSeekVBA()
Dim Target As Long
On Error GoTo Errorhandler
Target = InputBox("Enter the required value", "Enter Value")
Worksheets("Goal_Seek").Activate
With ActiveSheet.Range("C7")
.GoalSeek_ Goal:=Target, _
ChangingCell:=Range("C2")
End With
Exit Sub
Errorhandler: MsgBox ("Sorry, value is not valid.")
End Sub

Goal Seek can be super helpful for you to solve complex problems. Learn more about goal seek from here before you use this code.

71. VBA Code to Search on Google

Sub SearchWindow32()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Enter here your search here", "Google Search")
search_string = query
search_string = Replace(search_string, " ", "+")
'Uncomment the following line for Windows 64 versions and comment out Windows 32 versions'
'chromePath = "C:Program FilesGoogleChromeApplicationchrome.exe"
'Uncomment the following line for Windows 32 versions and comment out Windows 64 versions
'chromePath = "C:Program Files (x86)GoogleChromeApplicationchrome.exe"
Shell (chromePath & " -url http://google.com/#q=" & search_string)
End Sub

Formula Codes

These codes will help you to calculate or get results which often you do with worksheet functions and formulas.

72. Convert all Formulas into Values

Sub convertToValues()
Dim MyRange As Range
Dim MyCell As Range
Select Case _
MsgBox("You Can't Undo This Action. " _
& "Save Workbook First?", vbYesNoCancel, _
"Alert")
Case Is = vbYes
ThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
Set MyRange = Selection
For Each MyCell In MyRange
If MyCell.HasFormula Then
MyCell.Formula = MyCell.Value
End If
Next MyCell
End Sub

Simply convert formulas into values. When you run this macro it will quickly change the formulas into absolute values.

73. Remove Spaces from Selected Cells

Sub RemoveSpaces()
Dim myRange As Range
Dim myCell As Range
Select Case MsgBox("You Can't Undo This Action. " _
& "Save Workbook First?", _
vbYesNoCancel, "Alert")
Case Is = vbYesThisWorkbook.Save
Case Is = vbCancel
Exit Sub
End Select
Set myRange = Selection
For Each myCell In myRange
If Not IsEmpty(myCell) Then
myCell = Trim(myCell)
End If
Next myCell
End Sub

One of the most useful macros from this list. It will check your selection and then remove all the extra spaces from that.

74. Remove Characters from a String

Public Function removeFirstC(rng As String, cnt As Long)
removeFirstC = Right(rng, Len(rng) - cnt)
End Function

Simply remove characters from the starting of a text string. All you need is to refer to a cell or insert a text into the function and number of characters to remove from the text string.

It has two arguments «rng» for the text string and «cnt» for the count of characters to remove. For Example: If you want to remove first characters from a cell, you need to enter 1 in cnt.

75. Add Insert Degree Symbol in Excel

Sub degreeSymbol( )
Dim rng As Range
For Each rng In Selection
rng.Select
If ActiveCell <> "" Then
If IsNumeric(ActiveCell.Value) Then
ActiveCell.Value = ActiveCell.Value & "°"
End If
End If
Next
End Sub

Let’s say you have a list of numbers in a column and you want to add degree symbol with all of them.

76. Reverse Text

Public Function rvrse(ByVal cell As Range) As String
rvrse = VBA.strReverse(cell.Value)
End Function

All you have to do just enter «rvrse» function in a cell and refer to the cell in which you have text which you want to reverse.

77. Activate R1C1 Reference Style

Sub ActivateR1C1()
If Application.ReferenceStyle = xlA1 Then
Application.ReferenceStyle = xlR1C1
Else
Application.ReferenceStyle = xlR1C1
End If
End Sub

This macro code will help you to activate R1C1 reference style without using Excel options.

78. Activate A1 Reference Style

Sub ActivateA1()
If Application.ReferenceStyle = xlR1C1 Then
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlA1
End If
End Sub

This macro code will help you to activate A1 reference style without using Excel options.

79. Insert Time Range

Sub TimeStamp()
Dim i As Integer
For i = 1 To 24
ActiveCell.FormulaR1C1 = i & ":00"
ActiveCell.NumberFormat = "[$-409]h:mm AM/PM;@"
ActiveCell.Offset(RowOffset:=1, ColumnOffset:=0).Select
Next i
End Sub

With this code, you can insert a time range in sequence from 00:00 to 23:00.

80. Convert Date into Day

Sub date2day()
Dim tempCell As Range
Selection.Value = Selection.Value
For Each tempCell In Selection
If IsDate(tempCell) = True Then
With tempCell
.Value = Day(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub

If you have dates in your worksheet and you want to convert all those dates into days then this code is for you. Simply select the range of cells and run this macro.

81. Convert Date into Year

Sub date2year()
Dim tempCell As Range
Selection.Value = Selection.Value
For Each tempCell In Selection
If IsDate(tempCell) = True Then
With tempCell
.Value = Year(tempCell)
.NumberFormat = "0"
End With
End If
Next tempCell
End Sub

This code will convert dates into years.

82. Remove Time from Date

Sub removeTime()
Dim Rng As Range
For Each Rng In Selection
If IsDate(Rng) = True Then
Rng.Value = VBA.Int(Rng.Value)
End If
Next
Selection.NumberFormat = "dd-mmm-yy"
End Sub

If you have time with the date and you want to remove it then you can use this code.

83. Remove Date from Date and Time

Sub removeDate()
Dim Rng As Range
For Each Rng In Selection
If IsDate(Rng) = True Then
Rng.Value = Rng.Value - VBA.Fix(Rng.Value)
End If
NextSelection.NumberFormat = "hh:mm:ss am/pm"
End Sub

It will return only time from a date and time value.

84. Convert to Upper Case

Sub convertUpperCase()
Dim Rng As Range
For Each Rng In Selection
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Rng)
End If
Next
End Sub

Select the cells and run this code. It will check each and every cell of selected range and then convert it into upper case text.

85. Convert to Lower Case

Sub convertLowerCase()
Dim Rng As Range
For Each Rng In Selection
If Application.WorksheetFunction.IsText(Rng) Then
Rng.Value= LCase(Rng)
End If
Next
End Sub

This code will help you to convert selected text into lower case text. Just select a range of cells where you have text and run this code. If a cell has a number or any value other than text that value will remain same.

86. Convert to Proper Case

Sub convertProperCase()
Dim Rng As Range
For Each Rng In Selection
If WorksheetFunction.IsText(Rng) Then
Rng.Value = WorksheetFunction.Proper(Rng.Value)
End If
Next
End Sub

And this code will convert selected text into the proper case where you have the first letter in capital and rest in small.

87. Convert to Sentence Case

Sub convertTextCase()
Dim Rng As Range
For Each Rng In Selection
If WorksheetFunction.IsText(Rng) Then
Rng.Value = UCase(Left(Rng, 1)) & LCase(Right(Rng, Len(Rng) - 1))
End If
Next Rng
End Sub

In text case, you have the first letter of the first word in capital and rest all in words in small for a single sentence and this code will help you convert normal text into sentence case.

88. Remove a Character from Selection

Sub removeChar()
Dim Rng As Range
Dim rc As String
rc = InputBox("Character(s) to Replace", "Enter Value")
For Each Rng In Selection
Selection.Replace What:=rc, Replacement:=""
Next
End Sub

To remove a particular character from a selected cell you can use this code. It will show you an input box to enter the character you want to remove.

89. Word Count from Entire Worksheet

Sub Word_Count_Worksheet()
Dim WordCnt As Long
Dim rng As Range
Dim S As String
Dim N As Long
For Each rng In ActiveSheet.UsedRange.Cells
S = Application.WorksheetFunction.Trim(rng.Text)
N = 0
If S <> vbNullString Then
N = Len(S) - Len(Replace(S, " ", "")) + 1
End If
WordCnt = WordCnt + N
Next rng
MsgBox "There are total " _
& Format(WordCnt, "#,##0") & _
" words in the active worksheet"
End Sub

It can help you to count all the words from a worksheet.

90. Remove the Apostrophe from a Number

Sub removeApostrophes()
Selection.Value = Selection.Value
End Sub

If you have numeric data where you have an apostrophe before each number, you run this code to remove it.

91. Remove Decimals from Numbers

Sub removeDecimals()
Dim lnumber As Double
Dim lResult As Long
Dim rng As Range
For Each rng In Selection
rng.Value = Int(rng)
rng.NumberFormat = "0"
Next rng
End Sub

This code will simply help you to remove all the decimals from the numbers from the selected range.

92. Multiply all the Values by a Number

Sub addNumber()
Dim rng As Range
Dim i As Integer
i = InputBox("Enter number to multiple", "Input Required")
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng + i
Else
End If
Next rng
End Sub

Let’s you have a list of numbers and you want to multiply all the number with a particular. To use this code: Select that range of cells and run this code. It will first ask you for the number with whom you want to multiple and then instantly multiply all the numbers with it.

93. Add a Number in all the Numbers

Sub addNumber()
Dim rng As Range
Dim i As Integer
i = InputBox("Enter number to multiple", "Input Required")
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng + i
Else
End If
Next rng
End Sub

Just like multiplying you can also add a number into a set of numbers.

94. Calculate the Square Root

Sub getSquareRoot()
Dim rng As Range
Dim i As Integer
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = Sqr(rng)
Else
End If
Next rng
End Sub

To calculate square root without applying a formula you can use this code. It will simply check all the selected cells and convert numbers to their square root.

95. Calculate the Cube Root

Sub getCubeRoot()
Dim rng As Range
Dimi As Integer
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = rng ^ (1 / 3)
Else
End If
Nextrng
End Sub

To calculate cube root without applying a formula you can use this code. It will simply check all the selected cells and convert numbers to their cube root.

96. Add A-Z Alphabets in a Range

Sub addsAlphabets1()
Dim i As Integer
For i = 65 To 90
ActiveCell.Value = Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub
Sub addsAlphabets2()
Dim i As Integer
For i = 97 To 122
ActiveCell.Value = Chr(i)
ActiveCell.Offset(1, 0).Select
Next i
End Sub

Just like serial numbers you can also insert alphabets in your worksheet. Beloware the code which you can use.

97. Convert Roman Numbers into Arabic Numbers

Sub convertToNumbers()
Dim rng As Range
Selection.Value = Selection.Value
For Each rng In Selection
If Not WorksheetFunction.IsNonText(rng) Then
rng.Value = WorksheetFunction.Arabic(rng)
End If
Next rng
End Sub

Sometimes it’s really hard to understand Roman numbers as serial numbers. This code will help you to convert roman numbers into Arabic numbers.

98. Remove Negative Signs

Sub removeNegativeSign()
Dim rng As Range
Selection.Value = Selection.Value
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
rng.Value = Abs(rng)
End If
Next rng

This code will simply check all the cell in the selection and convert all the negative numbers into positive. Just select a range and run this code.

99. Replace Blank Cells with Zeros

Sub replaceBlankWithZero()
Dim rng As Range
Selection.Value = Selection.Value
For Each rng In Selection
If rng = "" Or rng = " " Then
rng.Value = "0"
Else
End If
Next rng
End Sub

For data where you have blank cells, you can use the below code to add zeros in all those cells. It makes easier to use those cells in further calculations.

More Codes

100. More VBA Examples and Tutorials

  • User Defined Function [UDF] in Excel using VBA
  • VBA Interview Questions
  • Add a Comment in a VBA Code (Macro)
  • Add a Line Break in a VBA Code (Single Line into Several Lines)
  • Add a New Line (Carriage Return) in a String in VBA
  • Personal Macro Workbook (personal.xlsb)
  • Record a Macro in Excel
  • VBA Exit Sub Statement
  • VBA Immediate Window (Debug.Print)
  • VBA Module
  • VBA MSGBOX
  • VBA Objects
  • VBA With Statement
  • Count Rows using VBA
  • Excel VBA Font (Color, Size, Type, and Bold)
  • Excel VBA Hide and Unhide a Column or a Row
  • Excel VBA Range – Working with Range and Cells in VBA
  • Apply Borders on a Cell using VBA in Excel
  • Find Last Row, Column, and Cell using VBA in Excel
  • Insert a Row using VBA in Excel
  • Merge Cells in Excel using a VBA Code
  • Select a Range/Cell using VBA in Excel
  • How to SELECT ALL the Cells in a Worksheet using a VBA Code
  • use ActiveCell in VBA in Excel
  • How to use Special Cells Method in VBA in Excel
  • How to use UsedRange Property in VBA in Excel
  • VBA AutoFit (Rows, Column, or the Entire Worksheet)
  • VBA ClearContents (from a Cell, Range, or Entire Worksheet)
  • VBA Copy Range to Another Sheet + Workbook
  • VBA Enter Value in a Cell (Set, Get and Change)
  • VBA Insert Column (Single and Multiple)
  • VBA Named Range
  • VBA Range Offset
  • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
  • VBA Wrap Text (Cell, Range, and Entire Worksheet)
  • How to CLEAR an Entire Sheet using VBA in Excel
  • How to Copy and Move a Sheet in Excel using VBA
  • How to COUNT Sheets using VBA in Excel
  • How to DELETE a SHEET using VBA in Excel
  • How to Hide & Unhide a Sheet using VBA in Excel
  • How to PROTECT and UNPROTECT a Sheet using VBA in Excel
  • RENAME a Sheet using VBA
  • Write a VBA Code to Create a New Sheet
  • VBA Worksheet Object
  • Activate a Sheet using VBA
  • Copy an Excel File (Workbook)
  • VBA Activate Workbook (Excel File)
  • VBA Close Workbook (Excel File)
  • VBA Combine Workbooks (Excel Files)
  • VBA Create New Workbook (Excel File)
  • VBA Delete Workbook (Excel File)
  • VBA Open Workbook (Excel File)
  • VBA Protect/Unprotect Workbook (Excel File)
  • VBA Rename Workbook (Excel File)
  • VBA Save Workbook (Excel File)
  • VBA ThisWorkbook (Current Excel File)
  • VBA Workbook 
  • Declare Global Variable (Public) in VBA
  • Range or a Cell as a Variable in VBA
  • Option Explicit Statement in VBA
  • Variable in a Message Box
  • VBA Constants
  • VBA Dim Statement
  • VBA Variables (Declare, Data Types, and Scope)
  • VBA Add New Value to the Array
  • VBA Array
  • VBA Array Length (Size)
  • VBA Array with Strings
  • VBA Clear Array (Erase)
  • VBA Dynamic Array
  • VBA Loop Through an Array
  • VBA Multi-Dimensional Array
  • VBA Range to an Array
  • VBA Search for a Value in an Array
  • VBA Sort Array
  • How to Average Values in Excel using VBA
  • Get Today’s Date and Current Time using VBA
  • Sum Values in Excel using VBA
  • Match Function in VBA
  • MOD in VBA
  • Random Number
  • VBA Calculate (Cell, Range, Row, & Workbook)
  • VBA Concatenate
  • VBA Worksheet Function (Use Excel Functions in a Macro)
  • How to Check IF a Sheet Exists using VBA in Excel
  • VBA Check IF a Cell is Empty + Multiple Cells
  • VBA Check IF a Workbook Exists in a Folder (Excel File)
  • VBA Check IF a Workbook is Open (Excel File)
  • VBA Exit IF
  • VBA IF – IF Then Else Statement
  • VBA IF And (Test Multiple Conditions)
  • VBA IF Not
  • VBA IF OR (Test Multiple Conditions)
  • VBA Nested IF
  • VBA SELECT CASE Statement (Test Multiple Conditions)
  • VBA Automation Error (Error 440)
  • VBA Error 400
  • VBA ERROR Handling
  • VBA Invalid Procedure Call Or Argument Error (Error 5)
  • VBA Object Doesn’t Support this Property or Method Error (Error 438)
  • VBA Object Required Error (Error 424)
  • VBA Out of Memory Error (Error 7)
  • VBA Overflow Error (Error 6)
  • VBA Runtime Error (Error 1004)
  • VBA Subscript Out of Range Runtime Error (Error 9)
  • VBA Type Mismatch Error (Error 13)
  • Excel VBA Do While Loop and (Do Loop While)
  • How to Loop Through All the Sheets using VBA
  • Loop Through a Range using VBA
  • VBA FOR LOOP
  • VBA GoTo Statement
  • Input Box in VBA
  • VBA Create and Write to a Text File
  • VBA ScreenUpdating
  • VBA Status Bar
  • VBA Wait and Sleep

About the Author

puneet one point one

Puneet is using Excel since his college days. He helped thousands of people to understand the power of the spreadsheets and learn Microsoft Excel. You can find him online, tweeting about Excel, on a running track, or sometimes hiking up a mountain.


Excel Macros — Overview

An Excel macro is an action or a set of actions that you can record, give a name, save and run as many times as you want and whenever you want. When you create a macro, you are recording your mouse clicks and keystrokes. When you run a saved macro, the recorded mouse clicks and keystrokes will be executed in the same sequence as they are recorded.

Macros help you to save time on repetitive tasks involved in data manipulation and data reports that are required to be done frequently.

Macro and VBA

You can record and run macros with either Excel commands or from Excel VBA.

VBA stands for Visual Basic for Applications and is a simple programming language that is available through Excel Visual Basic Editor (VBE), which is available from the DEVELOPER tab on the Ribbon. When you record a macro, Excel generates VBA code. If you just want to record a macro and run it, there is no need to learn Excel VBA. However, if you want to modify a macro, then you can do it only by modifying the VBA code in the Excel VBA editor.

You will learn how to record a simple macro and run it with Excel commands in the chapter — Creating a Simple Macro. You will learn more about macros and about creating and / or modifying macros from Excel VBA editor in the later chapters.

Personal Macro Workbook

A macro can be saved in the same workbook from where you recorded it. In that case, you can run the macro from that workbook only and hence you should keep it open. Excel gives you an alternative way to store all your macros. It is the personal macro workbook, where you can save your macros, which enables you to run those macros from any workbook.

You will learn about Personal Macro Workbook in the chapter — Saving all your Macros in a Single Workbook.

Macro Security

Macros will be stored as VBA code in Excel. As with the case of any other code, macro code is also susceptible to malicious code that can run when you open a workbook. This is a threat to your computer. Microsoft provided with the Macro Security facility that helps you in protecting your computer from such macro viruses.

You will learn more about this in the chapter — Macro Security.

Absolute References and Relative References

While recording a macro, you can use either absolute references or relative references for the cells on which you are clicking. Absolute references make your macro run at the same cells where you recorded the macro. On the other hand, relative references make your macro run at the active cell.

You will learn about these in the chapters — Using Absolute References for a Macro and Using Relative References for a Macro.

Macro Code in VBA

You can record and run macros from Excel even if you do not know Excel VBA. However, if you have to modify a recorded macro or create a macro by writing VBA code, you should learn Excel VBA. You can refer to the Excel VBA tutorial in this tutorials library for this

However, you should know how to view the macro code. You can learn how to access VBA editor in Excel and about the different parts of the VBA editor in the chapter – Excel VBA.

You can learn how to view the macro code in Excel VBA editor and you can understand the macro code in the chapter — Understanding Macro Code.

Assigning Macros to Objects

You can assign a macro to an object such as a shape or a graphic or a control. Then, you can run the macro by clicking on that object. You will learn about this in the chapter — Assigning Macros to Objects.

Running Macros

Excel provides several ways to run a macro. You can choose the way you want to run a macro. You will learn about these different possible ways of running a macro in the chapter — Running a Macro.

Creating a Macro Using VBA Editor

If you decide to write the macro code, you can learn it in the chapter — Creating a Macro Using VBA Editor. However, the prerequisite is that you should have Excel VBA knowledge.

Editing a Macro

You can modify macro code in Excel VBA editor. If you want to make extensive changes, you should have Excel VBA knowledge. But, if you want to make only minor changes to the code or if you want to copy the VBA code from a recorded macro to another macro, you can refer to the chapter — Editing a Macro.

You can rename a macro and even delete it. You will learn about this also in the same chapter.

User Forms

A Form is normally used to collect required information. It will be self-explanatory making the task simple. Excel User Forms created from Excel VBA editor serve the same purpose, providing the familiar options such as text boxes, check boxes, radio buttons, list boxes, combo boxes, scroll bars, etc. as controls.

You will learn how to create a User Form and how to use the different controls in the chapter – User Forms.

Debugging Macro Code

At times, a macro may not run as expected. You might have created the macro or you might be using a macro supplied to you by someone. You can debug the macro code just as you debug any other code to uncover the defects and correct them. You will learn about this in the chapter — Debugging Macro Code.

Configuring a Macro to Run on Opening a Workbook

You can make your macro run automatically when you open a workbook. You can do this either by creating an Auto_Run macro or by writing VBA code for workbook open event. You will learn this in the chapter — Configuring a Macro to Run on Opening a Workbook.

Excel Macros — Creation

You can create a macro with Excel commands by recording the key strokes and mouse clicks, giving the macro a name and specifying how to store the macro. A macro thus recorded can be run with an Excel command.

Suppose you have to collect certain results repeatedly in the following format −

Format

Instead of creating the table each time, you can have a macro to do it for you.

Recording a Macro

To record a macro do the following −

  • Click the VIEW tab on the Ribbon.
  • Click Macros in the Macros group.
  • Select Record Macro from the dropdown list.

Record

The Record Macro dialog box appears.

  • Type MyFirstMacro in the Macro name box.

  • Type A Simple Macro in the Description box and click OK.

Record Macro

Remember that whatever key strokes and mouse clicks you do, will be recorded now.

  • Click in the cell B2.

  • Create the table.

  • Click in a different cell in the worksheet.

  • Click the VIEW tab on the Ribbon.

  • Click Macros.

  • Select Stop Recording from the dropdown list.

Stop Recording

Your macro recording is completed.

The first step to click on a particular cell is important as it tells where exactly the macro has to start placing the recorded steps. Once you are done with the recording, you have to click Stop Recording to avoid recording of unnecessary steps.

Running a Macro

You can run the macro you have recorded any number of times you want. To run the macro, do the following −

  • Click on a new worksheet.

Note the active cell. In our case, it is A1.

  • Click the VIEW tab on the Ribbon.

  • Click Macros.

  • Select View Macros from the dropdown list.

View

The Macro dialog box appears.

Macro Dialog Box

Only the macro that you recorded appears in the Macros list.

  • Click the macro name – MyFirstMacro in the Macro dialog box. The description you typed while recording the macro will get displayed. Macro description allows you to identify for what purpose you have recorded the macro.

  • Click the Run button. The same table that you have created while recording the macro will appear in just a split of a second.

Macros List

You have discovered the magic wand that Excel provides you to save time on mundane tasks. You will observe the following −

  • Though the active cell before running the macro was A1, the table is placed in the cell B2 as you have recorded.

  • In addition, the active cell became E2, as you have clicked that cell before you stopped recording.

You can run the macro in multiple worksheets with different active cells before running the macro and observe the same conditions as given above. Just keep a note of this and you will understand later in this tutorial why it has occurred so.

You can also have a macro recording that places your recorded steps in the active cell. You will learn how to do this as you progress in the tutorial.

Storing a Macro

You might wonder how to save the macros that are created. In this context you need to know −

  • Storing a macro
  • Saving a macro enabled file

As and when you create a macro, you can choose where to store that particular macro. You can do this in the Record Macro dialog box.

Click the box — Store macro in. The following three options are available −

  • This Workbook.
  • New Workbook.
  • Personal Macro Workbook

Store Macro

This Workbook

This is the default option. The macro will be stored in your current workbook from where you created the macro.

New Workbook

This option, though available, is not recommended. You will be asking Excel to store the macro in a different new workbook and mostly it is not necessary.

Personal Macro Workbook

If you create several macros that you use across your workbooks, Personal Macro Workbook provides you with the facility to store all the macros at one place. You will learn more about this option in the next chapter.

Saving a Macro Enabled File

If you had chosen This Workbook as the option for storing the macro, you would need to save your workbook along with the macro.

Try to save the workbook. By default, you would be asking Excel to save the workbook as an .xls file. Excel displays a message saying that an Excel feature VB project cannot be saved in a macro free workbook, as shown below.

This Workbook

Note − If you click Yes, Excel will save your workbook as a macro free .xls file and your macro that you stored with This Workbook option will not get saved. To avoid this, Excel provides you an option to save your workbook as a macro-enabled workbook that will have .xlsm extension.

  • Click No in the warning message box.
  • Select Excel Macro-Enabled Workbook (*.xlsm) in the Save as type.
  • Click Save.

Save File

You will learn more about these in later chapters in this tutorial.

Excel Macros — Macros in a Single Workbook

Excel provides you with a facility to store all your macros in a single workbook. The workbook is called Personal Macro Workbook — Personal.xlsb. It is a hidden workbook stored on your computer, which opens every time you open Excel. This enables you to run your macros from any workbook. There will be a single Personal Macro Workbook per computer and you cannot share it across computers. You can view and run the macros in your Personal Macro Workbook from any workbook on your computer.

Saving Macros in Personal Macro Workbook

You can save macros in your Personal Macro Workbook by selecting it as the storing option while recording the macros.

Select Personal Macro Workbook from the drop down list under the category Store macro in.

Personal Macro

  • Record your second macro.
  • Give macro details in the Record Macro dialog box as shown below.
  • Click OK.

Second Macro

Your recording starts. Create a table as shown below.

Recording Starts

  • Stop recording.

  • Click the VIEW tab on the Ribbon.

  • Click Macros.

  • Select View Macros from the dropdown list. The Macro dialog box appears.

View Macros

The macro name appears with a prefix PERSONAL.XLSB! indicating that the Macro is in the Personal Macro Workbook.

Save your workbook. It will get saved as an .xls file as the macro is not in your workbook and close Excel.

You will get the following message regarding saving the changes to the Personal Macro Workbook −

Save

Click the Save button. Your macro is saved in the Personal.xlsb file on your computer.

Hiding / Unhiding Personal Macro Workbook

Personal Macro Workbook will be hidden, by default. When you start Excel, the personal macro workbook is loaded but you cannot see it because it is hidden. You can unhide it as follows −

  • Click the VIEW tab on the Ribbon.

  • Click Unhide in the Window group.

View Tab

The Unhide dialog box appears.

Unhide

PERSONAL.XLSB appears in the Unhide workbook box and click OK.

Personal XLSB

Now you can view the macros saved in the personal macro workbook.

To hide the personal macro workbook, do the following −

  • Click on the personal macro workbook.
  • Click the VIEW tab on the Ribbon.
  • Click Hide on the Ribbon.

Running Macros Saved in Personal Macro Workbook

You can run the macros saved in personal macro workbook from any workbook. To run the macros, it does not make any difference whether the personal macro workbook is hidden or unhidden.

  • Click View Macros.
  • Select the macro name from the macros list.
  • Click the Run button. The macro will run.

Adding / Deleting Macros in Personal Macro Workbook

You can add more macros in personal macro workbook by selecting it for Store macro in option while recording the macros, as you had seen earlier.

You can delete a macro in personal macro workbook as follows −

  • Make sure that the personal macro workbook is unhidden.
  • Click the macro name in the View Macros dialog box.
  • Click the Delete button.

If the personal macro workbook is hidden, you will get a message saying “Cannot edit a macro on a hidden workbook”.

Hidden Workbook

Unhide the personal macro workbook and delete the selected macro.

The macro will not appear in the macros list. However, when you create a new macro and save it in your personal workbook or delete any macros that it contains, you will be prompted to save the personal workbook just as in the case you saved it first time.

Excel Macros — Security

The macros that you create in Excel would be written in the programming language VBA (Visual Basic for Applications). You will learn about the Excel macro code in later chapters. As you are aware, when there is an executable code, there is a threat of viruses. Macros are also susceptible to viruses.

What are Macro Viruses?

Excel VBA in which the Macros are written has access to most Windows system calls and executes automatically when workbooks are opened. Hence, there is a potential threat of the existence of a virus written as a macro and is hidden within Excel that are executed on opening a workbook. Therefore, Excel macros can be very dangerous to your computer in many ways. However, Microsoft has taken appropriate measures to shield the workbooks from macro viruses.

Microsoft has introduced macro security so that you can identify which macros you can trust and which you cannot.

Macro Enabled Excel Workbooks

The most important Excel macro security feature is — file extensions.

Excel workbooks will be saved with .xlsx file extension by default. You can always trust workbooks with .xlsx file extension, as they are incapable of storing a macro and will not carry any threat.

Excel workbooks with macros are saved with .xlsm file extension. They are termed as Macro Enabled Excel Workbooks. Before you open such workbooks, you should make sure that the macros they contain are not malicious. For this, you must ensure that you can trust the origin of this type of workbooks.

Ways of Trusting Macro Enabled Workbook

Excel provides three ways to trust a macro enabled workbook.

  • Placing the macro enabled workbooks in a trusted folder

  • Checking if a macro is digitally signed

  • Enabling security alert messages before opening macro enabled workbooks

Placing the macro enabled workbooks in a trusted folder

This is the easiest and best way to manage macro security. Excel allows you to designate a folder as a trusted location. Place all your macro-enabled workbooks in that trusted folder. You can open macro-enabled workbooks that are saved to this location without warnings or restrictions.

Checking if a macro is digitally signed

Digital signatures confirm the identity of the author. You can configure Excel to run digitally signed macros from trusted persons without warnings or restrictions. Excel will also warn the recipient if it has been changed since the author signed it.

Enabling security alert messages before opening macro enabled workbooks

When you open a workbook, Excel warns you that the workbook contains macros and asks whether you wish to enable them. You can click the Enable Content button if the source of the workbook is reliable.

Security

You can set any of these three options in the Trust Center in the Excel Options.

If you work in an organization, the system administrator might have changed the default settings to prevent anyone from changing the settings. Microsoft advises that you do not change security settings in the Trust Center as the consequences can be loss of data, data theft or security compromises on your computer or network.

However, you can learn the macro security settings in the following sections and check if they are to be changed. You have to use your own instinct to decide on any of these options based on the context and your knowledge of the file origin.

Macro Security Settings in Trust Center

The macro settings are located in the Trust Center in the Excel Options. To access the Trust Center, do the following −

  • Click the FILE tab on the Ribbon.

  • Click Options. The Excel Options dialog box appears.

  • Click Trust Center in the left pane.

  • Click the Trust Center Settings button under Microsoft Excel Trust Center.

Macro Settings

The Trust Center dialog box appears.

Trust Center

You will see various options available in the Excel Trust Center in the left pane. You will learn about the options related to Excel macros in the following sections.

Macro Settings

Macro settings are located in the Trust Center.

Macro Settings

Under Macro Settings, four options are available.

  • Disable all macros without notification − If this option is chosen, Macros and security alerts about macros are disabled.

  • Disable all macros with notification − Macros are disabled, but security alerts appear if there are macros present. You can enable macros on a case-by-case basis.

  • Disable all macros except digitally signed macros − Macros are disabled but security alerts appear if there are macros present. However, if the macro is digitally signed by a trusted publisher, the macro runs if you trust the publisher. If you have do not trust the publisher, you will be notified to enable the signed macro and trust the publisher.

  • Enable all macros (not recommended, susceptible to macro viruses) − If this option is chosen, all macros run. This setting makes your computer vulnerable to potentially malicious code.

You have an additional security option under Developer Macro Settings with a Check box.

  • Trust access to the VBA project object model.

    • This option allows programmatic access to the Visual Basic for Applications (VBA) object model from an automation client.

    • This security option is for code written to automate an Office program and manipulate the VBA environment and object model.

    • It is a per-user and per-application setting, and denies access by default, hindering unauthorized programs from building harmful self-replicating code.

    • For automation clients to access the VBA object model, the user running the code must grant access. To turn on access, select the check box.

Defining a Trusted Location

If you think that a macro-enabled workbook is from a reliable source, it is better to move the file to the trusted location identified by Excel, instead of changing the default Trust Center settings to a less-safe macro security setting.

You can find the trusted folder settings in the Trust Center.

Click the Trusted Locations in the Trust Center dialog box. The Trusted Locations set by Microsoft Office appear on the right side.

Trusted Location

You can add new locations, remove the existing locations and modify the existing locations. The identified trusted locations will be treated by Microsoft office as reliable for opening files. However, if you add or modify a location, ensure that the location is secure.

You can also find the options that office does not recommend, such as locations on internet.

Digitally Signed Macros from Reliable Sources

Microsoft provides an option to accommodate digitally signed macros. However, even if a macro is digitally signed, you need to ensure that it is from a trusted publisher.

You will find the trusted publishers in in the Trust Center.

  • Click Trusted Publishers in the Trust Center dialog box. A list of certificates appear on the right side with the details – Issued To, Issued By and Expiration Date.

  • Select a certificate and click View.

Trusted Publishers

The certificate information is displayed.

As you have learnt earlier in this chapter, you can set an option to run a macro that is digitally signed only if you trust the publisher. If you do not trust the publisher, you will be notified to enable the signed macro and trust the publisher.

Using Warning Messages

The Message Bar displays security alert when there are macros in the file that you are opening. The yellow Message Bar with a shield icon alerts you that the macros are disabled.

Warning Messages

If you know that the macro or macros are from a reliable source, you can click n the Enable Content button on the Message Bar, to enable the macros.

You can disable the Message Bar option if you do not want security alerts. On the other hand, you can enable the Message Bar option to increase security.

Enabling / Disabling Security Alerts on the Message Bar

You can enable / disable security alerts with Message Bars as follows −

  • Click the FILE tab on the Ribbon.
  • Click Options. The Excel Options dialog box appears.
  • Click Trust Center.
  • Click the Trust Center Settings button.
  • Click Message Bar.

The Message Bar Settings for all Office Applications appear.

Message Bar

There are two options under — Showing the Message Bar.

Option 1 − Show the Message Bar in all applications when active content such as macros is blocked.

  • This is the default option. The Message Bar appears when potentially unsafe content has been disabled.

  • If you had selected — Disable all macros without notification in the Macro Settings of the Trust Center, this option is not selected and the Message Bar does not appear.

Showing Message

Option 2 − Never show information about blocked content.

If this option if selected, it disables the Message Bar and no alerts appear about security issues, regardless of any security settings in the Trust Center.

Blocked

Excel Macros — Absolute References

Excel macros can be recorded either with absolute references or relative references. A macro recorded with absolute references places the recorded steps exactly in the cells where it was recorded, irrespective of the active cell. On the other hand, a macro recorded with relative references can perform the recorded tasks at different parts on the worksheet.

You will learn about absolute references for macro in this chapter. You will learn about relative references in the next chapter.

Suppose you have to submit a report about your team’s work at the end of every day in the following format −

Absolute Reference

Now, the report should be placed in the cell B2 and should be in the given format.

A sample filled in report will be as shown below −

Sample

Except for the data in the following cells, the information is constant for every report that you generate for the project.

  • C3 – Report for Date.
  • C13 – No. of Tasks Completed Today.
  • C14 – Total No. of Tasks Completed.
  • C15 – % Work Complete.

Of these also, in C3 (Report for Date) you can place the Excel function = TODAY () that places the date of your report without your intervention. Further, in cell C15, you can have the formula C14/C12 and format the cell C15 as percentage to have the % Work Complete calculated by Excel for you.

This leaves you with only two cells – C13 and C14 that need to be filled in by you every day. Hence, it would be ideal to have information for the rest of the cells, every time you have to create the report. This saves time for you and you can do the mundane activity of reporting in just few minutes.

Now, suppose you have to send such reports for three projects. You can imagine the time you can save and take up more challenging work for the day and of course get the accolades from your management.

You can achieve this by recording a macro per project and running them on a day-to-day basis to generate the required reports in a matter of just few minutes. However, every time you run the macro, the report should appear on the worksheet as given above, irrespective of the active cell. For this, you have to use absolute references.

Ensuring Absolute References

To record a macro with absolute references, you have to ensure that the macro is being recorded starting from the cell where the steps have to start. This means, in the case of the example given in the previous section, you need to do the following −

  • Start recording the macro.
  • Create a new worksheet.
  • Click in any cell other than B2 in the new worksheet.
  • Click in the cell B2.
  • Continue recording the macro.

This will create a new worksheet for every new report and get the report format placed in the cell B2 every time you run the macro.

Note − The first three steps given above are essential.

  • If you do not create a new worksheet, when you run the macro, it places whatever you recorded on the same worksheet at the same place. This is not what you want. You need to have every report on a different worksheet.

  • If you do not click in a different cell at the beginning of the recording, even if the active cell is B2, Excel places the recorded steps in the active cell. When you run the macro, it will place the recorded report format at any part of the worksheet based on the active cell. By explicitly clicking in a cell other than B2 and then the the cell B2, you are telling the recorder to always place your macro steps in the cell B2.

Recording a Macro

You can start recording the macro with the Record Macro command on the Ribbon under the VIEW tab → Macros. You can also click the Start Recording Macro button present on left side of the Excel task bar.

Recording Macro

  • Start recording the macro. The Record Macro dialog box appears.

  • Give a meaningful name to identify the macro as a report of a particular project.

  • Select This Workbook under Store macro in, as you will produce reports from this specific workbook only.

  • Give a description to your macro and click OK.

Description

Your macro starts recording.

  • Create a new worksheet. This ensures your new report will be on a new worksheet.

  • Click in any cell other than B2 in the new worksheet.

  • Click in the cell B2. This ensures that the macro places your recorded steps in B2 always.

  • Create the format for the report.

  • Fill in the static information for the project report.

  • Place = TODAY () in C3 and = C14/C12 in the cell C15.

  • Format the cells with dates.

Stop recording the macro.

Stop Record

You can stop recording the macro either with the Stop Recording command on the Ribbon under VIEW tab → Macros or by clicking the Stop Recording Macro button present on left side of the Excel task bar.

Taskbar

Your Project Report macro is ready. Save the workbook as a macro-enabled workbook (with .xlsm extension).

Running a Macro

You can generate any number of reports in a few seconds just by running the macro.

  • Click the VIEW button on the Ribbon.
  • Click Macros.
  • Select View Macros from the dropdown list. The Macro dialog box appears.
  • Click the macro Report_ProjectXYZ.
  • Click the Run button.

A new worksheet will be created in your workbook, with the report stencil created in it in the cell B2.

Excel Macros — Relative References

Relative reference macros record an offset from the active cell. Such macros will be useful if you have to repeat the steps at various places in the worksheet.

Suppose you are required to analyze the data of voters collected from 280 constituencies. For each constituency, the following details are collected −

  • Constituency name.
  • Total population in the constituency.
  • Number of voters in the constituency.
  • Number of male voters, and
  • Number of female voters.

The data is provided to you in a worksheet as given below.

Relative References

It is not possible to analyze the data in the above format. Therefore, arrange the data in a table as shown below.

Table

If you attempt to arrange the given data in the above format −

  • It takes substantial amount of time to arrange the data from the 280 constituencies

  • It can be error prone

  • It becomes a mundane task not allowing you to focus on technical things

The solution is to record a macro so that you can complete the task in not more than a few seconds. The macro needs to use relative references, as you will move down the rows while arranging the data.

Using Relative References

In order to let the macro recorder know that it has to use relative references, do the following −

  • Click the VIEW tab on the Ribbon.

  • Click Macros.

  • Click Use Relative References.

Relative Reference

Preparing the Data Format

The first step in arranging the above given data is to define the data format in a table with headers.

Create the row of headers as shown below.

Preparing

Recording a Macro

Record the macro as follows −

  • Click Record Macro.

  • Give a meaningful name, say, DataArrange to the macro.

  • Type = row ()- 3 in the cell B4. This is because the S. No. is the current row number – the 3 rows above it.

  • Cut the cells B5, B6, B7, B8 and B9 and paste it in the cells C4 to C8 respectively.

  • Now click in the cell B5. Your table looks as shown below.

Macro Recording

The first data set is arranged in the first row of the table. Delete the rows B6 – B11 and click in the cell B5.

First Data Set

You can see that the active cell is B5 and the next data set will be placed here.

Stop recording the macro. Your macro for arranging the data is ready.

Running a Macro

You need to run the macro repeatedly to complete the data arrangement in the table as given below.

The active cell is B5. Run the macro. The second data set will be arranged in the second row of the table and the active cell will be B6.

Macro Running

Run the macro again. The third data set will be arranged in the third row of the table and the active cell will become B7.

Run the Macro

Each time you run the macro, the active cell advances to the next row, facilitating the repetition of recorded steps at the appropriate positions. This is possible because of the relative references in macro.

Run the macro until all the 280 data sets are arranged into 280 rows in the table. This process takes a few seconds and as the steps are automated, the entire exercise is error free.

Excel Macros — VBA

Excel stores the macros as Excel VBA (Visual Basic for Applications) code. After recording a macro, you can view the code that is generated, modify it, copy a part of it, etc. You can even write a macro code yourself if you are comfortable with programming in VBA.

You will learn how to create a macro, by writing a VBA code, in the chapter — Creating a Macro Using VBA Editor. You will learn how to modify a macro by editing VBA code in the chapter — Editing a Macro. You will learn the Excel VBA features in this chapter.

Developer Tab on the Ribbon

You can access macro code in VBA from the Developer tab on the Ribbon.

Developer

If you do not find the Developer tab on the Ribbon, you need to add it as follows −

  • Right click on the Ribbon.

  • Select Customize the Ribbon from the dropdown list.

Customize Ribbon

The Excel Options dialog box appears.

  • Select Main Tabs from Customize the Ribbon dropdown list.

  • Check the box – Developer in the Main Tabs list and click OK. The developer tab appears.

Excel Options

Developer Commands for Macros

You need to know the commands that are for macros under the developer tab.

Click the DEVELOPER tab on the Ribbon. The following commands are available in the Code group −

  • Visual Basic
  • Macros
  • Record Macro
  • Use Relative References
  • Macro Security

Controls

The Visual Basic command is used to open the VBA Editor in Excel and the Macros command is used to view, run and delete the macros.

You have already learnt the commands other than VBA Editor in the previous chapters.

VBA Editor

VBA Editor or VBE is the developer platform for VBA in Excel.

Open the workbook – MyFirstMacro.xlsm that you saved earlier in the chapter – Creating a Simple Macro, in this tutorial.

You can open the VBE in any of the two ways −

Option 1 − Click Visual Basic in the Code group under the Developer tab on the Ribbon.

VBA Editor

Option 2 − Click Edit in the Macro dialog box that appears when you click VIEW tab → Macros → View Macros

View Macro

VBE appears in a new window.

VBE

The name of your Excel macro enabled workbook name appears with the prefix – Microsoft Visual Basic for Applications.

You will find the following in the VBE −

  • Projects Explorer.
  • Properties.
  • Module window with Code.

Projects Explorer

Project Explorer is where you find the VBA project names. Under a project, you will find Sheet names and Module names. When you click a module name, the corresponding code appears on the right side in a window.

Properties Window

The Properties are the parameters for VBA objects. When you have an object such as command button, its properties will appear in the Properties window.

Module Window with Code

The code of a macro will be stored in a module in VBA. When you select a macro and click Edit, the code of the macro appears in the corresponding module window.

Excel Macros — Understanding Codes

When you record a macro, Excel stores it as a VBA code. You can view this code in the VBA editor. You can understand the code and modify it if you have substantial knowledge of Excel VBA. You can refer to the Excel VBA tutorial in this tutorials library to obtain a grasp on the language.

However, you can still view the macro code in Excel VBA editor and match it to the steps that you recorded in macro. You will learn how to view the code and understand it for the first macro that you created in this tutorial – MyFirstMacro.

Viewing a Macro Code in VBA Editor

To view a macro code, do the following −

  • Open the workbook in which you stored the macro.
  • Click VIEW tab on the Ribbon.
  • Click Macros.
  • Select View Macros from the dropdown list.

Viewing

The Macro dialog box appears.

  • Click MyFirstMacro in the macros list.
  • Click the Edit button.

Edit

The VBA editor opens and the code of the macro MyFirstMacro appears.

Macro

Understanding the Recorded Actions as Parts of Code

You can browse through the macro code and map them to your recorded steps.

  • Start reading the code.
  • Map the code to the recorded steps.

Understanding

Scroll down the code to view more code. Alternatively, you can enlarge the code window.

Enlarge Code

Observe that the code is simple. If you learn Excel VBA, you can create the macros by writing the code in the VBA editor.

You will learn how to write a VBA code to create a macro in the chapter — Creating a Macro Using VBA Editor.

Excel Macros — Assigning Macros to Objects

Suppose you have created a macro that you need to execute several times. For example, the macros that you have created for absolute references and relative references. Then, it would be easy for you if you can run the macro using a mouse click. You can accomplish this by assigning the macro to an object such as a shape or a graphic or a control.

In this chapter, you will learn how to include an object in your workbook and assign a macro to it.

Recall the macro that you created using relative references. The macro arranges the data given in one column into a table to facilitate data analysis.

Recall

Assigning a Macro to a Shape

You can insert a shape in your worksheet that is in a meaningful form with self-explanatory text, which when clicked runs the macro assigned to it.

  • Click the INSERT tab on the Ribbon.

  • Click Shapes in the Illustrations group.

  • Select any of the ready-made shapes that appear in the dropdown list. For example, the Flowchart shape – Preparation, as you are in the process of preparing the data.

Assigning

Draw the shape and format it.

Draw Shape

  • Right click on the shape and select Edit Text from the dropdown list.

  • Type text inside the shape — Run Macro.

  • Format the text.

Edit Text

  • Right click on the shape.
  • Select Assign Macro from the dropdown list.

Assign Macro

The Assign Macro dialog box appears. Click the macro name i.e. RelativeMacro and click OK.

Macro Name

The macro is assigned to the shape.

  • Click in the cell where you have to run the macro say B4.

  • Move the cursor (pointer) onto the shape. The cursor (pointer) changes to finger.

Cursor

Now click the shape. The macro will run. Just repeat the mouse clicks to run the macro several times and you are done with the task of arranging the data into a table in a matter of a few seconds.

Assigning a Macro to a Graphic

You can insert a graphic in the worksheet and assign a macro to it. The graphic can be chosen to visualize your macro. For example, you can have a graphic of table representing that the macro will arrange the data into a table.

  • Click the INSERT tab on the Ribbon.
  • Click Pictures in the Illustrations group.
  • Select a file that contains your graphic.

Graphic

The rest of the steps are the same as those of shape given in the previous section.

Assigning a Macro to a Control

Inserting a VBA control and assigning a macro to it makes your work look professional. You can insert VBA controls from the Developer tab on the Ribbon.

  • Click the DEVELOPER tab on the Ribbon.

  • Click Insert in the Controls group.

Insert

Select the Button icon under Form Controls from the dropdown list as shown in screenshot given below −

Form Controls

  • Click the cell on the worksheet where you want to insert the Button control. The Assign Macro dialog box appears.

  • Click the macro name and click OK.

Button Control

The control button with the assigned macro will be inserted.

Control Button

  • Right click on the button.
  • Click Edit Text.
  • Type – Run Macro.
  • Format Text and resize Button.

Type Run Macro

You can run the macro any number of times by just clicking the Button repeatedly.

Using Form Controls is an easy and effective way of interacting with the user. You will learn more about this in the chapter – Interacting with the User.

Excel Macros — Running a Macro

There are several ways of executing a macro in your workbook. The macro would have been saved in your macro enabled workbook or in your Personal macro workbook that you can access from any workbook as you had learnt earlier.

You can run a macro in the following ways −

  • Running a Macro from the View Tab
  • Running a Macro by pressing Ctrl plus a shortcut key
  • Running a Macro by clicking a button on the Quick Access Toolbar
  • Running a Macro by clicking a button in a Custom Group on the Ribbon
  • Running a Macro by clicking on a Graphic Object
  • Running a Macro from Developer Tab
  • Running a Macro from VBA Editor

Running a Macro from View Tab

You have already learnt running a macro from the View tab on the Ribbon. A quick recap −

  • Click the VIEW tab on the Ribbon.
  • Click Macros.
  • Select View Macros from the dropdown list.

Active Cell

The Macro dialog box appears.

  • Click the macro name.
  • Click the Run button.

Dialog Box

Running a Macro with Shortcut Key

You can assign a shortcut key (Ctrl + key) for a macro. You can do this while recording the macro in the Create Macro dialog box. Otherwise, you can add this later in the Macro Options dialog box.

Adding a Shortcut Key While Recording a Macro

  • Click the VIEW tab.
  • Click Macros.
  • Select Record Macro from the dropdown list.

The Create Macro dialog box appears.

  • Type a macro name
  • Type a letter, say q, in the box next to Ctrl + under Shortcut key.

Adding

Adding a Shortcut Key in Macro Options

  • Click the VIEW tab.
  • Click Macros.
  • Select View Macros from the dropdown list.

The Macro dialog box appears.

  • Select the macro name.
  • Click the Options button.

Shortcut Key

The Macro Options dialog box appears. Type a letter, say q, in the box next to Ctrl + under Shortcut key. Click OK.

Type a Letter

To run the macro with the shortcut key, press the Ctrl key and the key q together. The macro will run.

Note − You can use any lowercase or uppercase letters for the shortcut key of a macro. If you use any Ctrl + letter combination that is an Excel shortcut key, you will override it. Examples include Ctrl+C, Ctrl+V, Ctrl+X, etc. Hence, use your jurisdiction while choosing the letters.

Running a Macro through Quick Access Toolbar

You can add a macro button to the Quick Access Toolbar and run the macro by clicking it. This option would be useful when you store your macros in personal macro workbook. The added button will appear on the Quick Access Toolbar in whatever workbook you open, thus making it easy for you to run the macro.

Suppose you have a macro with the name MyMacro in your personal macro workbook.

To add the macro button to the Quick Access Toolbar do the following −

  • Right click on the Quick Access Toolbar.

  • Select Customize Quick Access Toolbar from the dropdown list.

Quick Access

The Excel Options dialog box appears. Select Macros from the dropdown list under the category- Choose commands from.

Commands

A list of macros appears under Macros.

  • Click PERSONAL.XLSB!MyMacro.
  • Click the Add button.

List

The macro name appears on the right side, with a macro button image.

To change the macro button image, proceed as follows −

  • Click the macro name in the right box.
  • Click the Modify button.

Modify

The Modify Button dialog box appears. Select one symbol to set it as the icon of the button.

Icon

Modify the Display name that appears when you place the pointer on the Button image on the Quick Access Toolbar to a meaningful name, say, Run MyMacro for this example. Click OK.

MyMacro

The Macro name and the icon symbol change in the right pane. Click OK.

Symbol

The macro button appears on the Quick Access Toolbar and the macro display name appears when you place the pointer on the button.

Pointer

To run the macro, just click the macro button on the Quick Access Toolbar.

Running a Macro in Custom Group

You can add a custom group and a custom button on the Ribbon and assign your macro to the button.

  • Right click on the Ribbon.
  • Select Customize the Ribbon from the dropdown list.

Custom Group

The Excel Options dialog box appears.

  • Select Main Tabs under Customize the Ribbon.
  • Click New Tab.

Excel Option

The New Tab (Custom) appears in Main Tabs list.

  • Click New Tab (Custom).
  • Click the New Group button.

The New Group (Custom) appears under New Tab (Custom).

  • Click New Tab (Custom).
  • Click the Rename button.

Custom

The Rename dialog box appears. Type the name for your custom tab that appears in Main tabs on the Ribbon, say — My Macros and click OK.

Rename

Note − All the Main tabs on the Ribbon are in uppercase letters. You can use your discretion to use uppercase or lowercase letters. I have chosen lowercase with capitalization of words so that it stands out in the standard tabs.

The new tab name changes to My Macros (Custom).

  • Click New Group (Custom).
  • Click the Rename button.

New Group

The Rename dialog box appears. Type the group name in the Display name dialog box and click OK.

Display Name

The new group name changes to Personal Macros (custom).

Click Macros in the left pane under Choose commands from.

Commands from

  • Select your macro name, say – MyFirstMacro from the macros list.
  • Click the Add button.

Macro List

The macro will be added under the Personal Macros (Custom) group.

Personal Macros

  • Click My Macros (Custom) in the list.
  • Click the arrows to move the tab up or down.

Arrows

The position of the tab in the main tabs list determines where it will be placed on the Ribbon. Click OK.

Position

Your custom tab – My Macros appears on the Ribbon.

Click the tab — My Macros. Personal Macros group appears on the Ribbon. MyFirstMacro appears in the Personal Macros group. To run the macro, just click on MyFirstMacro in the Personal Macros group.

Click Tab

Running a Macro by Clicking an Object

You can insert an object such as a shape, a graphic or a VBA control in your worksheet and assign a macro to it. To run the macro, just click the object.

For details on running a macro using objects, refer to chapter – Assigning Macros to Objects.

Running a Macro from the Developer Tab

You can run a macro from the Developer tab.

  • Click the Developer tab on the Ribbon.
  • Click Macros.

Developer Tab

The Macro dialog box appears. Click the macro name and then click Run.

Click Run

Running a Macro from VBA Editor

You can run a macro from the VBA editor as follows −

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.

UserForm

Creating a Macro Using VBA Editor

You can create a macro by writing the code in the VBA editor. In this chapter, you will learn where and how to write the code for a macro.

VBA Objects and Modules

Before you start coding for a Macro, understand the VBA Objects and Modules.

  • Open the macro-enabled workbook with your first macro.
  • Click the DEVELOPER tab on the Ribbon.
  • Click Visual Basic in the Code group.

Objects

The VBA editor window opens.

Window Opens

You will observe the following in the Projects Explorer window −

  • Your macro enabled workbook – MyFirstMacro.xlsm appears as a VBA Project.

  • All the worksheets and the workbook appear as Microsoft Excel Objects under the project.

  • Module1 appears under Modules. Your macro code is located here.

  • Click Module1.

  • Click the View tab on the Ribbon.

  • Select Code from the dropdown list.

Code

The code of your macro appears.

Code of Macro

Creating a Macro by Coding

Next, create a second macro in the same workbook – this time by writing VBA code.

You can do this in two steps −

  • Insert a command button.

  • Write the code stating the actions to take place when you click the command button.

Inserting a Command Button

  • Create a new worksheet.

  • Click in the new worksheet.

  • Click the DEVELOPER button on the Ribbon.

  • Click Insert in the Controls group.

  • Select the button icon from Form Controls.

Inserting Command

  • Click in the worksheet where you want to place the command button.
  • The Assign Macro dialog box appears.

Button1_Click

The Visual Basic editor appears.

Visual Basic

You will observe the following −

  • A new module – Module2 is inserted in the Project Explorer.
  • Code window with title Module2 (Code) appears.
  • A sub procedure Button1_Click () is inserted in the Module2 code.

Coding the Macro

Your coding is half done by the VBA editor itself.

For example, type MsgBox “Best Wishes to You!” in the sub procedure Button1_Click (). A message box with the given string will be displayed when the command button is clicked.

Message Box

That’s it! Your macro code is ready to run. As you are aware, VBA code does not require compilation as it runs with an interpreter.

Running the Macro from VBA Editor

You can test your macro code from the VBA editor itself.

  • Click the Run tab on the Ribbon.

  • Select Run Sub/UserForm from the dropdown list. The message box with the string you typed appears in your worksheet.

Macro From VBA

You can see that the button is selected. Click OK in the message box. You will be taken back to the VBA editor.

Running the Macro from Worksheet

You can run the macro that you coded any number of times from the worksheet.

  • Click somewhere on the worksheet.
  • Click the Button. The Message box appears on the worksheet.

Macro From Worksheet

You have created a macro by writing VBA code. As you can observe, VBA coding is simple.

Excel Macros — Editing

You have learnt how to write macro code in VBA editor in the previous chapter. You can edit the macro code, rename a macro and delete a macro.

If you master Excel VBA, writing code or modifying code for a macro is a trivial task. You can edit the macro code however you want. If you want to make only few simple changes in the macro code, you can even copy macro code from one place to another.

Copying a Macro Code

You have created two macros – MyFirstMacro and Button1_Click in the macro enabled workbook MyFirstMacro.xlsm. You have created the first macro by recording the steps and the second macro by writing code. You can copy code from the first macro into the second macro.

  • Open the workbook MyFirstMacro.xlsm.

  • Click the Developer tab on the Ribbon.

  • Click Visual Basic. The Visual Basic editor opens.

  • Open the code for Module1 (MyFirstMacro macro code) and Module2 (Button1_Click () macro code).

  • Click the Window tab on the Ribbon.

  • Select Tile Horizontally from the dropdown list.

You can view the code of the two macros in the tiled windows.

Copying

  • Copy the MsgBox line in the Module2 code.

  • Paste it above that line.

  • Modify the string as −

    MsgBox “Hello World!”

  • Copy the following code from Module1.

Copy Code

Paste it in the Module2 code in between the two MsgBox lines of code.

MsgBox

  • Click the Save icon to save the code.

  • Click the Button in the Excel sheet. A Message box appears with the message — Hello World! Click OK.

Hello World

The table data appears (according to the code that you copied) and message box appears with message — Best Wishes to You!

Table Data

You can modify the code in just a few steps. This is the easiest task for a beginner.

Renaming a Macro

Suppose you want to run the edited macro from any worksheet other than the one that has the command button. You can do it irrespective of button click by renaming the macro.

  • Click the VIEW tab on the Ribbon.
  • Click Macros.
  • Select View Macros from the dropdown list.

The Macro dialog box appears.

  • Click the macro name – Button1_Click.
  • Click the Edit button.

Renaming Macro

The macro code appears in the VBA editor.

Change the name that appears in the Sub line from Button1_Click to RenamedMacro. Leave Sub and parenthesis as they are.

RenamedMacro

Open the Macro dialog box. The macro name appears as you renamed.

Open Macro

  • Click RenamedMacro.
  • Click the Run button. The macro runs. Now a button click is not necessary.

Deleting a Macro

You can delete a macro that you have recorded or coded.

  • Open the Macros dialog box.
  • Click the macro name.
  • Click the Delete button.

Deleting Macro

The Delete confirmation message appears.

Delete Confirmation

Click Yes if you are sure to delete the macro. Otherwise, click No.

Excel Macros — UserForms

At times, you might have to collect information repeatedly from others. Excel VBA provides you with an easy way of handling this task- UserForm. As any other form that you fill up, UserForm makes it simple to understand, what information is to be provided. UserForm is user friendly in the way that the controls provided are self-explanatory, accompanied by additional instructions where necessary.

Major advantage of UserForm is that you can save on time that you spend on what and how the information is to be filled.

Creating a UserForm

To create a UserForm, proceed as follows −

  • Click the DEVELOPER tab on the Ribbon.
  • Click Visual Basic. A Visual Basic window for the workbook opens.
  • Click Insert,
  • Select UserForm from the dropdown list.

Creating UserForm

The UserForm appears on the right side of the window.

UserForm Appears

Understanding the UserForm

Maximize the UserForm.xlsx – UserForm1 window.

You are in the design mode now. You can insert controls on the UserForm and write code for the respective actions. The controls are available in the ToolBox. Properties of UserForm are in the Properties window. UserForm1 (caption of the UserForm) is given under Forms in the Projects Explorer.

Understanding UserForm

  • Change the caption of the UserForm to Project Report – Daily in the properties window.
  • Change the name of the UserForm to ProjectReport.

ProjectReport

The changes are reflected in the UserForm, properties and project explorer.

Controls in the ToolBox

A UserForm will have different components. As and when you click on any of the components, either you will be provided with instructions on what and how the information is to be provided or you will be provided with options (choices) to select from. All these are provided by means of ActiveX controls in the ToolBox of the UserForm.

Excel provides two types of controls – Form controls and ActiveX controls. You need to understand the difference between these two types of controls.

Form controls

Form controls are the Excel original controls that are compatible with earlier versions of Excel, starting with Excel version 5.0. Form controls are also designed for use on XLM macro sheets.

You can run macros by using Form controls. You can assign an existing macro to a control, or write or record a new macro. When the control is clicked, the macro. You have already learnt how to insert a command button from Form controls in the worksheet to run a macro. However, these controls cannot be added to a UserForm.

ActiveX controls

ActiveX controls can be used on VBA UserForms. ActiveX controls have extensive properties that you can use to customize their appearance, behavior, fonts and other characteristics.

You have the following ActiveX controls in the UserForm ToolBox −

  • Pointer
  • Label
  • TextBox
  • ComboBox
  • ListBox
  • CheckBox
  • OptionButton
  • Frame
  • ToggleButton
  • CommandButton
  • TabStrip
  • MultiPage
  • ScrollBar
  • SpinButton
  • Image

In addition to these controls, Visual Basic provides you with MsgBox function that can be used to display messages and/or prompt the user for an action.

In the next few sections, you will understand these controls and MsgBox. Then, you will be in a position to choose which of these controls are required to design your UserForm.

Label

You can use Labels for identification purpose by displaying descriptive text, such as titles, captions and / or brief instructions.

Example

Label

TextBox

You can use a TextBox that is a rectangular box, to type, view or edit text. You can also use a TextBox as a static text field that presents read-only information.

Example

TextBox

List Box

You can use a List Box to display a list of one or more items of text from which a user can choose. Use a list box for displaying large numbers of choices that vary in number or content.

  • Insert a ListBox on the UserForm.
  • Click on the ListBox.
  • Type ProjectCodes for Name in the Properties window of the ListBox.

There are three types of List Boxes −

  • Single-selection List box − A single-selection List Box enables only one choice. In this case, a list box resembles a group of option buttons, except that a list box can handle a large number of items more efficiently.

  • Multiple selection List Box − A multiple selection List Box enables either one choice or contiguous (adjacent) choices.

  • Extended-selection List Box − An extended-selection List Box enables one choice, contiguous choices and noncontiguous (or disjointed) choices.

You can select one of these types of List Boxes, from the Properties window.

ListBox

  • Right click on the UserForm.
  • Select View Code from the dropdown list. The code window of UserForm opens.
  • Click Initialize in the top right box of the code window.
  • Type the following under Private Sub UserForm_Initialize().
ProjectCodes.List = Array ("Proj2016-1", "Proj2016-2", "Proj2016-3", "Proj20164", "Proj2016-5") 

Initialize

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.

Select Run

Next, you can write code for actions on selecting an item in the list. Otherwise, you can just display the text that is selected, which is the case for filling the Project Code in the Report.

ComboBox

You can use ComboBox that combines a text box with a list box to create a dropdown list box. A combo box is more compact than a list box but requires the user to click the down arrow to display the list of items. Use a combo box to choose only one item from the list.

  • Insert a ComboBox on the UserForm.
  • Click the ComboBox.
  • Type ProjectCodes2 for Name in the Properties window of the ComboBox.

ComboBox

  • Right click on the UserForm.
  • Select View Code from the dropdown list.
  • The code window of UserForm opens.

Type the following as shown below.

ProjectCodes2.List = Array ("Proj2016-1", "Proj2016-2", "Proj2016-3", "Proj20164", "Proj2016-5") 

Code Window

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.

Run Tab

Click the down arrow to display the list of items.

Click Down Arrow

Click on the required item, say, Project2016-5. The selected option will be displayed in the combo box.

Required Item

CheckBox

You can use check boxes to select one or more options that are displayed by clicking in the boxes. The options will have labels and you can clearly visualize what options are selected.

A check box can have two states −

  • Selected (turned on), denoted by a tick mark in the box
  • Cleared (turned off), denoted by a clear box

You can use check boxes for selection of options in a combo box to save space. In such a case, the check box can have a third state also −

  • Mixed, meaning a combination of on and off states, denoted by a black dot in the box. This will be displayed to indicate multiple selections in the combo box with check boxes.

  • Insert check boxes in the UserForm as shown below.

CheckBox

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.
  • Click in the boxes for your selected options.

Boxes

OptionButton

You can use an option button, also known as the radio button to make a single choice within a limited set of mutually exclusive choices. An option button is usually contained in a group box or a frame.

An option button is represented by a small circle. An option button can have one of the following two states −

  • Selected (turned on), denoted by a dot in the circle
  • Cleared (turned off), denoted by a blank

Frame

You can use a frame control, also referred to as a group box to group related controls into one visual unit. Typically, option buttons, check boxes or closely related contents are grouped in a frame control.

A frame control is represented by a rectangular object with an optional label.

  • Insert a frame with caption “Choice”.

  • Insert two option buttons with captions “Yes” and “No” in the frame control. The options Yes and No are mutually exclusive.

Frame

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.
  • Click on your selected option.

Selected Option

ToggleButton

You can use a toggle button to indicate a state, such as Yes or No, or a mode, such as on or off. The button alternates between an enabled and a disabled state when it is clicked.

Insert a toggle button on UserForm as shown below −

TogglebButton

  • Click the Run tab on the Ribbon.

  • Select Run Sub/UserForm from the dropdown list. The toggle button will be in enabled state by default.

Default

Click the toggle button. The toggle button will be disabled.

Toggle Button

If you click the toggle button again, it will be enabled.

CommandButton

You can use a command button to run a macro that performs some actions when the user clicks on it. You have already learnt how to use a command button on a worksheet to run a macro.

Command button is also referred to as a push button. Insert a command button on the UserForm as shown below −

CommandButton

  • Right click on the command button.
  • Type the following code in the sub Commandbutton1_click ().
ProjectCodes2.DropDown 

CommandButton1

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.

Daily Report

Click the command button. The dropdown list of combo box opens, as it is the action that you have written in the code.

Combo Box

TabStrip

You can insert a tab strip that resembles Excel tabs on the UserForm.

ScrollBar

You can use a scroll bar to scroll through a range of values by clicking on the scroll arrows or by dragging the scroll box.

Insert a scroll bar on the UserForm by drawing it at the required position and adjust the length of the scroll bar.

ScrollBar

  • Right click on the scroll bar.
  • Select View Code from the dropdown list. The Code window opens.
  • Add the following line under sub ScrollBar1_Scroll().
TextBox2.Text = "Scrolling Values" 

Scrolling Value

  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.

ScrollBar Report

Drag the scroll box. The Text – Scrolling Values will be displayed in the text box as you specified it as the action for scroll bar scroll.

Text Box

MsgBox ()

You can use the MsgBox () function to display a message when you click on something. It can be a guideline or some information or a warning or an error alert.

For example, you can display a message that values are being scrolled when you start scrolling the scroll box.

MsgBox Function

Message Box Icon Displays

You can use message-box icon displays that portray the specific message. You have the multiple message box icons to suit your purpose −

  • Type the following code under ScrollBar1_scroll.
MsgBox "Select Ok or Cancel", vbOKCancel, "OK  - Cancel Message" 
MsgBox "It's an Error!", vbCritical, "Run time result" 
MsgBox "Why this value", vbQuestion, "Run time result" 
MsgBox "Value Been for a Long Time", vbInformation, "Run time result" 
MsgBox "Oh Is it so", vbExclamation, "Run time result" 
  • Click the Run tab on the Ribbon.
  • Select Run Sub/UserForm from the dropdown list.
  • Drag the scroll box.

You will get the following message boxes successively.

Message Boxes

Designing UserForm

Now, you have an understanding of the different controls that you can use on a UserForm. Select the controls, group them if required and arrange them on the UserForm as per some meaningful sequence. Write the required actions as code corresponding to the respective controls.

Refer to the VBA tutorial in this tutorials library for an example of UserForm.

Excel Macros — Debugging a Code

You have learnt that the macro is stored as VBA code in Excel. You have also learnt that you can directly write code to create a macro in VBA editor. However, as with the case with any code, even the macro code can have defects and the macro may not run as you expected.

This requires examining the code to find the defects and correct them. The term that is used for this activity in software development is debugging.

VBA Debugging

VBA editor allows you to pause the execution of the code and perform any required debug task. Following are some of the debugging tasks that you can do.

  • Stepping Through Code
  • Using Breakpoints
  • Backing Up or Moving Forward in Code
  • Not Stepping Through Each Line of Code
  • Querying Anything While Stepping Through Code
  • Halting the Execution

These are just some of the tasks that you might perform in VBA’s debugging environment.

Stepping Through the Code

The first thing that you have to do for debugging is to step through the code while executing it. If you have an idea of which part of the code is probably producing the defect, you can jump to that line of the code. Otherwise, you can execute the code line by line, backing up or moving forward in the code.

You can step into the code either from Macro dialog box in your workbook or from the VBA editor itself.

Stepping into the code from the workbook

To step into the code from the workbook, do the following −

  • Click the VIEW tab on the Ribbon.
  • Click Macros.
  • Select View Macros from the dropdown list.

The Macro dialog box appears.

  • Click the macro name.
  • Click the Step into button.

Step into

VBA editor opens and the macro code appears in the code window. The first line in the macro code will be highlighted in yellow color.

Macro Code

Stepping into the code from the VBA editor

To step into the code from the VBA editor, do the following −

  • Click the DEVELOPER tab on the Ribbon.
  • Click Visual Basic. The VBA editor opens.
  • Click the module that contains the macro code.

The macro code appears in the code window.

Stepping

  • Click the Debug tab on the Ribbon.

  • Select Step into from the dropdown list.

Dropdown

The first line in the macro code will be highlighted. The code is in the debugging mode and the options in the Debug dropdown list will become active.

Active

Backing Up or Moving Forward in the Code

You can move forward or backward in the code by selecting Step Over or Step Out.

Not Stepping Through Each Line of Code

You can avoid stepping through each line code, if you identify a potential part of the code that needs to be discussed, by selecting Run to Cursor.

Using Breakpoints

Alternatively, you can set breakpoints at specific lines of code and execute the code, observing the results at each breakpoint. You can toggle a breakpoint and clear all breakpoints if and when required.

Using Watch

You can add a watch while debugging, to evaluate an expression and stop the execution when a variable attains a specific value. This means that you configure a watch expression, which will be monitored until it is true and then the macro will halt and leave you in break mode. VBA provides you with several watch types to select from, in order to accomplish what you are looking for.

Halting the Execution

During debugging, at any point of time, if you have found a clue on what is going wrong, you can halt the execution to decipher further.

If you are an experienced developer, the debugging terminology is familiar to you and VBA editor debugging options make your life simple. Even otherwise, it will not take much time to master this skill if you have learnt VBA and understand the code.

Excel Macros — Configuring a Macro

You can record a macro and save it with the name Auto_Open to run it whenever you open the workbook that contains this macro.

You can also write VBA code for the same purpose with the Open event of the workbook. The Open event runs the code in the sub procedure Workbook_Open () every time you open the workbook.

Recording an Auto_Open Macro

You can record an Auto_Run macro as follows −

  • Click the VIEW tab on the Ribbon.
  • Click Macros.
  • Click Record Macro. The Record Macro dialog box appears.
  • Type Auto_Run for the macro name.
  • Type a description and click OK.

Auto_open

  • Start recording the macro.
  • Stop Recording.
  • Save the workbook as macro enabled workbook.
  • Close the workbook.
  • Open the workbook. The macro Auto_Run will run automatically.

If you want Excel to start without running an Auto_Open macro, hold the SHIFT key when you start Excel.

Limitations of Auto_Open Macro

The following are the limitations of Auto_Open macro −

  • If the workbook in which you saved the Auto_Open macro contains code for workbook Open event, the code for the Open event will override the actions in the Auto_Open macro.

  • An Auto_Open macro is ignored when the workbook is opened by running code that uses the Open method.

  • An Auto_Open macro runs before any other workbooks open. Hence, if you record actions that you want Excel to perform on the default Book1 workbook or on a workbook that is loaded from the XLStart folder, the Auto_Open macro will fail when you restart Excel, because the macro runs before the default and startup workbooks open.

If you encounter any of these limitations, instead of recording an Auto_Open macro, you must write a code for the Open event as described in the next section.

VBA Code for Open Event of a Workbook

You can write code that will get executed when you open a workbook. VBA provides you with an event called open that incorporates a VBA procedure for the actions to be done on opening a workbook.

Open the workbook in which you stored the macro that you have written for the absolute references – Report_ProjectXYZ. When this macro is run, a new worksheet will be added in the workbook and the project report structure appears on the new worksheet.

You can write a macro code that will perform these actions when you open the workbook. That means when you open the Project Report workbook, a new worksheet with the report structure will be ready for you to enter the details.

Follow the below given procedure in VBA editor−

  • Double click on ThisWorkbook in Projects Explorer.

  • In the code window, select Workbook in the left dropdown list and Open in the right dropdown list. Sub Workbook_Open () appears.

Workbook_open

  • Click Modules in the Projects Explorer.

  • Double click on the module name that contains the macro code.

  • Copy the macro code from the module and paste it in the Sub WorkBook_Open ().

Sub Workbook_open

Save the macro-enabled workbook. Open it again. The macro runs and a new worksheet with the report structure is inserted.

Понравилась статья? Поделить с друзьями:
  • All about excel in selenium
  • All about excel in computer
  • All about excel graphs
  • All about excel functions
  • All about excel forms