What is excel vba training

Excel VBA Tutorial – How to Write Code in a Spreadsheet Using Visual Basic

Introduction

This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).

Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said  «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.

  • In 1996, there were over 30 million users of Microsoft Excel (source).
  • Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.

We’re one big happy family!

In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.

Prerequisites

You don’t need any prior programming experience to understand this tutorial. However, you will need:

  • Basic to intermediate familiarity with Microsoft Excel
  • If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
  • A willingness to try new things

Learning Objectives

Over the course of this article, you will learn:

  1. What VBA is
  2. Why you would use VBA
  3. How to get set up in Excel to write VBA
  4. How to solve some real-world problems with VBA

Important Concepts

Here are some important concepts that you should be familiar with to fully understand this tutorial.

Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.

If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!

Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:

  • Subroutines: a group of VBA statements that performs one or more actions
  • Functions: a group of VBA statements that performs one or more actions and returns one or more values

Note: you can have functions operating inside of subroutines. You’ll see later.

Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.

Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.

For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.

What is VBA?

Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.

Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.

But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.

Pizza in a pizza oven

Yum.

Why use VBA in Excel?

Because wood-fired pizza is the best!

But seriously.

A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?

Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.

You should consider using VBA if you need to:

  • Automate repetitive tasks
  • Create easy ways for users to interact with your spreadsheets
  • Manipulate large amounts of data

Getting Set Up to Write VBA in Excel

Developer Tab

To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.

VBA developer tab

To add the Developer tab to the ribbon:

  1. On the File tab, go to Options > Customize Ribbon.
  2. Under Customize the Ribbon and under Main Tabs, select the Developer check box.

After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.

VBA Editor

Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.

VBA editor

Excel VBA Examples

First, let’s create a file for us to play around in.

  1. Open a new Excel file
  2. Save it as a macro-enabled workbook (. xlsm)
  3. Select the Developer tab
  4. Open the VBA Editor

Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.

Example #1: Display a Message when Users Open the Excel Workbook

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub

Save, close the workbook, and reopen the workbook. This dialog should display.

Welcome to XYZ notebook message example

Ta da!

How is it doing that?

Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:

  • Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
  • Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
  • By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
  • msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”

In short, this is a simple subroutine that contains a function.

When could I use this?

Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.

  • Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
  • Solution: create a user message that contains a concise answer to each of these frequently answered questions.

Real World Examples

  • Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
  • Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
  • Use the InputBox function to get information from the user

Example #2: Allow User to Execute another Procedure

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub

Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub

Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.

Now click the button. This message should display:

Process the XYZ report message example

Click “yes” or hit Enter.

Thanks for processing the XYZ report message example

Once again, tada!

Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first…

How is it doing that?

This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:

  • Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
  • Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
  • UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
  • Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
  • If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.

When could I use this?

This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.

For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.

  • Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
  • Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.

Real World Examples

  • Create a dialog box for user to automatically populate certain information across multiple sheets
  • Use the InputBox function to get information from the user, which is then populated across multiple sheets

Example #3: Add Numbers to a Range with a For-Next Loop

For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”

In the VBA Editor, select Insert -> New Module

Write this code in the Module window (don’t paste!):

Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub

Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.

This should happen:

For-Next loop results

Etc, until the 100th row.

How is it doing that?

  • Dim X As Integer: declares the variable X as a data type of Integer.
  • For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
  • Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
  • Next X: this tells the loop to run again

When could I use this?

The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.

Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.

You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.

Real World Examples

  • Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
  • Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
  • Loop through each character in a string and extract all numbers
  • Randomly select a number of values from an array

Conclusion

Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.

  • What is VBA?
  • How do I get set up to start using VBA in Excel?
  • Why and when would you use VBA?
  • What are some problems I could solve with VBA?

If you have a fair idea of how to you could answer these questions, then this was successful.

Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.

Happy coding!

Learning Resources

  • Excel VBA Programming for Dummies, John Walkenbach
  • Get Started with VBA, Microsoft Documentation
  • Learning VBA in Excel, Lynda

A bit about me

I’m Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I’m continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started


This Excel VBA tutorial for beginners covers in-depth lessons to learn VBA Excel and VBA basics. This Visual Basic for Applications Excel Tutorial covers all the basics as well as advanced concepts of VBA for beginners.

What is VBA?

VBA stands for Visual Basic for Applications. It is a combination of the Microsoft’s event-driven programming language Visual Basic with Microsoft Office Applications such as Microsoft Excel. VBA enables you to automate various activities in Excel like generating reports, preparing charts & graphs, doing calculations, etc. This automation activity is also often referred as Macro. This way it helps users to save their time spent behind running the repetitive steps.

Excel VBA Syllabus

Introduction

Advanced Stuff

👉 Lesson 1 VBA Controls — VBA Form Control & ActiveX Controls in Excel
👉 Lesson 2 VBA Arithmetic Operators — Multiplication, Division & Addition
👉 Lesson 3 VBA String Functions — VBA String Operators & Manipulation Functions
👉 Lesson 4 VBA Comparison Operators — Not equal, Less than or Equal to
👉 Lesson 5 VBA Logical Operators — AND, OR, NOT, IF NOT in Excel VBA
👉 Lesson 6 Excel VBA Subroutine — How to Call Sub in VBA with Example
👉 Lesson 7 Excel VBA Function Tutorial — Return, Call, Examples
👉 Lesson 8 Excel VBA Range Object — What is, How to Use
👉 Lesson 9 Web Scraping with VBA — Learn Web Scraping from basics

Must Know!

Why learn Excel VBA?

Excel VBA enables you to use English like statements to write instructions for creating various applications. Excel VBA is easy to learn, and it has easy to use User Interface in which you just have to drag and drop the interface controls. It also allows you to enhance Excel functionality by making it behave the way you want.

What is VBA used for?

VBA is used for both personal use as well as business uses. You can automate your daily routine tasks using simple VBA macros for personal use. For business use, you can create strong programs and leverage the power of Excel in your custom programs using VBA.

Prerequisites for learning VBA Excel Tutorial?

Nothing! This Excel VBA training assumes you as an absolute beginner to VBA. However, it is desirable if you know the basics of Excel and how the functions in Excel work, it will boost your learning speed and understanding.

What will you learn in this Excel VBA tutorial?

In this Excel VBA tutorial, you will learn all the basics of VBA like introduction to Macros, VBA data types, variables, arrays, etc. You will also learn the advanced concepts of Excel VBA like VBA Excel form control, ActiveX control, VBA operators, subroutines, functions, objects, web scraping with VBA and many more interesting topics.

This VBA tutorial will teach you the basics of using VBA with Excel. No prior coding experience? No problem! Because VBA is integrated into Excel, coding is very intuitive. Beginners can learn VBA very quickly!

The tutorial is 100% free. No sign-up is required, but by creating an account you’ll be able to save your tutorial progress, and receive many other VBA resources for free!

VBA for Excel

The tutorial contains 100 exercises spread across 10 chapters. The course is meant to replicate a «boot camp» experience where you learn very quickly by immediately completing exercises related to the course topics.

Each exericse has a «Hint» button, showing you the correct answer. So if you’re stuck, you can easily see the correct answer.

The course contents are listed below:

Excel VBA Tutorial about essential terms to learnSo you’ve created your first (or your first few) Excel macro(s), perhaps by following these 7 easy steps to create a macro. By now, your colleagues are already looking at you like you’re a wizard.

That is a great sign that you’re on a good way to learning macros and Visual Basic for Applications (VBA).

However…

Being able to create a basic macro in Excel is only the beginning in the process to become a really efficient and productive user of macros and VBA. If you really want to unleash the power of these tools, you must learn VBA due to the fact that, among others, recording a macro sometimes simply doesn’t “cut it”.

The bad news (at least for some of you) is that using VBA requires that you learn programming.

The good news is that programming in Excel is not as difficult as it may sound at first.

If this doesn’t sound that convincing, wait…

In order to help you during the process of learning Visual Basic for Applications, I have created this Excel VBA tutorial for beginners where I explain, in detail, 16 (actually you’ll probably learn even more) essential terms you need to know in order to learn VBA programming. In particular, I focus on the basic terms that you will constantly find during the process of becoming a VBA expert.

By the time you’re done reading this beginners guide, you will understand the basics of at least 16 essential terms you need to know to learn Visual Basic for Applications. The following is the outline for this Excel tutorial:

This Excel VBA Tutorial for Beginners is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by clicking the button below.

Get immediate free access to the Excel VBA Tutorial for Beginners workbook examples

If some (or all) of the terms above sound completely strange to you, don’t worry. Before learning VBA, I studied and worked in 2 careers that are infamous for using specialized jargon that is completely incomprehensible to outsiders: law and finance. To make a long story short…Visual Basic for Applications still seemed to me like a completely different language. But then I realized something:

VBA is indeed a different language and, after some time, I realized is not that hard to learn. This brings me to the first question I cover in this Excel VBA tutorial for beginners…

What Is VBA?

As you may already know, VBA stands for Visual Basic for Applications.

VBA is a programming language which was developed by Microsoft and is included in most products that are part of Microsoft Office.

What does this mean exactly?

You can think of a programming language just as you would think of pretty much any other language: English, Spanish, German, French, Italian, Portuguese, Hindi, Mandarin Chinese, Korean, etc. A language has several functions but, for purposes of this Excel VBA tutorial for beginners, I focus on one aspect: Communication.

Programming languages are slightly different in that you generally don’t use them to communicate with a human being. You use a programming language, such as VBA, to communicate with a computer. More particularly, you communicate instructions to the computer.

In other words, Visual Basic for Applications is the language that allows you and me to communicate instructions to Excel.

So there is no way around it:

In order to be able to automate tasks in Excel and unleash its power, you must learn VBA. However, as you may expect, VBA is different from regular human languages.

More generally, the codes you can use to communicate with your computer are slightly different from those you use to communicate with other people. One of the main reasons for this is that, despite the recent advances, computers can’t fully deal with or handle certain human communication features. These include, for example, human facial and body expressions.

Imagine you are learning a new human language (such as French, Italian or Spanish). One of the subject you need to study is its structure and, quite likely, you come across terms such as nouns, pronouns, verbs, adjectives, and the like. If you hadn’t heard those terms before or you’re like me and forgot their precise meanings, learning a new language could be quite challenging.

Well…

Programming languages are not significantly different and, therefore, in order to learn a language such as Visual Basic for Applications, you need to understand its structure. Since this structure isn’t exactly the same as that of human languages, you encounter some special (and different) terms that you must learn.

And this is where this Excel VBA tutorial for beginners comes in to help. In the following sections, I explain to you some of the most important terms that you need to know to learn VBA programming. By the end of this guide, you will understand the basic building blocks of Visual Basic for Applications, which will allow you to learn this programming language and become fluent much faster.

You can, to a certain extent, make an analogy between some of the word classes (nouns, verbs, adverbs, etc.) in English and some of the components of VBA to help you understand these elements better. In this Excel VBA tutorial for beginners, I use the analogy between VBA components and parts of speech to a certain extent but, where appropriate, I use different illustrations.

What Is A Macro? The Difference Between Macros And VBA?

Excel macros and Visual Basic for Applications are not exactly the same thing, although they are closely related and, sometimes, people use them interchangeably.

As explained above, VBA is a programming language which can be used in several programs that are part of Microsoft Office such as Excel, Power Point, Word and Access.

A macro is:

  • Not a programming language.
  • (Usually) Defined as a set of instructions you use to automate a Microsoft Office application (such as Excel).

In other words:

  • A macro is the sequence of instructions that you want Excel to follow in order to achieve a particular purpose.
  • Visual Basic for Applications is a programming language you can use to create macros.

Take, for example, the following instructions:

Example of difference between macros and visual basic for applications

The whole set of instructions is the equivalent of an Excel macro. It’s a sequence of instructions that should be followed in order to achieve a purpose which, in this case, is enjoying a tsukemen meal.

The language in which the instructions in the image above are written is English. This is the equivalent of Visual Basic for Applications.

So… as you can see: VBA and Excel macros have a very close relationship but, strictly speaking, they are not the same.

However, as you will see below, it is not uncommon to use certain terms interchangeably with the word macro.

What Is VBA Code?

This is where it may start to get a little bit confusing, but please bear with me…

When working with VBA, you execute VBA code. This VBA code carries out (certain) actions/tasks. You can generate VBA code in one of the following 2 ways:

  • By recording certain actions you perform in an Excel workbook by using the macro recorder.
  • By writing the VBA code in the Visual Basic Editor (VBE).

The following is a very basic example of VBA code. The comments near the top (in green font) explain what the piece of code does.

Example of VBA code

Now, you may wonder… what is the difference between a macro and VBA code?

I don’t go into too may details (it deviates from the purpose of this Excel VBA tutorial for beginners). For purposes of this guide, there is no essential difference. In fact, in the context of several Microsoft Office applications, the term “macro” is used by several users to refer to VBA code.

Some Excel VBA users distinguish between code and macros. From this perspective:

  • The term “VBA code” (usually) refers to the set of VBA commands you create by either:
    • Recording a macro; or
    • Writing VBA code in the VBE.
  • The term “macro” (usually) refers to the set of instructions Excel executes automatically.

Now that the definitions of macros, VBA and VBA code are clear (or at least clearer than they were at the beginning), let’s start looking at the different components of Visual Basic for Applications.

What Is A Module?

In broad terms, a module is the equivalent of a VBA container. In other words, it is where Excel actually stores the VBA code.

If you have seen a cargo ship or port, or if you have ever been involved in shipping, you may have seen intermodal containers (such as the ones in the image below). These containers are used for, among other purposes, storing goods.

Containers used as analogy for modules in VBA

In Excel, the equivalent of the intermodal containers are modules and the goods that are stored are the pieces of VBA code.

You can check out which modules are stored in the Excel workbook you’re currently working on in the Project Explorer (which is one of the sections of the Visual Basic Editor). The following screenshot shows an example of the Project Explorer, where there is only 1 standard module (called “Module1”).

project explorer with module

Standard modules are also referred to simply as modules. There are other types of modules in addition to standard modules.

Modules are made out of procedures so, as you can imagine, the next logical question is…

What Are Procedures And Routines?

A procedure is, basically, the part of a computer program that performs a particular task or action.

In more technical terms, a procedure is a block of statements that is enclosed by a particular declaration statement and an End declaration. VBA supports two types of procedures:

  • Sub procedures, which perform an action in Excel. The declaration statement that begins a Sub procedure is “Sub”.

    For example, the following piece of VBA code (the comments near the top of the image describe its basic purpose) is a Sub procedure. Notice the opening declaration statement, the matching End declaration and how the block of statements is enclosed by these two declarations.

    Example of a sub procedure with declaration and end statement

  • Function procedures, which carry out calculations and return a value.

Sub procedures do not return a value but function procedures can perform certain activities before returning a value.

The practical use of terms such as sub procedure, routine, program, procedure and macro can be a little bit confusing. In some cases, these terms are used interchangeably.

Perhaps the most important distinction you should be able to make is between Sub and Function procedures, as explained above. You can refer to these tutorials on Sub procedures and Function procedures for further information.

I imagine that you may have several questions related to the (more technical) definition of procedure given above, so let’s take a look at the meaning of one of its key words…

What Is A Statement?

A statement is an instruction. In some contexts, you can distinguish 2 main types of statements:

  1. Declaration statements are, as implied by their name, used to declare something such as a variable or a constant.

    When defining what a Sub procedure is, I showed you an example of a declaration statement. In this particular case, this declaration statement is the opening Sub statement which declares the Sub procedure named Best_Excel_Tutorial.

    Example of a declaration statement in VBA code

  2. Executable statements are statements that specify that a particular action should be taken.

    The Best_Excel_Tutorial macro used as an example above has several executable statements. For example, the statement “ActiveCell.Select” specifies that Excel should select the current active cell.

    Example of an executable statement in VBA code

    A special type of executable statements are assignment statements. Assignment statements assign a particular value or expression to a variable or constant.

What Are Objects?

As you’ve seen above, procedures perform tasks or actions.

You may wonder, what is the object of those tasks? In other words, on what is Excel performing the particular action?

The answer is objects.

Consider English grammar.

  • In regular English, an object (usually) has something done to/with it.
  • In real life, you can find objects anywhere, including the laptop that you use to work on Excel.

Analogy to explain what is an object in VBA

Horses are another example of objects.

Example of an object in Visual Basic for Applications

Actually, since I used to be a real big fan of horses when I was a child, I use them for explanation purposes throughout this Excel VBA tutorial for beginners and have some more horse pictures throughout this guide.

In Visual Basic for Applications things are not very different. This is because most VBA code works with (and manipulates) objects. In the context of Excel VBA, you can work with more than 100 objects.

The following are some examples of objects in Visual Basic for Applications:

  • Workbooks.
  • Worksheets.
  • Cell ranges.
  • Cells.
  • Cell fonts.

Can you spot 2 objects in the Best_Excel_Tutorial macro that has been used as an example?

If you haven’t, don’t worry; I point them out for you in the following screenshot.

Example of two objects in a piece of VBA code

The ActiveCell and Selection objects which I highlight above are among the most common.

  • ActiveCell refers to the current active cell in the current active Excel workbook.
  • Selection refers to the currently selected object which, in the example above, is a cell.

Objects are defined by classes, so the next question is…

What Are Classes?

As I mention above, classes define objects and, more particularly, classes define the following aspects of an object:

  • Variables.
  • Properties.
  • Procedures.
  • Events.

As a consequence of the above, you can:

  • Think of objects as instances of classes; or
  • (Similarly)Think about classes as blueprints.

For example, let’s assume you used to run a company that produced roll film cameras. That company had a basic blueprint or technical drawing such as the following:

Blueprint analogy to explain difference between classes and objects in VBA

This blueprint defines the characteristics of each of the roll film cameras to be produced and is, therefore, the equivalent of a VBA class. Once the company has the blueprint, it can produce the actual cameras.

Analogy explaining distinction between classes and objects

The actual produced cameras are the equivalent of a VBA object.

Classes are a slightly advanced Excel topic and, therefore, you’re unlikely to work much with them at the beginning. But, just in case, now you know what a class is and how it is different from, and related to, an object.

What Are Collections?

In Visual Basic for Applications, the word collection refers to collections of objects.

At the basic level, the general use of the word collection doesn’t differ too much from the use given to it in VBA. As you’d expect, in very general terms, a collection is a group of objects, more precisely a group of related objects.

Therefore, you can use collections to group and manage objects that are related between them.

At a basic level, the concept of collections is relatively simple but, if you want a more graphical illustration, check out the following Dr. Seuss collection.

Analogy of a collection of objects in VBA

In the context of VBA:

  • Collections are objects.
  • There is (also) a collection class.

If collections group objects that have some relationship between them, you may be wondering…

How Are Objects Related To Each Other?

Objects can be related to each other in several ways. However, the main type of relationship is of containment.

Containment relationships are present when objects are put within a container object. This means that objects can contain other objects within them, such as the plastic container (an object) that holds the Dr. Seuss books (other objects) in the image above.

A very good example of a containment relationship is a collection of objects.

Another important type of relationship is hierarchical, which is mostly applicable to classes. Hierarchical relationships occur when a class is derived from a more fundamental class.

What Is A Property?

Objects have properties. These are the attributes, characteristics or qualities that can be used to describe the object. I cover the topic of properties in this Excel tutorial.

VBA allows you to do both of the following:

  • Read the current value of an object’s properties; and
  • Change an object’s properties.

Let’s take, for example, this horse:

Example of VBA object properties

What are some of its properties? How about the color of its hair or its eyes? The size of its ears?

You get the idea.

In addition to having properties, objects have methods. As you may expect, the next question I answer is…

What Are Methods?

To understand what methods are, let’s go back to English grammar.

As I explain above when defining the term “object”, an object has something done to it. The method is the “something” which is done to the object. In other words: A method expresses an action performed with/on an object.

In grammatical terms, a method (in VBA) is roughly the equivalent of a verb (in English). I cover the topic of methods in more detail here.

Let’s continue using horses to illustrate the meaning of these Visual Basic for Applications components:

What is an example of a method (verb) that could be applied to a horse?

How about horseback riding?

Illustration of VBA methods in Excel

How Do Properties And Methods Look Like In Excel?

Let’s go back to the Best_Excel_Tutorial macro that I have been using as an example in this particular guide for beginners. If you run that macro, Excel does the following:

  • Types “This is the best Excel tutorial” into the active cell.
  • Auto-fits the column width of the active cell.
  • Colors the active cell red.
  • Changes the font color of the active cell to blue.

Example of a macro changing the properties of cells in Excel

Now that you know what is a property and what is a method:

Would you be able to distinguish which of the above make reference to a property and which to a method?

To answer this question, let’s take a look again at the VBA code:

example of Visual Basic for Applications code

And let’s take a closer look at the relevant lines to determine whether they make reference to a property or a method:

  • “ActiveCell.FormulaR1C1 = “This is the best Excel tutorial”” tells Excel to write “This is the best Excel tutorial” in the active cell.

    FormulaR1C1 as a property in Visual Basic for Applications
    ActiveCell returns an object. More precisely, it returns the current active cell.

    So what is FormulaR1C1? A property or a method?

    Property. More precisely, Formula R1C1 sets the formula for ActiveCell.

  • “Selection.Columns.AutoFit” instructs Excel to auto-fit the column of the active cell.

    Example of AutoFit as a method in Visual Basic for Applications
    In this case, the object is represented by Selection.Columns which represents the column of the current active cell.

    So what is the remaining part of the statement? Is AutoFit a property or a method?If you answered method, you are correct. AutoFit is changing the width of the relevant column to achieve the best fit. In other words, is doing something (auto-fitting) to the object.

  • The part of the first With… End With statement that actually sets the fill color of the active cell is “.Color = 255”.

    Example of the color property in Visual Basic for Applications
    All the individual statements within this With… End With statement (including “.Color = 255”) refer to Selection.Interior. This is the interior of the current selection (in this case, the active cell).

    You know which question is coming:

    Is Color a property or a method?Since Color is setting the main color of the interior of the active cell, the answer is property.

  • Finally, the part of the second With… End With Statement that determines the font color is “.Color = –4165632”.

    Another example of the Color property in VBA
    This is, for purposes of this Excel VBA tutorial for beginners, substantially the same case as above. In this case reference is made to Selection.Font which, in this example, is the font of the text in the active cell.

    And, as you already know that Color is a property, I won’t ask you again 😉 .

What Are Variables And Arrays?

In computer science, a variable is a storage location that you pair with a name and use to represent a particular value. That value is stored in the computer’s memory.

In other words: You use variables as placeholders for particular values. You can think about variables as envelopes.

Analogy used to illustrate concept of variables in Visual Basic for Applications

How can you use envelopes to store information?

You can, for example:

  • Put some information inside an envelope. This is the content of the envelope or, for programming purposes, the value of the variable.
  • Put a name to the envelope. This is the name of the envelope or variable.

Now, let’s imagine that you need to tell somebody to get the information that is inside a particular envelope. You can describe the information that you need in either of the following ways:

  • By describing the information itself. In this case, the person that is helping you has to open each and every envelope to check out their contents.
  • By mentioning the name of the relevant envelope. In this case, the person helping you doesn’t need to open each envelope to know where the piece of information they need to get is.

Can you picture why referring to the name of the envelope, instead of the information itself, can be a more efficient option?

But let’s get back to the topic that really matters:

Horses!

I bet you were not expecting that 😛 … but let’s imagine that you own one of the horses in the images above and a very important part of your horse’s diet is sugar cubes.

Image used to explain concept of variables in Visual Basic for Applications

The horse has 5 different caretakers and, each day, he should eat between 5 and 10 sugar cubes. In order to guarantee that this is the case, you set the following rule: each caretaker should give 1 or 2 sugar cubes per day to the horse.

At the beginning of each day, each caretaker needs to report how many sugar cubes he has given to the horse the day before. This report is done by filling the following Excel table.

Table used to explain VBA variables

Since you are a very efficient manager, you want to program a VBA application (let’s call it “Horse_Sugar_Cubes”) that does the following:

  • Asks each caretaker how many sugar cubes they have given to the horse.
  • If any of the caretakers has not followed the rule that requires him to give 1 or 2 sugar cubes to the horse, issues a reminder.

Before we take a look at the actual VBA code, check out how the Horse_Sugar_Cubes macro works in practice:

Example of how VBA application will run in Excel

This Excel VBA Tutorial for Beginners is accompanied by Excel workbooks containing the data and macros I use (including the Horse_Sugar_Cubes macro). You can get immediate free access to these example workbooks by clicking the button below.

Get immediate free access to the Excel VBA Tutorial for Beginners workbook examples

Let’s start the set up of the Horse_Sugar_Cubes application. For these purposes, you may want to use the following two variables:

  • A variable that stores the number of sugar cubes given by a particular caretaker to the horse. You can name this variable sugarCubes.
  • A variable that stores the identification number of the caretaker. You can name this variable caretakerNumber.

How do you create these variables?

To create a variable in Visual Basic for Applications, you must declare it. When you declare a variable, you determine what is the name and what are the characteristics of the particular variable, and tell the computer to allocate some storage space.

You declare a variable in VBA by using the Dim statement. I explain the topic of variable declaration in this Excel tutorial. For the moment, bear in mind the following:

  • You can declare variables at different levels. The level at which you declare a variable determines when is the variable applicable.

    For example, you can declare a variable at the top of a module. This variable is known as a module-level variable and exists as long as the module is loaded. Additionally, they’re available for use in any procedure within the relevant module.

    You can also create a variable with a more limited reach, by declaring the variable within a procedure. In this case, this variable is known as a procedure-level variable. Procedure-level variables can only be used within the relevant procedure in which they have been declared.

  • Since you use variables to store different types of data, you can define different types for a variable. You do this by using the As keyword.

    Some examples of types that you can specify for a variable are Integer, Boolean, String and Range.

Let’s take a look at how you can declare the variables caretakerNumber and sugarCubes in practice.

Example of how to declare a variable in Visual Basic for Applications

I come back to the topic of variables further down this Excel VBA tutorial for purposes of explaining how you can use variables in the VBA macro to help you keep track of how many sugar cubes are given to the horse each day.

As a final note, allow me to make a brief introduction of arrays. I provide a more detailed introduction to arrays in this VBA tutorial.

Variables that contain a single value are known as scalar variables. You use scalar variables when working with a single item.

What do you do if you are working with a group of items that are related to each other?

In these cases, you use arrays. Arrays are sets of indexed elements that share the same data type and have a logical relationship between them. The function is substantially the same as that of a variable: holding values. The main difference is that arrays can store several values while scalar variables can hold only one value.

When you use an array, you refer to the different elements of the array using the common name and distinguish among them with a number (called a subscript or index). For example, if you had a group of 10 horses numbered 1 through 10, you can refer to them as horses(1), horses(2), horses(3) and so on until horses(10).

Example of an array in Visual Basic for Applications

Let’s continue with the study of the main VBA components that appear in the Horse_Sugar_Cubes application by understanding…

What Is A Condition?

A condition is a statement or expression that evaluates to either true or false. Then, depending on whether the statement has evaluated to true or false, Excel executes (or doesn’t execute) a group of statements. In other words: If the condition is met (true), something happens.

Can you think of a way you can apply a conditional statement in the VBA application you are developing to keep track of how many sugar cubes are given to your horse by the caretakers?

Hint: conditional statements often use the if-then structure.

If you take a close look at the description of the 2 things that the Horse_Sugar_Cubes application should do, you’ll notice that the second step follows the if-then structure. More precisely:

  • If any of the caretakers doesn’t follow the rule that requires him to give 1 or 2 sugar cubes to the horse…
  • Then the Horse_Sugar_Cubes macro issues a reminder.

If you’re an Excel user, you may have noticed that conditions are not exclusive to VBA programming. For example, several Excel functions such as the IF function allow you to check whether a condition is true or not and, based on the result, do one thing or another. Additionally, you can use other functions such as ISNUMBER to perform logical tests.

There are several ways to structure conditional statements in Visual Basic Applications. For purposes of the Horse_Sugar_Cubes application, you can use an If…Then…Else statement.

How does this look inside the Visual Basic Editor?

You can use set up the following If…Then statement for the Horse_Sugar_Cubes macro:

Example of an If...Then statement in Visual Basic for Applications

Let’s take a look at each of the lines in this code snippet:

  • The first line states 2 conditions that can evaluate to either true or false.

    This particular line asks Excel to check whether the value of sugarCubes (the amount of sugar cubes that a particular caretaker has given to the horse) is less than 1 or more than 2. In other words, this is where Excel confirms whether a particular caretaker has complied with the rule that requires him to give 1 or 2 sugar cubes per day to the horse.

    If either of these 2 conditions is true, Excel executes the statement that appears in the second row. If neither of the 2 conditions is true (both are false), Excel doesn’t execute the statement in the second line.

  • The second line tells Excel what it should do if either of the 2 conditions set in the first line is true.

    In this case, if a caretaker has not given any sugar cubes (less than 1) or has given more than 2 sugar cubes to the horse in a particular day, Excel displays a message in a dialog box reminding that caretaker that he “should give 1 or 2 sugar cubes per day to the horse”.

  • The third line terminates the If…Then…Else block.

You now know how to create the variables that store the number of sugar cubes given to the horse by each caretaker and the identification number of each caretaker. You also know how to get Excel to remind a caretaker of the rule that states they should give 1 or 2 sugar cubes per day to the horse in case they haven’t done so.

You only need one extra VBA component to complete the basic structure of you Horse_Sugar_Cubes macro:

How do you get Excel to ask each of the 5 caretakers how many sugar cubes he has given to the horse?

I help you answer this question in the following section.

What Is A Loop?

Loops are statements that:

  • Are specified once, but…
  • Are carried out several times.

In other words, a loop is a particular statement that makes a group of instructions be followed multiple times. Just as conditional statements, there are several ways in which you can structure loops.

However, for purposes of the Horse_Sugar_Cubes application, you can can use a For Each…Next statement. This statement asks Excel to execute a group of statements repeatedly for each of the components of a particular group.

In practice, this looks roughly as follows. This is the For Each…Next statement of the Horse_Sugar_Cubes macro that I am using as example in this Excel VBA tutorial for beginners.

Example of a For Each loop in Visual Basic for Applications

Notice that the conditional statement that I explain in the section above is there.

Example of a condition within a loop in Visual Basic for Applications

However, what is more relevant for purposes of this section is the general structure of a For Each…Next statement, so let’s take a look at it.

  • At the beginning, a For Each…Next statement must say “For Each element of a certain type in the particular group”. In the example above, this line is as follows:

    Example of opening line of a For Each...Next statement in Visual Basic for Applications
    The word element refers to the particular items of a collection through which the loop should run. In the case I am using as an example, the elements are sugarCubes.

    In this particular case, sugarCubes is defined as a Range object variable. If you’re in a situation where the element has not been declared previously, you declare its data type.

    The last portion of the statement refers to the group in which the elements are. In this case, this is the range of cells C5 through C9. This is the collection over which the statements inside the loop is repeated.

    In other words, Excel applies the set of instructions inside the loop to each of the cells highlighted in the following screenshot.

    Example of the elements of a collection used in a VBA loop

  • The body of a simple For Each…Next statement such as the one in the Horse_Sugar_Cubes macro includes a certain number of instructions that Excel applies to each of the elements in the group (according to what has been stated in the first line).

    In the example being used in this Excel VBA tutorial for beginners, the body of statements looks as follows:

    Example of the statements inside a For Each...Next statement in Visual Basic for Applications
    The above group of statements is a very simple example. There are structures that are more complicated than this, involving statements (such as Continue For or Exit For) which can be used to transfer the control to different parts of the VBA code.

  • The last statement of the For Each…Next statement is of the form “Next element”. In the example above, this looks as follows:

    Example of closing line of a For Each...Next statement in Visual Basic for Applications
    This statement simply terminates the definition of the loop and tells Excel that, after carrying out the instructions inside the loop, it should move to the next element (in this case, the next sugarCubes).

To summarize, the opening and closing lines of the For Each…Next statement tell Excel that it should run the instructions that are inside the loop for each of the 5 cells where the number of sugar cubes given to the horse by each caretaker are to be recorded.

Macro Example: Horse_Sugar_Cubes

Before I end this Excel VBA tutorial for beginners, let’s take a final line-by-line look at the complete VBA code behind the Horse_Sugar_Cubes macro to review some of the essential terms that have been covered in this guide and understand each of the instructions behind the application.

Example of VBA code

For ease of reference, here is once more an illustration of how the Horse_Sugar_Cubes macro works in practice:

Example of how a VBA application works when running in Excel

Let’s go through the main items of this macro while making some general comments to further illustrate each of the terms covered in this tutorial:

#1. General aspects.

The Horse_Sugar_Cubes application is written in Visual Basic for Applications or VBA, the programming language you can use to communicate instructions to Excel.

Horse_Sugar_Cubes itself is a macro, a sequence of instructions for Excel to follow. The code that appears in the screenshot above is an example of VBA code. The terms macro, VBA code, Sub procedure, routine and procedure are sometimes used interchangeably.

The VBA code behind the Horse_Sugar_Cubes application is stored by Excel in a module, the container where Excel stores the VBA code.

The Horse_Sugar_Cubes macro has several statements, or instructions.

#2. Sub Horse_Sugar_Cubes() and End Sub.

Example of the declaration of a sub procedure in VBA code

The first line of code in the screenshot above declares the sub procedure Horse_Sugar_Cubes. A Sub procedure is the series of statements that are between the Sub and the End Sub statements and, more precisely, is a part of a computer program that performs an action.

The other main type of procedure in VBA are Function procedures, which carry out calculations and return a particular value.

The last line of code in the screenshot above terminates the execution of the sub procedure Horse_Sugar_Cubes. Once Excel executes this line, the macro stops running.

#3. Dim caretakerNumber As Integer and Dim sugarCubes as Range.

Example of how 2 variables are declared in Visual Basic for Applications

In Visual Basic for Applications, variables are usually declared using the Dim statement. After this, you can determine the name of the variable and its characteristics. The computer allocates a storage location to the variable and, then, you can use the declared variable as a placeholder to represent a particular value.

In the example above, 2 variables are declared. caretakerNumber is declared as an integer and sugarCubes as a range.

#4. caretakerNumber = 1.

Example of how to assign a value to a variable in VBA

This line is an assignment statement which assigns the value 1 to the variable caretakerNumber. As a consequence of this assignment, every time that the Horse_Sugar_Cubes macro is executed, caretakerNumber is set to the initial value of 1.

#5. For Each…Next statement.

Example of a For Each...Next statement in Visual Basic for Applications

A For Each…Next statement asks Excel to execute a group of statements repeatedly for each member of a group. This type of statement is one of the simplest ways to implement a loop, a statement that makes a particular group of instructions be repeated several times.

In the case of the Horse_Sugar_Cubes macro, the loop asks Excel to repeat the relevant set of instructions for each of the 5 caretakers of the horse. Let’s take a look at the body of the For Each…Next statement to understand the set of instructions that is repeated:

  • sugarCubes.Value = InputBox(“Number of sugar cubes given to horse by caretaker ” & caretakerNumber).

    Example of a statement inside a For Each...Next statement in Visual Basic for Applications


    The first part of the line (sugarCubes.Value =) assigns a value to the variable sugarCubes.

    The second part of the statement (InputBox(“Number of sugar cubes given to horse by caretaker ” & caretakerNumber)) instructs Excel to show a pop-up input box that asks what is the number of sugar cubes given to the horse by each caretaker. The number that is inputted in the box is recorded in the relevant cell of the Excel worksheet and is the value assigned to the variable sugarCubes.

    The input box refers to each caretaker by its identification number (1 through 5) by calling the value of the variable caretakerNumber (for example, the first caretaker is referred to as caretaker 1, and so on). As a consequence of the statement immediately above the For Each…Next statement (caretakerNumber = 1), the value of the variable caretakerNumber at the beginning of the process is always 1. I explain further below which statement asks Excel to update the caretaker number for the relevant caretaker.

  • Conditional statement.

    Example of a conditional statement in Visual Basic for Applications
    Conditional statements evaluate a particular condition and, depending on the result (true or false), Excel carries out (or refrains from carrying out) certain actions.

    The conditional statement in the Horse_Sugar_Cubes macro evaluates whether a caretaker has given less than 1 or more than 2 sugar cubes to the horse (therefore not complying with the rule that requires them to give either 1 or 2 sugar cubes per day to the horse). If any of the 2 conditions is met (the number of sugar cubes given to the horse is less than 1 or more than 2), Excel displays a message box with a reminder that states “You should give 1 or 2 sugar cubes per day to the horse”.

  • caretakerNumber = caretakerNumber + 1.This statement increases the value of the variable caretakerNumber by 1 for each successive repetition of the For Each…Next statement.

    Therefore, the second time the set of instructions is repeated by the macro, caretakerNumber is equal to 2. The third time, the variable has the value of 3. As you may expect, the values for the fourth and fifth times are 4 and 5 respectively.

Conclusion

You have made it to the end of this Excel VBA tutorial for beginners.

By now, based on what you have learned on this beginners guide, you know the meanings of at least 16 essential terms you need to know to learn VBA programming. You’re also able to understand how some of these terms are sometimes used interchangeably and some of the discussions regarding their use.

Additionally, you’ve seen how these concepts come together to form a macro, and you know how some of the VBA components that have been explained in this Excel VBA tutorial for beginners can be implemented in practice.

I hope that this Excel tutorial for beginners has proved that the most essential terms you need to know to learn VBA programming are not that complicated to understand.

You’re likely to find the terms that have been covered in this particular guide for beginners many times during your journey to becoming a VBA expert so you may want to bookmark this post and come back as required during your future Visual Basic for Applications studies.

Welcome to part one of the Ultimate VBA Tutorial for beginners.

If you are brand new to VBA, then make sure that you have read the post How To Create a Macro From Scratch in Excel so that your environment is set up correctly to run macros.

In this Excel VBA tutorial you will learn how to create real-world macros. The focus is on learning by doing. This tutorial has coding examples and activities to help you on your way. You will find a quiz at the end of this VBA tutorial. You can use this to test your knowledge and see how much you have learned.

In part one of this VBA tutorial we will concentrate on the basics of creating Excel macros. See the next sections for the learning outcomes and for tips on getting started with VBA.

“The noblest pleasure is the joy of understanding.” – Leonardo da Vinci

Learning Outcomes for this VBA Tutorial

When you finish this VBA tutorial you will be able to:

  1. Create a module
  2. Create a sub
  3. Understand the difference between a module and sub
  4. Run the code in a sub
  5. Write a value to a cell
  6. Copy the value from one cell to another
  7. Copy values from one range of cells to another
  8. Copy values between difference worksheets
  9. Test your output using the Immediate Window
  10. Write code faster using the With Statement
  11. Create and use variables
  12. Copy from a cell to a variable and vice versa

Before we get started, let’s look at some simple tips that will help you on your journey.

The Six Killer Tips For This VBA Tutorial

  1. Practice, Practice, Practice – Don’t try to learn by reading. Try the examples and activities.
  2. Type the code examples instead of copying and pasting – this will help you understand the code better.
  3. Have a clearly defined target for learning VBA. One you will know when you reach.
  4. Don’t be put off by errors. They help you write proper code.
  5. Start by creating simple macros for your work. Then create more complex ones as you get better.
  6. Don’t be afraid to work through each tutorial more than once.The more times you do it the more deeply embedded the knowledge will become.

Basic Terms Used in this VBA Tutorial

Excel Macros: A macro is a group of programming instructions we use to create automated tasks.

VBA: VBA is the programming language we use to create macros. It is short for Visual Basic for Applications.

Line of code: This a VBA instruction. Generally speaking, they perform one task.

Sub: A sub is made up of one or more lines of code. When we “Run” the sub, VBA goes through all the lines of code and carries out the appropriate actions. A macro and a sub are essentially the same thing.

Module: A module is simply a container for our subs. A module contains subs which in turn contain lines of code. There is no limit(within reason) to the number of modules in a workbook or the number of subs in a module.

VBA Editor: This is where we write our code. Pressing Alt + F11 switches between Excel and the Visual Basic Editor. If the Visual Basic editor is not currently open then pressing Alt + F11 will automatically open it.

The screenshot below shows the main parts of the Visual Basic Editor:

The Visual Basic Editor

Tip for the VBA Tutorial Activities

When you are working on the activities in this VBA Tutorial it is a good idea to close all other Excel workbooks.

Creating a Module

In Excel, we use the VBA language to create macros. VBA stands for Visual Basic for Applications.

When we use the term Excel Macros we are referring to VBA. The term macro is essentially another name for a sub. Any time you see the terms Excel Macros or VBA just remember they are referring to the same thing.

In VBA we create lines of instructions for VBA to process. We place the lines of code in a sub. These subs are stored in modules.

We can place our subs in the module of the worksheet. However, we generally only place code for worksheet events here.

In VBA, we create new modules to hold most of our subs. So for our first activity let’s go ahead and create a new module.

 Activity 1

  1. Open a new blank workbook in Excel.
  2. Open the Visual Basic Editor(Alt + F11).
  3. Go to the Project – VBAProject window on the left(Ctrl + R if it is not visible).
  4. Right-click on the workbook and click Insert and then Module.
  5. Click on Module1 in the Project – VBAProject window.
  6. In the Properties window in the bottom left(F4 if not visible), change the module name from module1 to MyFirstModule.

 End of Activity 1

The module is where you place your code. It is simply a container for code and you don’t use it for anything else.

You can think of a module like a section in a bookshop. It’s sole purpose is to store books and having similar books in a particular section makes the overall shop more organised.

The main window(or code window) is where the code is written. To view the code for any module including the worksheets you can double-click on the item in the Project – VBAProject window.

Let’s do this now so you can become familiar with the code window.

 Activity 2

  1. Open a new workbook and create a new module like you did in the last activity.
  2. Double-click on the new module in the Project – VBAProject window.
  3. The code window for this module will open. You will see the name in the title bar of Visual Basic.

VBA Tutorial 2A

 End of Activity 2

You can have as many modules as you like in a workbook and as many subs as you like within a module. It’s up to you how you want to name the modules and how you organize your subs within your modules.

In the next part of this VBA Tutorial, we are going to look at using subs.

How to Use Subs

A line of code is the instruction(s) we give to VBA. We group the lines of code into a sub. We place these subs in a module.

We create a sub so that VBA will process the instructions we give it. To do this we get VBA to Run the sub. When we select Run Sub from the menu, VBA will go through the lines of code in the sub and process them one at a time in the order they have been placed.

Let’s go ahead and create a sub. Then afterward, we will have a look at the lines of code and what they do.

 Activity 3

  1. Take the module you created in the last activity or create a new one.
  2. Select the module by double-clicking on it in the Project – VBAProject window. Make sure the name is visible in the title bar.
  3. Enter the following line in the code window and press enter.
    Sub WriteValue
    
  4. VBA will automatically add the second line End Sub. We place our code between these two lines.
  5. Between these two lines enter the line
     Sheet1.Range("A1") = 5
    

    You have created a sub! Let’s take it for a test drive.

  6. Click in the sub to ensure the cursor is placed there. Select Run->Run Sub/Userform from the menu(or press F5).
    Note: If you don’t place the cursor in the sub, VBA will display a list of available subs to run.
  7. Open Excel(Alt + F11). You will see the value 5 in the cell A1.
  8. Add each of the following lines to your sub, run the sub and check the results.
Sheet1.Range("B1") = "Some text"
Sheet1.Range("C3:E5") = 5.55
Sheet1.Range("F1") = Now

You should see “Some text” in cells B1, 5.55 in the cells C3 to E5 and the current time and date in the cell F1.

 End of Activity 3

Writing values to cells

Let’s look at the line of code we used in the previous section of this VBA Tutorial

Sheet1.Range("A1") = 5

We can also write this line like this

Sheet1.Range("A1").Value = 5

However in most cases we don’t need to use Value as this is the default property.

We use lines of code like these to assign(.i.e. copy) values between cells and variables.

VBA evaluates the right of the equals sign and places the result in the variable/cell/range that is to the left of the equals.

The line is saying “the left cellvariablerange will now be equal to the result of the item on the right”.

Tutorial 1 Assignment line parts

Let’s look the part of the code to the left of the equals sign

Sheet1.Range("A1") = 5

In this code , Sheet1 refers to the code name of the worksheet. We can only use the code name to reference worksheets in the workbook containing the code. We will look at this in the section The code name of the worksheet.

When we have the reference to a worksheet we can use the Range property of the worksheet to write to a range of one or more cells.

Using a line like this we can copy a value from one cell to another.

Here are some more examples:

' https://excelmacromastery.com/
Sub CopyValues()
    
    ' copies the value from C2 to A1
    Sheet1.Range("A1") = Sheet1.Range("C2")
    
    ' copies the value from D6 to A2
    Sheet1.Range("A2") = Sheet1.Range("D6")
    
    ' copies the value from B1 on sheet2 to A3 on sheet1
    Sheet1.Range("A3") = Sheet2.Range("B1")
    
    ' writes result of D1 + D2 to A4
    Sheet1.Range("A4") = Sheet2.Range("D1") + Sheet2.Range("D2")
    
End Sub

Now it’s your turn to try some examples. Copying between cells is a fundamental part of Excel VBA, so understanding this will really help you on your path to VBA mastery.

 Activity 4

      1. Create a new Excel workbook.
      2. Manually add values to the cells in sheet1 as follows: 20 to C1 and 80 to C2.
      3. Create a new sub called Act4.
      4. Write code to place the value from C1 in cell A1.
      5. Write code to place the result of C2 + 50 in cell A2.
      6. Write code to multiply the values in cells C1 and C2. Place the results in cell A3.
      7. Run the code. Cells should have the values A1 20, A2 130 and A3 1600

 End of Activity 4

Cells in Different Sheets

We can easily copy between cells on different worksheets. It is very similar to how we copy cells on the same worksheet. The only difference is the worksheet names which we use in our code.

In the next VBA Tutorial activity, we are going to write between cells on different worksheets.

 Activity 5

      1. Add a new worksheet to the workbook from the last activity. You should now have two worksheets called which are called Sheet1 and Sheet2.
      2. Create a new sub called Act5.
      3. Add code to copy the value from C1 on Sheet1 to cell A1 on Sheet2.
      4. Add code to place the result from C1 + C2 on Sheet1 to cell A2 on Sheet2.
      5. Add code to place the result from C1 * C2 on Sheet1 to cell A3 on Sheet2.
      6. Run the code in the sub(F5). Cells on Sheet2 should have the values as follows:
        A1 20, A2 100 and A3 1600

 End of Activity 5

The Code Name of the Worksheet

In the activities so far, we have been using the default names of the worksheet such as Sheet1 and Sheet2. It is considered good practice to give these sheets more meaningful names.

We do this by changing the code name of the worksheet. Let’s look at the code name and what it is.

When you look in the Project – VBAProject window for a new workbook you will see Sheet1 both inside and outside of parenthesis:

VBA Code name

      • Sheet1 on the left is the code name of the worksheet.
      • Sheet1 on the right(in parenthesis) is the worksheet name. This is the name you see on the tab in Excel.

The code name has the following attributes

      1. We can use it to directly reference the worksheet as we have been doing e.g.
Sheet1.Range("A1")

Note: We can only use the code name if the worksheet is in the same workbook as our code.

      1. If the worksheet name is changed our code will still work if we are using the code name to refer to the sheet.

The worksheet name has the following attributes

      1. To reference the worksheet using the worksheet name we need to use the worksheets collection of the workbook. e.g.
ThisWorkbook.Worksheets("Sheet1").Range("A1")
      1. If the worksheet name changes then we need to change the name in our code. For example, if we changed the name of our sheet from Sheet1 to Data then we would need to change the above code as follows
ThisWorkbook.Worksheets("Data").Range("A1")

We can only change the code name in the Properties window.
We can change the worksheet name from both the worksheet tab in Excel and from the Properties window.

VBA Code name

worksheet name on tab

In the next activity, we will change the code name of the worksheet.

 Activity 6

      1. Open a new blank workbook and go to the Visual Basic editor.
      2. Click on Sheet1 in the Project – VBAProject Window(Ctrl + R if not visible).
      3. Go to the Properties window(F4 if not visible).
      4. Change the code name of the worksheet to shReport.
      5. Create a new module and call it modAct6.
      6. Add the following sub and run it(F5)
Sub UseCodename()
    shReport.Range("A1") = 66
End Sub
      1. Then add the following sub and run it(F5)
Sub UseWorksheetname()
    ThisWorkbook.Worksheets("Sheet1").Range("B2") = 55
End Sub
      1. Cell A1 should now have the value 66 and cell B2 should have the value 55.
      2. Change the name of the worksheet in Excel to Report i.e. right-click on the worksheet tab and rename.
      3. Delete the contents of the cells and run the UseCodename code again. The code should still run correctly.
      4. Run the UseWorksheetname sub again. You will get the error “Subscript out of Range”. This cryptically sounding error simply means that there is no worksheet called Sheet1 in the worksheets collection.
      5. Change the code as follows and run it again. The code will now run correctly.
Sub UseWorksheetname()
    ThisWorkbook.Worksheets("Report").Range("B2") = 55
End Sub

The With keyword

You may have noticed in this VBA Tutorial that we need to use the worksheet name repeatedly – each time we refer to a range in our code.

Imagine there was a simpler way of writing the code. Where we could just mention the worksheet name once and VBA would apply to any range we used after that. The good news is we can do exactly that using the With statement.

In VBA we can take any item before a full stop and use the With statement on it. Let’s rewrite some code using the With statement.

The following code is pretty similar to what we have been using so far in this VBA Tutorial:

' https://excelmacromastery.com/
Sub WriteValues()

    Sheet1.Range("A1") = Sheet1.Range("C1")
    Sheet1.Range("A2") = Sheet1.Range("C2") + 50
    Sheet1.Range("A3") = Sheet1.Range("C1") * Sheet1.Range("C2")
    
End Sub

Let’s update this code using the With statement:

' https://excelmacromastery.com/
Sub UsingWith()

    With Sheet1
        .Range("A1") = .Range("C1")
        .Range("A2") = .Range("C2") + 50
        .Range("A3") = .Range("C1") * .Range("C2")
    End With
        
End Sub

We use With and the worksheet to start the section. Anywhere VBA finds a full stop it knows to use the worksheet before it.

We can use the With statement with other types of objects in VBA including workbooks, ranges, charts and so on.

We signify the end of the With section by using the line End With.

Indenting(Tabbing) the Code
You will notice that the lines of code between the start and end With statments are tabbed once to right. We call this indenting the code.

We always indent the code between VBA sections that have a starting line and end line. Examples of these are as subs, the With statement, the If statement and the For loop.

You can tab the lines of code to the right by selecting the appropriate lines of code and pressing the Tab key. Pressing Shift and Tab will tab to the left.

Tabbing(or indenting) is useful because it makes our code more readable.

 Activity 7

      1. Rewrite the following code using the With statement. Don’t forget to indent the code.
' https://excelmacromastery.com/
Sub UseWith()

Sheet1.Range("A1") = Sheet1.Range("B3") * 6
Sheet1.Cells(2, 1) = Sheet1.Range("C2") + 50
Sheet1.Range("A3") = Sheet2.Range("C3")


End Sub

 End of Activity 7

Copying values between multiple cells

You can copy the values from one range of cells to another range of cells as follows

Sheet2.Range("A1:D4") = Sheet2.Range("G2:I5").Value

It is very important to notice than we use the Value property of the source range. If we leave this out it will write blank values to our destination range.

' the source cells will end up blank because Value is missing
Sheet2.Range("A1:D4") = Sheet2.Range("G2:I5")

The code above is a very efficient way to copy values between cells. When people are new to VBA they often think they need to use some form of select, copy and paste to copy cell values. However these are slow, cumbersome and unnecessary.

It is important that both the destination and source ranges are the same size.

      • If the destination range is smaller then only cell in the range will be filled. This is different to copy/pasting where we only need to specify the first destination cell and Excel will fill in the rest.
      • If the destination range is larger the extra cells will be filled with #N/A.

 Activity 8

      1. Create a new blank workbook in Excel.
      2. Add a new worksheet to this workbook so there are two sheets – Sheet1 and Sheet2.
      3. Add the following data to the range C2:E4 on Sheet1

VBA Tutorial Act 7

      1. Write code to copy the data from Sheet1 to the range B3:D5 on Sheet2.
      2. Run the code(F5).
      3. Clear the results and then change the destination range to be smaller than the source range. Run again and check the results.
      4. Clear the results and then change the destination range to be larger than the source range. Run again and check the results.

 End of Activity 8

Transposing a Range of Cells

If you need to transpose the date(convert from row to column and vice versa) you can use the WorksheetFunction Transpose.

Place the values 1 to 4 in the cells A1 to A4. The following code will write the values to E1 to H1

Sheet1.Range("E1:H1") = WorksheetFunction.Transpose(Sheet1.Range("A1:A4").Value)

The following code will read from E1:H1 to L1:L4

Sheet1.Range("L1:L4") = WorksheetFunction.Transpose(Sheet1.Range("E1:H1").Value)

You will notice that these lines are long. We can split one line over multiple lines by using the underscore(_) e.g.

Sheet1.Range("E1:H1") = _ 
    WorksheetFunction.Transpose(Sheet1.Range("A1:A4").Value)
Sheet1.Range("L1:L4") = _
    WorksheetFunction.Transpose(Sheet1.Range("E1:H1").Value)

How to Use Variables

So far in this VBA Tutorial we haven’t used variables. Variables are an essential part of every programming language.

So what are they and why do you need them?

Variables are like cells in memory. We use them to store temporary values while our code is running.

We do three things with variables

      1. Declare(i.e. Create) the variable.
      2. Store a value in the variable.
      3. Read the value stored in the variable.

The variables types we use are the same as the data types we use in Excel.

The table below shows the common variables. There are other types but you will rarely use them. In fact you will probably use Long and String for 90% of your variables.

Type Details
Boolean Can be true or false only
Currency same as decimal but with 4 decimal places only
Date Use for date/time
Double Use for decimals
Long Use for integers
String Use for text
Variant VBA will decide the type at runtime

Declaring Variables

Before we use variables we should create them. If we don’t then we can run into various problems.

By default, VBA doesn’t make you declare variables. However, we should turn this behaviour on as it will save us a lot of pain in the long run.

To turn on “Require Variable Declaration” we add the following line to the top of our module

Option Explicit

To get VBA to automatically add this line, select Tools->Options from the menu and check Require Variable Declaration. Anytime you create a new module, VBA will add this line to the top.

VBA Option Explicit

Declaring a variable is simple. We use the format as follows

Dim variable_name As Type

We can use anything we like as the variable name. The type is one of the types from the table above. Here are some examples of declarations

Dim Total As Long
Dim Point As Double
Dim Price As Currency
Dim StartDate As Date
Dim CustomerName As String
Dim IsExpired As Boolean
Dim Item As Variant

To place a value in a variable we use the same type of statement we previously used to place a value in a cell. This is the statement with the equals sign:

' https://excelmacromastery.com/
Sub DeclaringVars()

    Dim Total As Long
    Total = 1
        
    Dim Price As Currency
    Price = 29.99
    
    Dim StartDate As Date
    StartDate = #1/21/2018#
    
    Dim CustomerName As String
    CustomerName = "John Smith"
    
End Sub

 Activity 9

      1. Create a new sub and call it UsingVariables.
      2. Declare a variable for storing a count and set the value to 5.
      3. Declare a variable for storing the ticket price and set the value to 99.99.
      4. Declare a variable for storing a country and set the value to “Spain”.
      5. Declare a variable for storing the end date and set the value to 21st March 2020.
      6. Declare a variable for storing if something is completed. Set the value to False.

 End of Activity 9

The Immediate Window

VBA has a real nifty tool that allows us to check our output. This tool is the Immediate Window. By using the Debug.Print we can write values, text and results of calculations to the Immediate Window.

To view this window you can select View->Immediate Window from the menu or press Ctrl + G.

The values will be written even if the Immediate Window is not visible.

We can use the Immediate Window to write out our variables so as to check the values they contain.

If we update the code from the last activity we can write out the values of each variable. Run the code below and check the result in the Immediate Window(Ctrl + G if not visible).

' https://excelmacromastery.com/
Sub WritingToImmediate()
    
    Dim count As Long
    count = 5
    Debug.Print count
    
    Dim ticketprice As Currency
    ticketprice = 99.99
    Debug.Print ticketprice
    
    Dim country As String
    country = "Spain"
    Debug.Print country
    
    Dim enddate As Date
    enddate = #3/21/2020#
    Debug.Print enddate
    
    Dim iscompleted As Boolean
    iscompleted = False
    Debug.Print iscompleted
        
End Sub

The Immediate is very useful for testing output before we write it to worksheets. We will be using it a lot in these tutorials.

Writing between variables and cells

We can write and read values between cells and cells, cells and variables,and variables and variables using the assignment line we have seen already.

Here are some examples

' https://excelmacromastery.com/
Sub VariablesCells()

    Dim price1 As Currency, price2 As Currency
    
    ' place value from A1 to price1
    price1 = Sheet1.Range("A1")
    
    ' place value from price1 to price2
    price2 = price1
    
    ' place value from price2 to cell b2
    Sheet1.Range("B2") = price2
    
    ' Print values to Immediate window
    Debug.Print "Price 1 is " & price1
    Debug.Print "Price 2 is " & price2

End Sub

 Activity 10

      1. Create a blank workbook and a worksheet so it has two worksheets: Sheet1 and Sheet2.
      2. Place the text “New York” in cell A1 on Sheet1. Place the number 49 in cell C1 on Sheet2.
      3. Create a sub that reads the values into variables from these cells.
      4. Add code to write the values to the Immediate window.

 End of Activity 10

Type Mismatch Errors

You may be wondering what happens if you use an incorrect type. For example, what happens if you read the number 99.55 to a Long(integer) variable type.

What happens is that VBA does it best to convert the variable. So if we assign the number 99.55 to a Long type, VBA will convert it to an integer.

In the code below it will round the number to 100.

Dim i As Long
i = 99.55

VBA will pretty much convert between any number types e.g.

' https://excelmacromastery.com/
Sub Conversion()

    Dim result As Long
    
    result = 26.77
    result = "25"
    result = 24.55555
    result = "24.55"  
    Dim c As Currency
    c = 23
    c = "23.334"
    result = 24.55
    c = result

End Sub

However, even VBA has it’s limit. The following code will result in Type Mismatch errors as VBA cannot convert the text to a number

' https://excelmacromastery.com/
Sub Conversion()

    Dim result As Long
    
    result = "26.77A"
    
    Dim c As Currency
    c = "a34"

End Sub

Tip: The Type Mismatch error is often caused by a user accidentally placing text in a cell that should have numeric data.

 Activity 11

      1. Declare a Double variable type called amount.
      2. Assign a value that causes a Type Mismatch error.
      3. Run the code and ensure the error occurs.

 End of Activity 11

VBA Tutorial Assignment

We’ve covered a lot of stuff in this tutorial. So let’s put it all together in the following assignment

 Tutorial One Assignment

I have created a simple workbook for this assignment. You can download it using the link below

Tutorial One Assignment Workbook

Open the assignment workbook. You will place your code here

      1. Create a module and call it Assignment1.
      2. Create a sub called Top5Report to write the data in all the columns from the top 5 countries to the Top 5 section in the Report worksheet. This is the range starting at B3 on the Report worksheet. Use the code name to refers to the worksheets.
      3. Create a sub call AreaReport to write all the areas size to the All the Areas section in the Report worksheet. This is the range H3:H30. Use the worksheet name to refer to the worksheets.
      4. Create a sub called ImmediateReport as follows, read the area and population from Russia to two variables. Print the population per square kilometre(pop/area) to the Immediate Window.
      5. Create a new worksheet and call it areas. Set the code name to be shAreas. Create a sub called RowsToCols that reads all the areas in D2:D11 from Countries worksheet and writes them to the range A1:J1 in the new worksheet Areas.

End of Tutorial Assignment

The following quiz is based on what we covered this tutorial.

VBA Tutorial One Quiz

1. What are the two main differences between the code name and the worksheet name?

2. What is the last line of a Sub?

3. What statement shortens our code by allowing us to write the object once but refer to it multiple times?

4. What does the following code do?

Sheet1.Range("D1") = result

5. What does the following code do?

Sheet1.Range("A1:C3") = Sheet2.Range("F1:H3")

6. What is the output from the following code?

Dim amount As Long
amount = 7

Debug.Print (5 + 6)  * amount  

7. What is the output from the following code?

Dim amt1 As Long, amt2 As Long

amt1 = "7.99"
Debug.Print amt1

amt2 = "14a"
Debug.Print amt2

8. If we have 1,2 and 3 in the cells A1,A2 and A3 respectively, what is the result of the following code?

Sheet1.Range("B1:B4") = Sheet1.Range("A1:A3").Value

9. What does the shortcut key Alt + F11 do?

10. In the following code we declare a variable but do not assign it a value. what is the output of the Debug.Print statement?

Dim amt As Long

Debug.Print amt

Conclusion of the VBA Tutorial Part One

Congratulations on finishing tutorial one. If you have completed the activities and the quiz then you will have learned some important concepts that will stand to you as you work with VBA.

In the Tutorial 2, we are going to deal with ranges where the column or row may differ each time the application runs. In this tutorial, we will cover

      • How to get the last row or column with data.
      • The amazingly efficient CurrentRegion property.
      • How to use flexbile rows and columns.
      • When to use Range and when to use Cells.
      • and much more…

.

Please note: that Tutorials 2 to 4 are available as part of the VBA Fundamentals course in the membership section.

What’s Next?

Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.

Excel VBA Tutorial for Beginners

If you are new to VBA and do not know anything about it, this is the best tutorial for beginners to start their journey in Excel 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. So, let us start the journey of your VBA tutorials today.

VBA is 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 Editor). For example, VBE is the platform to write our code of tasks to execute in Excel.

Table of contents
  • Excel VBA Tutorial for Beginners
    • What are the Macros in Excel?
      • Step 1: Go to FILE -> Under FILE, go to OPTIONS.
      • Step 2: Select Customize Ribbon
      • Step 3:Check the box DEVELOPER to enable it.
      • Step 4: Click on OK to enable it.
    • Tutorial to Record Macros in VBA Excel
      • Example #1
        • Step 1: Click on Record Macro
        • Step 2: Give Name to Macro
        • Step 3: Click on OK to Start the Recording.
        • Step 4: Stop Recording
        • Step 5: Open VBA Editor
        • Step 6: Run the Code
      • Example #2
    • How to Save Macro Workbook?
    • Things to Remember
    • Recommended Articles

VBA Tutorial

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 Tutorial (wallstreetmojo.com)

What are the Macros in Excel?

A 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. Let us record the Macro to start with the VBA Macro 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 technique.

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.

VBA Tutorial (Developer tab) 1

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

Step 1: Go to FILE -> Under FILE, go to OPTIONS.

vba msg box

Step 2: Select Customize Ribbon

You will see the “Excel Options” window. Select “Customize Ribbon in ExcelRibbons in Excel 2016 are designed to help you easily locate the command you want to use. Ribbons are organized into logical groups called Tabs, each of which has its own set of functions.read more.

msgbox 1

Step 3:Check the box DEVELOPER to enable it.

msgbox 2

Step 4: Click on OK to enable it.

Now, you should see the “Developer” tab.

vba msgbox 3

Tutorial to Record Macros in VBA Excel

In this tutorial about VBA, we will learn how to record macros in ExcelRecording 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
with practical examples.

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

Example #1

We will start straight away by recording Macro.

Step 1: Click on Record Macro

Under the Developer tab, click on Record Macro.

(Record Macro)

Step 2: Give Name to Macro

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

Tutorial (Record Macro) 1

Give a proper name to Macro. The Macro should not contain any space characters and special characters. You can give underscore (_) as the word separator.

VBA Tutorial (Record Macro) 2

Step 3: Click on OK to Start the Recording.

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

So, firstly, we will select cell A1.

VBA Tutorial (Select A1)

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

VBA Tutorial (welcome to vba)

Step 4: Stop Recording

Now, we will click on the “Stop Recording” option under the “Developer” tab to stop the recording.

VBA Tutorial (Stop recording)

So, Excel stops recording the activities we do in Excel. Now, let us see how Excel recorded the activities.

Step 5: Open VBA Editor

Under the Developer tab, click on “Visual Basic.”

VBA Tutorial (Visual Basic)

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

VBA Tutorial (Visual Basic) 1

Double-click on “Modules.”

VBA Tutorial (Modules)

Now, we will see the code on the right-hand side. Macro code started with the word SUB.

All the Macro has two parts: Head and Tail. In addition, every Macro has a name.

VBA Tutorial (head & Tail)

Excel recorded all the activities between the head and tail of the Macro.

The first thing we did after recording the Macro was select 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.

The third activity is after typing the word “Welcome to VBA,” we press the “Enter” key, and Excel selects the A2 cell. So, Excel recorded the activity as Range (“A2”). Select

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

VBA Tutorial (Delete the word)

After deleting the word, go to VBE, where our code is once again.

Step 6: Run the Code

Click on the RUN button to enter the same text value to cell A1.

VBA Tutorial (run the code)

Note: Shortcut key to run the code is F5.

So, Macro executed, and we got 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.

Example 2

Click on “OK” to start the recording. First, we will enter 1, 2, and 3. Then, we will drag the fill handle to insert serial numbers.

Example 2-1

Now, click on “Stop Recording.”

Stop recording

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

Example 2-2

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 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.

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 Macro Workbook?

The Excel workbook containing Macro code should save as Macro-Enabled Workbook. Then, click on Save As in excelSave as is located in the worksheet’s file tab. It can be accessed from the quick access toolbar or by pressing F12 and choosing «save as,» or CTRL + S, which opens the save as dialogue box to save the file.read more and select the file extension as “Macro-Enabled Workbook.”

VBA Tutorial Example 2-3

Things to Remember

  • It is just the introduction part of VBA. Keep following our blog to see more posts as we advance.
  • 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 is a guide to VBA Tutorial for beginners. Here, we discuss steps to enable the Developer tab and learn how to record macros in Excel VBA and practical examples. Below you can find some useful Excel VBA articles: –

  • VBA Font Color Examples
  • Pivot Table using VBA Code
  • How to Paste in VBA?
  • How to Select Cell in VBA?

Понравилась статья? Поделить с друзьями:
  • What is excel time format
  • What is excel think cell
  • What is excel spreadsheet format
  • What is excel solver xlam
  • What is excel solver tool