What are vba macros in excel

What is VBA Macro in Excel?

A VBA Macro is nothing but a line of code to instruct Excel to do a specific task. Once we write the code in VBA, we can execute the same task at any time in the workbook. The macro code can eliminate repetitive, boring tasks and automate the process.

If you are new to VBA and do not know anything about it, this is the article to start your journey in Macros. So, let us start the journey of your coding class today.

VBA Visual Basic for Applications is the Microsoft programming language for Microsoft products like Excel, Word, and PowerPoint. It will do all the programming we wish to do in the VBE (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). It is the platform to write our code of tasks to execute in Excel. To start with VBA codingVBA 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 in Excel, you need to record a Macro.

Table of contents
  • What is VBA Macro in Excel?
    • Enable Developer Tab in Excel
      • Step 1: Go to File.
      • Step 2: Under File, go to Options.
      • Step 3: Select Customize Ribbon.
      • Step 4: Check the box Developer Tab to enable it.
      • Step 5: Click on OK to enable it.
    • How to Record Macros in Excel VBA?
      • Example #1
      • Example #2 –
    • How to Save Macro Workbook?
    • Things to Remember
    • Recommended Articles

VBA-Macro

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Macros (wallstreetmojo.com)

Enable Developer Tab in Excel

VBA coding is available under the Developer tab in excelEnabling 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.

If you do not see this developer tab in your Excel, follow the below steps to enable the Developer tab in Excel.

Note: We are using Excel 2016 version.

Step 1: Go to File.

Developer tab Step 1

Step 2: Under File, go to Options.

Developer tab Step 2

Step 3: Select Customize Ribbon.

You will see the Excel “Options” window from that select Customize Ribbon option.

Developer tab Step 3

Step 4: Check the box Developer Tab to enable it.

Developer tab Step 4

Step 5: Click on OK to enable it.

Now you should see the Developer tab.

Developer tab Step 5

How to Record Macros in Excel VBA?

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

Example #1

We will start straight away by recording the MacroRecording 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
. Then, under the “Developer” tab, click on Record Macro.

VBA Macro Example 1

As soon as you click on the “Record Macro,” Excel asks you to give a name to your Macro.

VBA Macro Example 1-1

Give a proper name to the Macro. It should not contain any space characters or special characters. For example, you can give underscore (_) as the word separator and then click on “OK” to start the recording.

VBA Macro Example 1-2

From now onwards, the macro recorder keeps recording all your activities in the Excel sheet.

Firstly, we will select cell A1.

VBA Macro Example 1-3

Now, we will type “Welcome to VBA” in the A1 cell.

VBA Macro Example 1-4

Now, we will stop recording under the “Developer” tab.

VBA Macro Example 1-5

So, Excel stops recording the activities we do in Excel. Now, let us see how Excel recorded the activities. Under the “Developer” tab, click on “Visual Basic.”

VBA Macro Example 1-6

As soon as you click on “Visual Basic,” we will see the below window.

VBA Macro Example 1-7

Double click on “Modules.”

VBA Macro Example 1-8

Now, we will see the code on the right-hand side.

VBA Macro Example 1-9

Macro code started with the word SUB.

All the macro has two parts: the “Head” and the “Tail” because every macro has a name.

VBA Macro Example 1-10

In between the head and tail of the macro, excel recorded all the activities.

The first thing we did after starting recording the macro was we selected cell A1, and Excel recorded it as Range (“A1”). Select.

The second activity was when we entered the value “Welcome to VBA.” When we selected it, it became an active cell, so Excel recorded the activity as ActiveCell.FormulaR1C1 = “Welcome to VBA.”

Note: R1C1 is row 1, column 1.

A third activity is after typing the word “Welcome to VBA,” we press the “Enter” key, and Excel selects the A2 cell.

Like this, the Macro recorder recorded all our activities in the Excel sheet. Now, delete the word in cell A1.

VBA Macro Example 1-11

After deleting the word, go to VBE, where our code is once again. Click on the “Run” button to enter the same text value to cell A1.

Note: The shortcut key to run the code is F5.

VBA Macro Example 1-12

So the macro is executed, and we get the same value again. Like this, we can automate our daily routine work to save time and eliminate boring daily tasks.

Example #2 –

Now, let us record one more macro to understand better. In this recording, we will insert serial numbers from A1 to A10.

Go to the “Developer” tab and click on the “Record Macro” option, as shown in the above example.

Record Example 2

Click on “OK” to start the recording. First, we will enter 1, 2, 3, and then drag the fill handleThe fill handle in Excel allows you to avoid copying and pasting each value into cells and instead use patterns to fill out the information. This tiny cross is a versatile tool in the Excel suite that can be used for data entry, data transformation, and many other applications.read more to insert serial numbers.

Using “Fill Handle,” we will insert serial numbers.

Example 2-1

Now, click on “Stop Recording.”

VBA Macro Example 2-2

Go to “Visual Basic Editor” and see what the code is.

Example 2-3

Let us look at the code now. Firstly, we have selected cell A1.

Code:

Range (“A1”).Select

Secondly, we have inserted 1 into the active cell.

Code:

ActiveCell.FormulaR1C1 = "1"

The third activity was when we selected cell A2.

Code:

Range (“A2”).Select

The fourth activity was we inserted 2 into the active cell.

Code:

ActiveCell.FormulaR1C1 = "2"

The fifth activity was when we selected cell A3.

Code:

Range (“A3”).Select

In the sixth activity we inserted 3 into the active cell.

Code:

ActiveCell.FormulaR1C1 = "3"

Then, we selected the range of cells from A1 to A3.

Code:

Range ("A1:A3").Select

After selecting the cells, we filled the serial numbers using the fill handle.

Code:

Selection.AutoFill Destination:=Range("A1:A10"), Type:=xlFillDefault

So finally, we have selected the range A1 to A10.

Code:

Range ("A1:A10").Select

So, you can run this code whenever we want to insert serial numbers from 1 to 10 in cells A1 to A10.

How to Save a Macro Workbook?

One must save the Excel workbook containing macro code as “Macro-Enabled Workbook.” Then, click “Save As” and select the file’s extensionExcel extensions represent the file format. It helps the user to save different types of excel files in various formats. For instance, .xlsx is used for simple data, and XLSM is used to store the VBA code.read more as “Macro-Enabled Workbook.”

VBA Macro Example 2-4

Things to Remember

  • It is just the introduction part of the VBA Macro tutorial. Keep following our blog to see more posts in the future.
  • Recording macro is the best initialization to start the journey of macros.
  • Record more and more activities and see what the code is.

Recommended Articles

This article has been a guide to VBA Macro. Here, we learn how to record a macro in Excel to show automatically generated code in the VBA Editor, along with step-by-step examples. Below are some useful Excel articles related to VBA: –

  • VBA Delete Sheet
  • Goal Seek in Excel VBA
  • VBA Operators

How to set up macros in VBA

What are VBA Macros in Excel?

VBA Macros use the Visual Basic Application in Excel to create custom user-generated functions and speed up manual tasks by creating automated processes.  Additionally, VBA can be used to access the Windows Application Programming Interface (API).  One of its main uses is to change and customize the user interface by creating personalized toolbars, menus, dialog boxes, and forms.

To learn more, launch CFI’s Excel VBA course now!

VBA Macro course

Before you continue, use the form below to get access to our comprehensive VBA cheat sheet for an overview of key codes and macros, terminology, and best practices in Excel VBA.

How to Create Excel VBA Macros

In a separate article, CFI discusses what VBA is and how to access the VBA Editor. As a summary, pressing Alt + F11 in Excel opens up the VBA window and allows the user to begin coding macros.

To start coding, the user will have to create a Module file. Module files contain a group of macros. To create a new module, press Insert > Module. Optionally, the user can name this module using the properties window in the bottom left corner of the editor. Simply type in a new module name and press enter.

How to Name Excel VBA Macros

To start off, the macro must be given a unique name. This name cannot match other macros, and it usually cannot match the name of other properties, functions, and tools within Excel. The macro name is what the user will use to call the macro into action.

To define a macro name, the user must type Sub name() and press “enter” in the coding window of the editor. Pressing enter will automatically fill the window with the general format of an Excel macro. For example, to name the macro “CFI Macro”, a user should type “Sub cfiMacro()” and press enter. The VBA Editor will automatically add an “End Sub” line a few lines below the “Sub”.

VBA Macros sub procedure

Note: The general convention for typing names for any macro, function, or variable in VBA is to use lower case if there is only one word, and to use an uppercase letter at the start of every new word. VBA names generally cannot contain spaces. Since CFI Macro is two words, this should be written as cfiMacro. However, these are just best practice guidelines and need not necessarily be adhered to.

Sub Name in VBA

The Sub Name() line tells the editor the start of the macro code. The End Sub denotes the end. If the user wanted to, he or she could create a second new macro by starting a new Sub Name() line below the first End Sub. Try this out and you should notice that Excel will automatically create a line between the two different macros.

VBA Macro sub name

This is the basic structure of an Excel macro. The next step, before jumping into the actual process coding, is to define the variables the user is going to use in the code. You may be interested in our fully-fledged Excel VBA macro course. Click here to launch the course now!

Additional Resources

Thank you for reading the CFI introductory guide to VBA macros in Excel. To keep learning and advancing your career, check out these additional CFI resources:

  • Excel Shortcuts (PC and Mac)
  • Advanced Excel Formulas
  • List of Excel Functions
  • Free Excel Course
  • See all Excel resources

Excel Macro is a record and playback tool that simply records your Excel steps and the macro will play it back as many times as you want. VBA Macros save time as they automate repetitive tasks. It is a piece of programming code that runs in an Excel environment but you don’t need to be a coder to program macros. Though, you need basic knowledge of VBA to make advanced modifications in the macro.

In this Macros in Excel for beginners tutorial, you will learn Excel macro basics:

  • What is an Excel Macro?
  • Why are Excel Macros Used in Excel?
  • What is VBA in a Layman’s Language?
  • Excel Macro Basics
  • Step by Step Example of Recording Macros in Excel

Why are Excel Macros Used in Excel?

As humans, we are creatures of habit. There are certain things that we do on a daily basis, every working day. Wouldn’t it be better if there were some magical way of pressing a single button and all of our routine tasks are done? I can hear you say yes. Macro in Excel helps you to achieve that. In a layman’s language, a macro is defined as a recording of your routine steps in Excel that you can replay using a single button.

For example, you are working as a cashier for a water utility company. Some of the customers pay through the bank and at the end of the day, you are required to download the data from the bank and format it in a manner that meets your business requirements.

You can import the data into Excel and format. The following day you will be required to perform the same ritual. It will soon become boring and tedious. Macros solve such problems by automating such routine tasks. You can use a macro to record the steps of

  • Importing the data
  • Formatting it to meet your business reporting requirements.

What is VBA in a Layman’s Language?

VBA is the acronym for Visual Basic for Applications. It is a programming language that Excel uses to record your steps as you perform routine tasks. You do not need to be a programmer or a very technical person to enjoy the benefits of macros in Excel. Excel has features that automatically generated the source code for you. Read the article on VBA for more details.

Excel Macro Basics

Macros are one of the developer features. By default, the tab for developers is not displayed in Excel. You will need to display it via customize report

Excel Macros can be used to compromise your system by attackers. By default, they are disabled in Excel. If you need to run macros, you will need to enable running macros and only run macros that you know come from a trusted source

If you want to save Excel macros, then you must save your workbook in a macro-enabled format *.xlsm

The macro name should not contain any spaces.

Always fill in the description of the macro when creating one. This will help you and others to understand what the macro is doing.

Step by Step Example of Recording Macros in Excel

Now in this Excel macros tutorial, we will learn how to create a macro in Excel:

We will work with the scenario described in the importance of macros Excel. For this Excel macro tutorial, we will work with the following CSV file to write macros in Excel.

Introduction to Macros in Excel

You can download the above file here

Download the above CSV File & Macros

We will create a macro enabled template that will import the above data and format it to meet our business reporting requirements.

Enable Developer Option

To execute VBA program, you have to have access to developer option in Excel. Enable the developer option as shown in the below Excel macro example and pin it into your main ribbon in Excel.

Step 1)Go to main menu “FILE”

Select option “Options.”

How to Write Macros in Excel

What is VBA?

Step 2) Now another window will open, in that window do following things

  • Click on Customize Ribbon
  • Mark the checker box for Developer option
  • Click on OK button

How to Write Macros in Excel

Step 3) Developer Tab

You will now be able to see the DEVELOPER tab in the ribbon

How to Write Macros in Excel

Step 4) Download CSV

First, we will see how we can create a command button on the spreadsheet and execute the program.

  • Create a folder in drive C named Bank Receipts
  • Paste the receipts.csv file that you downloaded

How to Write Macros in Excel

Step 5) Record Macro

  1. Click on the DEVELOPER tab
  2. Click on Record Macro as shown in the image below

How to Write Macros in Excel

You will get the following dialogue window

Introduction to Macros in Excel

  1. Enter ImportBankReceipts as the macro name.
  2. Step two will be there by default
  3. Enter the description as shown in the above diagram
  4. Click on “OK” tab

Step 6) Perform Macro Operations/Steps you want to record

  • Put the cursor in cell A1
  • Click on the DATA tab
  • Click on From Text button on the Get External data ribbon bar

You will get the following dialogue window

How to Write Macros in Excel

  1. Go to the local drive where you have stored the CSV file
  2. Select the CSV file
  3. Click on Import button

You will get the following wizard

Introduction to Macros in Excel

Click on Next button after following the above steps

Introduction to Macros in Excel

Follow the above steps and click on next button

Introduction to Macros in Excel

  • Click on Finish button
  • Your workbook should now look as follows

Introduction to Macros in Excel

Step 7) Format the Data

Make the columns bold, add the grand total and use the SUM function to get the total amount.

How to Write Macros in Excel

Step 8) Stop Recording Macro

Now that we have finished our routine work, we can click on stop recording macro button as shown in the image below

How to Write Macros in Excel

Step 9) Replay the Macro

Before we save our work book, we will need to delete the imported data. We will do this to create a template that we will be copying every time we have new receipts and want to run the ImportBankReceipts macro.

  • Highlight all the imported data
  • Right click on the highlighted data
  • Click on Delete
  • Click on save as button
  • Save the workbook in a macro enabled format as shown below

How to Write Macros in Excel

  • Make a copy of the newly saved template
  • Open it
  • Click on DEVELOPER tab
  • Click on Macros button

You will get the following dialogue window

Introduction to Macros in Excel

  1. Select ImportBankReceipts
  2. Highlights the description of your macro
  3. Click on Run button

You will get the following data

Introduction to Macros in Excel

Congratulations, you just created your first macro in Excel.

Summary

Macros simplify our work lives by automating most of the routine works that we do. Macros Excel are powered by Visual Basic for Applications.

If you’ve ever used macros in Excel, you’ve used Visual Basic for Applications (VBA).  VBA is human-readable (and editable) programming code that gets generated when you record a macro.  When you run a macro it’s this code that Excel reads to replay your actions.

The following is a series of frequently asked questions about VBA, with answers for both newcomers to Excel macros and seasoned programmers.

What is VBA used for in Excel?

VBA is used to write macros, which automate simple and complex tasks in Excel.

Users of Microsoft Excel will often find themselves repeating the same series of tasks over and over again.  Sometimes these are minor tasks like copy-pasting subsets of data to different sheets, and sometimes the tasks are more complex like uploading data to a website.  With VBA, macros can be programmed to automate tasks like these, turning a series of manual operations into a single button click.

How do I start with VBA in Excel?

The easiest way to get started with macros is to record them using the Macro Recorder built into Excel.  The macro recorder generates VBA code which you can read and edit, giving you a stepping-stone to learn how to code your own macros from scratch.

For more information, see the article “How to Record a Macro”.

How can I access VBA code?

The VBA editor can be opened at any time by pressing the ALT+F11 keyboard shortcut.  From here, you can access the code for all open workbooks.

You can double-click any workbook, sheet, or module object in the Project window to show the VBA code contained in it.  Recorded macros will always appear in modules, which is where you’ll typically want to write your own macros too.

For more information about editing macros, see the article “Editing Excel VBA Macros“.

What can VBA do?

First of all: if there’s something you can do in Excel, you can write VBA code to do the same thing.  If you learn the commands (using the macro recorder or online resources), you can string together several actions together in a single macro.

Second: you can use VBA to write user-defined functions for use in worksheet formulas – much like the “=SUM()” function, for example.  Although Excel already packs a large variety of functions, if you find yourself wanting a function that’s more specific to your industry or workplace, you can add it with VBA.

Third: you can use VBA to add logic (If statements) and loops (repeat actions) to your macros.  This means that a macro can be more than a recording of actions – it can be a real program with smart repetition and decision-making.

An example of a loop

Fourth: VBA allows you to build user interfaces, giving users an easier way to interact with your macros.  These interfaces can be simple buttons on a worksheet, or complex UserForms with rich controls like TreeViews and FlexGrids.

(See the article “Add a Button and Assign a Macro in Excel” as a starting point.)

Fifth but not finally: VBA allows you to harness almost any resource your computer or the internet by using external DLL libraries.  You can automate a lot more than Excel this way, like accessing web services and databases, parsing XML files, interoperating with other Microsoft Office applications, and much, much more.

Are VB and VBA the same?

The VBA language is identical to Visual Basic 6.0.  If you have experience writing VB6 code, you can write VBA.

The VB Editor in Excel is a stripped-down version of the VB6 editor, with similar debugging capabilities and components like the ‘Project’ and ‘Properties’ windows.  The Form editor is also very similar, although it has some limitations (like the inability to create control arrays).

Less similar to VBA is Visual Basic .NET.  Although these languages share many of the same keywords and syntaxes, the code between these languages is less interoperable.  You wouldn’t have to re-write much (if anything) to port a procedure from VB6 to VBA, but you couldn’t do the same from VB.NET.

What is the difference between a macro and VBA?

VBA is just the language that macros are written with.  If your macro is a story, VBA is the grammar and dictionary it’s written with.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

What is the difference between a macro and a script?

Scripts use a limited subset of the Visual Basic language and are used for different purposes.

Macros are stored inside Excel workbook files and can only be run from inside Excel.  They’re typically used to automate various Excel functions and add extra functionality to workbooks.

Scripts are stored in text files using the .VBS extension and can be run from inside Windows or executed by other programs.  Sysadmins will use scripts to automate certain administrative tasks on a computer or network.

What does a VBA Developer do?

Often, people who create macros aren’t developers – they’re analysts, traders, accountants, or scientists, who have had training in programming and use VBA on more of an ad-hoc basis.

People who focus on VBA development tend to create more refined tools – they create Add-ins, user interfaces with Forms, interactive dashboards, report generators, and more.

Why is VBA important?

VBA is included as standard in all Microsoft Office applications, including Excel.  Excel is one of the most popular programs in the world and finds use in a wide variety of fields and workplaces, all with their own unique workflows and use-cases.

By not using automation, countless work-hours are wasted every week performing boring, repetitive tasks at a human speed.  Automation with VBA can perform the same tasks at the computer’s lightning-quick pace, letting users focus on the important aspects of their work, being more productive – and maybe getting out of the office a little earlier!

VBA Programming | Code Generator does work for you!

Is VBA a good programming language?

VBA has the typical programming elements like variables, arrays, functions, decisions and loops.  It has a syntax that’s easy to read, and can harness a lot of power from Windows and other services.

On the downside, error-handling isn’t very elegant in VBA.  While other languages use “try-catch-finally” code blocks, VBA uses “On Error” statements to modify how macros behave when an error occurs.

Additionally, VBA can’t be used to create standalone programs, web sites or services, and it can’t interface with newer programming APIs like the .NET platform.

Is VBA object-oriented?

VBA has some limited support for some object-oriented concepts:

  • Encapsulation: VBA supports data hiding using classes
  • Polymorphism: the Implements keyword allows programmers to use other classes as interfaces

In the strict sense though, VBA is not object-oriented.  It notably lacks the concept of inheritance, which severely limits the ability to extend the functionality of existing types.

You work in Excel every day and do the same things again and again. Why not automate those tasks? Or, maybe, you want Excel to do most of the work for you? Read on to learn what Excel macros are and how they can help you.

What are macros in Excel?

Excel is an extremely powerful tool for processing data in the form of spreadsheets. While most users use formulas, there is another way to manipulate data in Excel.

Excel macros are pieces of code that describe specific actions or contain a set of instructions. Every time you launch the macro, Excel follows those instructions step-by-step.

Why learn macros in Excel?

Macros are a must-have tool for an advanced Excel user. By using Excel macros you can avoid dull, repetitive actions or even create your own order management system for free.

Simple macros in Excel that will make things easier

There are lots of simple Excel macros that take just a few lines of code, but can save you hours. Excel can perform certain operations instantly, where it would take you a very long time to do the job manually.

For example, this macro will sort all worksheets alphabetically:

Sub SortSheetsTabName()
Application.ScreenUpdating = False
Dim ShCount As Integer, i As Integer, j As Integer
ShCount = Sheets.Count
For i = 1 To ShCount - 1
For j = i + 1 To ShCount
If Sheets(j).Name < Sheets(i).Name Then
Sheets(j).Move before:=Sheets(i)
End If
Next j
Next i
Application.ScreenUpdating = True
End Sub

The following code will unhide all hidden worksheets:

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

To unhide all rows and columns on a worksheet, use:

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

Advanced Excel macros that can significantly improve your workflow

If you are running a business, you have to store and manipulate data. Small companies can keep records by hand and large enterprises can buy specialized software (which is rather expensive). But what about medium-sized businesses that can no longer settle for manual record-keeping, but still cannot afford costly software? This is where Excel with macros shines.

By combining advanced Excel macros you can create a CRM (Customer Relationship Management) system which will help you provide better services. If you sell goods, you need an inventory management tool and Excel spreadsheets enhanced with macros will fit your needs.

If your data is contained in multiple Excel workbooks, you can use Coupler.io to move them around. You can even add third-party sources, like  Google Sheets, Airtable, BigQuery, etc. Data integration with Coupler.io does not require any programming skills and can be done in just a few clicks.

1 excel integrations coupler

Check out the available integrations with Excel.

Other Excel macros examples

Below are a few examples of useful Excel macros.

Sometimes you might accidentally add extra spaces to the data in cells. This mistake will cause errors, thereby preventing you from making correct calculations. To remove unnecessary spaces from the selected cells, use the following code:

Sub TrimTheSpaces()
Dim MyRange As Range
Dim MyCell As Range
Set MyRange = Selection
For Each MyCell In MyRange
If Not IsEmpty(MyCell) Then
MyCell = Trim(MyCell)
End If
Next MyCell
End Sub

It is often the case that you need to protect your workbook with a password. You can do that in the user interface of Excel. However, if you use the same password for all of your workbooks, you have to re-enter it every time. This macro will do the job for you (don’t forget to replace “1234” with your own password!):

Sub ProtectSheets()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Protect Password:="1234"
Next ws
End Sub

Using macros in Excel

As macros are programs that can do literally anything on your computer, using macros from untrusted sources is very risky. That’s why, when you open a workbook with macros in Excel, they will be disabled and you will see the following notification:

1 macros security warning

If you trust the source of the file, click Enable Content. That will add the workbook to the list of trusted documents and turn on its macros. The next time you open that workbook, there will be no warning.

You will see the above notification each time you open a workbook if it has been saved to an untrusted location. That can be a folder for temporary files or browser downloads. To avoid that, move the file to another folder or enable macros in the Excel Trust Center.

How to enable macros in Excel

If you do not want to see the security warning when opening Excel workbooks, you can permanently enable macros in the Trust Center.

To enable macros in the Excel Trust Center:

  1. In the upper-left corner, click the File tab and then select Options:

2 Excel options selection

  1. In the Excel Options window, select Trust Center and then click Trust Center Settings:

3 excel trust center selection

  1. In the Trust Center, go to Macro Settings and then select Enable all macros:

4 enable macros

Warning! Enabling macros for all workbooks is potentially risky because files from external sources may contain malicious code. If you open such a workbook, the macros may run automatically and corrupt your data or even cause hardware malfunctions.

How to use macros in Excel

If your workbook contains macros, you can run them by pressing Alt+F8. In the Macro window that opens, select the macro you need and click Run:

5 select the macro you need and click Run

If you want to create new macros, you need to enable the Developer tab first.

To enable the Developer tab:

  1. In the upper-left corner, click the File tab and then select Options.
  2. In the Excel Options window, select Customize Ribbon and then enable the Developer checkbox in the Main Tabs area:

6 enable developer tab

  1. Click OK to apply the changes.

In the Developer tab you can run existing macros by clicking the Macros button or create a new macro. For details on creating macros in Excel, see the following sections.

7 developer tab

How to delete macros in Excel

To delete a macro in Excel:

  1. Open the Macro window in one of the following ways:
    • Press Alt+F8.
    • Select the Developer tab and click Macros.
  2. Select the macro that you want to delete and click Delete.

8 delete macro

  1. Click Yes in the confirmation window that opens.

How to disable macros in Excel

Enabling Excel macros can make your computer vulnerable. Some macros will run when you open a workbook, which is especially dangerous if you have downloaded the workbook from an untrusted source. To prevent that, you can disable macros in Excel either with or without a notification.

To disable macros in Excel:

  1. In the upper-left corner, click the File tab and then select Options.
  2. In the Excel Options window, select Trust Center and then click Trust Center Settings.
  3. In the Trust Center, go to Macro Settings and then select one of the following options:
    • Disable all macros without notification. Macros will be disabled and you will not see a security warning when opening a workbook with macros.
    • Disable all macros with notification. Macros will be disabled but you will see a security warning when opening a workbook with macros and will be able to allow macros, if needed.

9 disable macros

Writing macros in Excel

In Excel you can not only run ready-to-use macros, but also write your own macros to automate your daily tasks. We will provide a few methods below for creating macros in Excel. Anyone can write macros in Excel: from a complete beginner to an advanced user with programming skills.

How to record a macro in Excel

If you are unfamiliar with programming languages, the easiest way to create your own Excel macro is to record it.

To record a macro in Excel:

  1. In the Developer tab, click Record Macro:

10 record macro

  1. Enter the macro name and click OK:

11 enter macro name

Excel will start recording the macro.

  1. Perform the actions, that need to be included in the macro, then click Stop Recording:

12 stop macro record

The macro will be saved to the workbook.

Creating VBA macros in Excel

If you can write code in any programming language, you can easily learn the basics of Visual Basic for Applications and create Excel macros in the VBA editor.

To open the editor, click Visual Basic in the Developer tab.

Each workbook is a VBA project in the editor. The project contains worksheets as objects and modules with macros:

13 VBA project

By default, macros recorded in the Developer tab are saved to Module1. For example, here is the macro that we recorded in the previous section:

14 sample macro

As you can see in the picture above, a macro starts with Sub followed by the macro name and (). You can insert the macro description in the comment lines. Be sure to indent the macro body for better readability. The End Sub string designates the end of the macro.

Excel macros language

Macros in Excel are written in VBA (Visual Basic for Applications). This programming language is used not only in Excel, but also in other MS office applications.

VBA provides many of the tools that are available in advanced programming languages. For example, to create Excel macros, you can use the following:

  • Variables
  • ‘If’ statements
  • ‘For’ cycles
  • Loops
  • Arrays
  • Events
  • Functions

Being an object-oriented language, VBA lets you manipulate the following objects:

  • Application object
  • Workbook object
  • Worksheet object
  • Range object

If you decide to turn your Excel worksheet into something much more powerful, like a CRM system, you can even create a graphical user interface with message boxes and user forms. To learn more about VBA, check out the official documentation.

Editing macros in Excel VBA editor

When creating macros in Excel, it may be difficult to get the desired result on the first try. By editing Excel macros and running them again, you can resolve errors and make your system work as expected.

To edit a macro in Excel VBA editor:

  1. In the Developer tab, click Visual Basic:

15 open VBA editor

  1. In the VBA project tree, double-click the module with the macro that you want to edit:

16 select module

  1. Edit the macro code, then save changes by clicking the Save button or pressing Ctrl+S.

The workbook with the macro will be saved.

You can press F5 or click Run in the editor to launch the macro:

17 run macro from editor

Note: If a macro changes workbook data, those changes cannot be reversed using the Undo command in Excel.

The VBA editor has a built-in debugger that highlights errors in code. The line that follows the error is highlighted:

18 VBA debugger

An easy way of learning how to create macros in Excel

In Excel you can record a macro by using the Record Macro button in the Developer tab. Then you can open the recorded macro in Excel VBA editor.

This is the easiest way to learn the VBA programming language. Just perform actions in the Excel user interface and see how they are interpreted in the macro code. Then you can change values and methods in the code to see how that affects the macro behavior.

Do I need Excel macros?

As you can see, macros can drastically enhance Excel features in many ways. By using macros, you can automate your daily operations and save yourself hours of time. Excel macros can even save you money if you decide to create an Excel-based order management system instead of buying costly software.

When you finish customizing your Excel workbook with macros, you may need to migrate your data from other sources, like Google Sheets or BigQuery.

  • Zakhar Yung

    A content manager at Coupler.io whose key responsibility is to ensure that the readers love our content on the blog. With 5 years of experience as a wordsmith in SaaS, I know how to make texts resonate with readers’ queries✍🏼

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Понравилась статья? Поделить с друзьями:
  • What are two word processing softwares
  • What are two word phrases
  • What are track changes in word
  • What are three letter word
  • What are three differences between dtp software and word processors