What is excel and visual basic

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

Содержание

  1. What is Excel VBA, and how can you use it?
  2. Our Example — Copying, Pasting and Formatting Information
  3. The VBA Programming Language
  4. What is VBA? The Excel Macro Language
  5. What is VBA used for in Excel?
  6. How do I start with VBA in Excel?
  7. How can I access VBA code?
  8. What can VBA do?
  9. Are VB and VBA the same?
  10. What is the difference between a macro and VBA?
  11. VBA Coding Made Easy
  12. What is the difference between a macro and a script?
  13. What does a VBA Developer do?
  14. Why is VBA important?
  15. Is VBA a good programming language?
  16. Is VBA object-oriented?
  17. What is Excel VBA? : Excel VBA Basics 001
  18. What is VBA?
  19. Is there any difference between a VBA Program and Macro?
  20. Why learning Excel VBA is so important?
  21. What all you can do with Excel VBA?
  22. Subscribe and be a part of our 15,000+ member family!

What is Excel VBA, and how can you use it?

You’ve probably heard of VBA (or Visual Basic for Applications, to give the programming language its full name), but what is it? And how can it help you?

I’m aware that there are ways to accomplish the task set out below without using macros, but that’s not the point of this blog!

Our Example — Copying, Pasting and Formatting Information

To see how VBA could help you, suppose that you are a data entry clerk for a major talent show on national TV. Every time there’s a vote, the scores are entered into a spreadsheet:

Whenever a vote is taken, the judges type their scores onto this spreadsheet

From here, your task is to copy the results faithfully into a results sheet:

You have to type in a row for the new contestant’s scores

There are two main problems with this:

  1. It takes ages — with all the copying/pasting and formatting involved, at least 20 mouse clicks for each contestant.
  2. It’s prone to error — you’ve noticed that you start making mistakes when you’re tired.

You start dreaming — wouldn’t it be fantastic if you could just click on a button to copy the results across:

The magical button (if only you knew how to create it) .

This blog shows you how to automate tasks like the one above using Visual Basic for Applications! But first, what is VBA?

The VBA Programming Language

You don’t really need to know this, but it’s good background .

All computer programs are written using a programming language (examples are Fortran, C#, C, Pascal and Visual Basic). The Visual Basic language — VB to its friends — is particularly favoured by Microsoft, and is used by millions of programmers around the world. Here’s a bit of VB:

‘if no menu (eg search page), hide

Title = «Search results»

Title = «Problem with page»

You can see that the language looks half like English and half like meaningless computer gibberish.

Microsoft have included a cut-down version of this language within each Office application (Word, Access, Excel, PowerPoint, SharePoint, Outlook and Visio all include variants of VBA). This language is called Visual Basic for Applications, or VBA, because it’s Visual Basic running within an application. Here’s an example of VBA from Excel, taken from a hangman game:

‘each part of the gallows

Dim Limb As Shape

‘ checks all the shapes on the worksheet and makes one of them visible

‘ has a shape been made visible in this function call?

Dim MadeVisible As Boolean

‘ assume no shapes have been made visible in this function call

‘ loop through all shapes

For Each Limb In ActiveSheet.Shapes

‘ if the current shape is invisble and we havn’t already made one visible

If Limb.Visible = msoFalse And MadeVisible = False Then

‘ …make it visible

‘ and make sure we leave the rest of them alone!

Fortunately for you (and everyone else), you don’t have to know how to write macros — you can just record them.

Источник

What is VBA? The Excel Macro Language

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

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

What is VBA used for in Excel?

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

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

How do I start with VBA in Excel?

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

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

How can I access VBA code?

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

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

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

What can VBA do?

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

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

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

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

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

Are VB and VBA the same?

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

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

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

What is the difference between a macro and VBA?

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

VBA Coding Made Easy

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

What is the difference between a macro and a script?

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

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

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

What does a VBA Developer do?

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

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

Why is VBA important?

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

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

Is VBA a good programming language?

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

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

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

Is VBA object-oriented?

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

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

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

Источник

What is Excel VBA? : Excel VBA Basics 001

Visual Basic for Applications (VBA) in Excel, is a powerful and sophisticated built-in programming language that allows you to write your own functions or commands in an Excel spreadsheet.

These custom functions or commands, can help to ease your tasks and thus by using Excel VBA you can do almost any imaginable thing in Excel.

Now, before we dive deep into Excel VBA, let’s first try to understand what VBA is.

Table of Contents

What is VBA?

In most simple terms you can also say that, VBA is the language that Office Applications like Excel, Word, PowerPoint, etc. understand. So, all the programming that we are going to do in Excel or in other office application has to be done in VBA.

But technically, VBA is an implementation of Microsoft’s event-driven programming language i.e. VB6 and its associated integrated development environment (IDE).

VBA is an extensible programming language that is made up of a core set of commands and extended on a per-application basis to be able to work directly with objects in that application. And because of this it is sometimes also called as a hosted language.

Visual Basic for Applications is bundled with office applications (host application) so that it can be used as medium for accessing and interacting with the host applications object model. This means that, Excel VBA, knows about things like workbooks, worksheets, cells and charts, but Word VBA doesn’t knows about such things. Instead Word VBA understand terms like documents, bookmarks etc., things that are more related to Microsoft Word.

Is there any difference between a VBA Program and Macro?

I have seen many people confusing between VBA and Macro language. But a Macro language is very much different from a VBA. Macros were used with the older versions of office applications and they could only be used for automating instructions.

In fact, the first spreadsheet macro programs were just shortcuts for the user interface commands. For example, if in the user interface you typed R (for “Range”), N (for “Name”), and C (for “Create”), you would enter RNC into the macro to automate the process.

This approach was intuitive, but it also had integral weaknesses. Because of such weaknesses, VBA later in 1993 replaced this Macro Language, and hence there is still a misconception among people to call VBA as macro language.

Visual Basic for Applications when compared to traditional Macro Language is more powerful and sophisticated and hence it was an instant success.

Why learning Excel VBA is so important?

As you become familiar with Excel, you will notice that although Excel provides you large number of tools, but still it doesn’t have everything that you need to perform your daily tasks. Such tasks may include creating custom functions, repetitive instructions, automating tasks etc.

And hence Microsoft has provided VBA as a gap filler; that allows users to write their own methods or commands to perform their tasks.

After having enough experience with VBA programming in Excel you will never ever get stuck during your tasks due to a lack of built-in tools. Using Visual Basic for Applications you will be able to write your own function and commands whenever you feel the need to write one.

What all you can do with Excel VBA?

With Excel VBA you can do a lot of things in Excel. I have enlisted few of them below:

  • You can automate the tasks that you have to do frequently.
  • You can create a custom command in excel.
  • You can repeat a set of instructions multiple times.
  • You can create custom function popularly called as User Defined Function (UDF)
  • You can create a custom add in in Excel.

Subscribe and be a part of our 15,000+ member family!

Now subscribe to Excel Trick and get a free copy of our ebook «200+ Excel Shortcuts» (printable format) to catapult your productivity.

Источник

Everybody in this country should learn how to program a computer... because it teaches you how to think." -Steve Jobs

I wish to extend the wise words of Steve Jobs and say everyone in the world should learn how to program a computer. You may not necessary end up working as a programmer or writing programs at all but it will teach you how to think.

In this VBA tutorial, we are going to cover the following topics.

  • What is Visual Basic for Applications (VBA)?
  • Why VBA?
  • Personal & Business Applications of VBA in Excel
  • Introduction to Visual Basic for Applications
  • Step by step example of creating a simple EMI calculator in Excel
  • How to use VBA in Excel Example

Visual Basic for Applications (VBA) is an event-driven programming language implemented by Microsoft to develop Office applications. VBA helps to develop automation processes, Windows API, and user-defined functions. It also enables you to manipulate the user interface features of the host applications.

Before we go into further details, let’s look at what computer programming is in a layman’s language. Assume you have a maid. If you want the maid to clean the house and do the laundry. You tell her what to do using let’s say English and she does the work for you. As you work with a computer, you will want to perform certain tasks. Just like you told the maid to do the house chores, you can also tell the computer to do the tasks for you.

The process of telling the computer what you want it to do for you is what is known as computer programming. Just as you used English to tell the maid what to do, you can also use English like statements to tell the computer what to do. The English like statements fall in the category of high level languages. VBA is a high level language that you can use to bend excel to your all powerful will.

VBA is actually a sub set of Visual Basic 6.0 BASIC stands for Beginners All-Purpose Symbolic Instruction Code.

Why VBA?

VBA enables you to use English like statements to write instructions for creating various applications. 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.

Personal & Business Applications of VBA in Excel

For personal use, you can use it for simple macros that will automate most of your routine tasks. Read the article on Macros for more information on how you can achieve this.

For business use, you can create complete powerful programs powered by excel and VBA. The advantage of this approach is you can leverage the powerful features of excel in your own custom programs.

Introduction to Visual Basic for Applications

Before we can write any code, we need to know the basics first. The following basics will help you get started.

  • Variable – in high school we learnt about algebra. Find (x + 2y) where x = 1 and y = 3. In this expression, x and y are variables. They can be assigned any numbers i.e. 1 and 3 respective as in this example. They can also be changed to say 4 and 2 respectively. Variables in short are memory locations. As you work with VBA Excel, you will be required to declare variables too just like in algebra classes
  • Rules for creating variables

    • Don’t use reserved words – if you work as a student, you cannot use the title lecturer or principal. These titles are reserved for the lecturers and the school authority. Reserved words are those words that have special meaning in Excel VBA and as such, you cannot use them as variable names.
    • Variable names cannot contain spaces – you cannot define a variable named first number. You can use firstNumber or first_number.
    • Use descriptive names – it’s very tempting to name a variable after yourself but avoid this. Use descriptive names i.e. quantity, price, subtotal etc. this will make your Excel VBA code easy to read
  • Arithmetic operators – The rules of Brackets of Division Multiplication Addition and Subtraction (BODMAS) apply so remember to apply them when working with expressions that use multiple different arithmetic operators. Just like in excel, you can use

    • + for addition
    • – for subtraction
    • * for multiplication
    • / for division.
  • Logical operators – The concept of logical operators covered in the earlier tutorials also apply when working with VBA. These include

    • If statements
    • OR
    • NOT
    • AND
    • TRUE
    • FALSE

How to Enable the Developer Tab

Below is the step by step process on how to enable the developer tab in Excel:

  • Create a new workbook
  • Click on the ribbon start button
  • Select options
  • Click on customize ribbon
  • Select the developer checkbox as shown in the image below
  • Click OK

Introduction to Macros in Excel

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

VBA Hello World!

Now we will demonstrate how to program in VBA programming language. All program in VBA has to start with “Sub” and end with “End sub”. Here the name is the name you want to assign to your program. While sub stands for a subroutine which we will learn in the later part of the tutorial.

Sub name()
.
.
. 
End Sub

We will create a basic VBA program that displays an input box to ask for the user’s name then display a greeting message

This tutorial assumes you have completed the tutorial on Macros in excel and have enabled the DEVELOPER tab in excel.

  • Create a new work book
  • Save it in an excel macro enabled worksheet format *.xlsm
  • Click on the DEVELOPER tab
  • Click on INSERT drop down box under controls ribbon bar
  • Select a command button as shown in the image below

Creating your First  Visual Basic for Applications (VBA) in Excel

Draw the command button anywhere on the worksheet

You will get the following dialogue window

Creating your First  Visual Basic for Applications (VBA) in Excel

  • Rename the macro name to btnHelloWorld_Click
  • Click on new button
  • You will get the following VBA code window

Creating your First  Visual Basic for Applications (VBA) in Excel

Enter the following instruction codes

Dim name As String
name = InputBox("Enter your name")
MsgBox "Hello " + name

HERE,

  • “Dim name as String” creates a variable called name. The variable will accept text, numeric and other characters because we defined it as a string
  • “name = InputBox(“Enter your name”)” calls the built in function InputBox that displays a window with the caption Enter your name. The entered name is then stored in the name variable.
  • MsgBox “Hello ” + name” calls the built in function MsgBox that display Hello and the entered name.

Your complete code window should now look as follows

Creating your First  Visual Basic for Applications (VBA) in Excel

  • Close the code window
  • Right click on button 1 and select edit text
  • Enter Say hello

Creating your First  Visual Basic for Applications (VBA) in Excel

  • Click on Say Hello
  • You will get the following input box

Creating your First  Visual Basic for Applications (VBA) in Excel

  • Enter your name i.e. Jordan
  • You will get the following message box

Creating your First  Visual Basic for Applications (VBA) in Excel

Congratulations, you just created your first VBA program in excel

Step by step example of creating a simple EMI calculator in Excel

In this tutorial exercise, we are going to create a simple program that calculates the EMI. EMI is the acronym for Equated Monthly Instalment. It’s the monthly amount that you repay when you get a loan. The following image shows the formula for calculating EMI.

Creating your First  Visual Basic for Applications (VBA) in Excel

The above formula is complex and can be written in excel. The good news is excel already took care of the above problem. You can use the PMT function to compute the above.

The PMT function works as follows

=PMT(rate,nper,pv)

HERE,

  • “rate” this is the monthly rate. It’s the interest rate divided by the number of payments per year
  • “nper” it is the total number of payments. It’s the loan term multiplied by number of payments per year
  • “pv” present value. It’s the actual loan amount

Create the GUI using excel cells as shown below

Creating your First  Visual Basic for Applications (VBA) in Excel

Add a command button between rows 7 and 8

Give the button macro name btnCalculateEMI_Click

Click on edit button

Enter the following code

Dim monthly_rate As Single, loan_amount As Double, number_of_periods As Single, emi As Double
monthly_rate = Range("B6").Value / Range("B5").Value
loan_amount = Range("B3").Value
number_of_periods = Range("B4").Value * Range("B5").Value 
emi = WorksheetFunction.Pmt(monthly_rate, number_of_periods, -loan_amount)
Range("B9").Value = emi

HERE,

  • “Dim monthly_rate As Single,…” Dim is the keyword that is used to define variables in VBA, monthly_rate is the variable name, Single is the data type that means the variable will accept number.
  • “monthly_rate = Range(“B6”).Value / Range(“B5″).Value” Range is the function used to access excel cells from VBA, Range(“B6”).Value makes reference to the value in B6
  • “WorksheetFunction.Pmt(…)” WorksheetFunction is the function used to access all the functions in excel

The following image shows the complete source code

Creating your First  Visual Basic for Applications (VBA) in Excel

  • Click on save and close the code window
  • Test your program as shown in the animated image below

Creating your First  Visual Basic for Applications (VBA) in Excel

How to use VBA in Excel Example

Following steps will explain how to use VBA in Excel.

Step 1) Open your VBA editor

Under Developer tab from the main menu, click on “Visual Basic” icon it will open your VBA editor.

What is VBA?

Step 2) Select the Excel sheet & Double click on the worksheet

It will open a VBA editor, from where you can select the Excel sheet where you want to run the code. To open VBA editor double click on the worksheet.

What is VBA?

It will open a VBA editor on the right-hand side of the folder. It will appear like a white space.

What is VBA?

Step 3) Write anything you want to display in the MsgBox

In this step we are going to see our first VBA program. To read and display our program we need an object. In VBA that object or medium in a MsgBox.

  • First, write “Sub” and then your “program name” (Guru99)
  • Write anything you want to display in the MsgBox (guru99-learning is fun)
  • End the program by End Sub

What is VBA?

Step 4) Click on the green run button on top of the editor

In next step you have to run this code by clicking on the green run button on top of the editor menu.

What is VBA?

Step 5) Select the sheet and click on “Run” button

When you run the code, another window will pops out. Here you have to select the sheet where you want to display the program and click on “Run” button

What is VBA?

Step 6) Display the msg in MsgBox

When you click on Run button, the program will get executed. It will display the msg in MsgBox.

What is VBA?

Download the above Excel Code

Summary

VBA Full Form : Visual Basic for Application. It’s a sub component of visual basic programming language that you can use to create applications in excel. With VBA, you can still take advantage of the powerful features of excel and use them in VBA.

The first step to working with VBA in Excel is to get yourself familiarized with the Visual Basic Editor (also called the VBA Editor or VB Editor).

In this tutorial, I will cover all there is to know about the VBA Editor and some useful options that you should know when coding in Excel VBA.

What is Visual Basic Editor in Excel?

Visual Basic Editor is a separate application that is a part of Excel and opens whenever you open an Excel workbook. By default, it’s hidden and to access it, you need to activate it.

VB Editor is the place where you keep the VB code.

There are multiple ways you get the code in the VB Editor:

  1. When you record a macro, it automatically creates a new module in the VB Editor and inserts the code in that module.
  2. You can manually type VB code in the VB editor.
  3. You can copy a code from some other workbook or from the internet and paste it in the VB Editor.

Opening the VB Editor

There are various ways to open the Visual Basic Editor in Excel:

  1. Using a Keyboard Shortcut (easiest and fastest)
  2. Using the Developer Tab.
  3. Using the Worksheet Tabs.

Let’s go through each of these quickly.

Keyboard Shortcut to Open the Visual Basic Editor

The easiest way to open the Visual Basic editor is to use the keyboard shortcut – ALT + F11 (hold the ALT key and press the F11 key).

Keyboard Shortcut to open Visual Basic Editor in Excel

As soon as you do this, it will open a separate window for the Visual Basic editor.

This shortcut works as a toggle, so when you use it again, it will take you back to the Excel application (without closing the VB Editor).

The shortcut for the Mac version is Opt + F11 or Fn + Opt + F11

Using the Developer Tab

To open the Visual Basic Editor from the ribbon:

  1. Click the Developer tab (if you don’t see a developer tab, read this on how to get it).
  2. In the Code group, click on Visual Basic.

Visual Basic Editor button in the ribbon

Using the Worksheet Tab

This is a less used method to open the Vb Editor.

Go to any of the worksheet tabs, right-click, and select ‘View Code’.

View code to open the VB Editor

This method wouldn’t just open the VB Editor, it will also take you to the code window for that worksheet object.

This is useful when you want to write code that works only for a specific worksheet. This is usually the case with worksheet events.

Anatomy of the Visual Basic Editor in Excel

When you open the VB Editor for the first time, it may look a bit overwhelming.

There are different options and sections that may seem completely new at first.

Also, it still has an old Excel 97 days look. While Excel has improved tremendously in design and usability over the years, the VB Editor has not seen any change in the way it looks.

In this section, I will take you through the different parts of the Visual Basic Editor application.

Note: When I started using VBA years ago, I was quite overwhelmed with all these new options and windows. But as you get used to working with VBA, you would get comfortable with most of these. And most of the time, you’ll not be required to use all the options, only a hand full.

Below is an image of the different components of the VB Editor. These are then described in detail in the below sections of this tutorial.

Different Parts of the VB Editor in Excel

Now let’s quickly go through each of these components and understand what it does:

Menu Bar

This is where you have all the options that you can use in the VB Editor. It is similar to the Excel ribbon where you have tabs and options with each tab.

You can explore the available options by clicking on each of the menu element.

You will notice that most of the options in VB Editor have keyboard shortcuts mentioned next to it. Once you get used to a few keyboard shortcuts, working with the VB Editor becomes really easy.

Tool Bar

By default, there is a toolbar in the VB Editor which has some useful options that you’re likely to need most often. This is just like the Quick Access Toolbar in Excel. It gives you quick access to some of the useful options.

You can customize it a little by removing or adding options to it (by clicking on the small downward pointing arrow at the end of the toolbar).

Add or Remove options in the toolbar

In most cases, the default toolbar is all you need when working with the VB Editor.

You can move the toolbar above the menu bar by clicking on the three gray dots (at the beginning of the toolbar) and dragging it above the menu bar.

Note: There are four toolbars in the VB Editor – Standard, Debug, Edit, and User form. What you see in the image above (which is also the default) is the standard toolbar. You can access other toolbars by going to the View option and hovering the cursor on the Toolbars option. You can add one or more toolbars to the VB Editor if you want.

Project Explorer

Project Explorer is a window on the left that shows all the objects currently open in Excel.

When you’re working with Excel, every workbook or add-in that is open is a project. And each of these projects can have a collection of objects in it.

For example, in the below image, the Project Explorer shows the two workbooks that are open (Book1 and Book2) and the objects in each workbook (worksheets, ThisWorkbook, and Module in Book1).

There is a plus icon to the left of objects that you can use to collapse the list of objects or expand and see the complete list of objects.

Project Explorer in Excel VBA Editor

The following objects can be a part of the Project Explorer:

  1. All open Workbooks – within each workbook (which is also called a project), you can have the following objects:
    • Worksheet object for each worksheet in the workbook
    • ThisWorkbook object which represents the workbook itself
    • Chartsheet object for each chart sheet (these are not as common as worksheets)
    • Modules – This is where the code that is generated with a macro recorder goes. You can also write or copy-paste VBA code here.
  2. All open Add-ins

Consider the Project Explorer as a place that outlines all the objects open in Excel at the given time.

The keyboard shortcut to open the Project Explorer is Control + R (hold the control key and then press R). To close it, simply click the close icon at the top right of the Project Explorer window.

Note: For every object in Project Explorer, there is a code window in which you can write the code (or copy and paste it from somewhere). The code window appears when you double click on the object.

Properties Window

Properties window is where you get to see the properties of the select object. If you don’t have the Properties window already, you can get it by using the keyboard shortcut F4 (or go to the View tab and click Properties window).

Properties window is a floating window which you can dock in the VB Editor. In the below example, I have docked it just below the Project Explorer.

Properties Window is docked below Project Explorer

Properties window allows us to change the properties of a selected object. For example, if I want to make a worksheet hidden (or very hidden), I can do that by changing the Visible Property of the selected worksheet object.

Changing the Visible Property of the Worksheet in Properties Window

Related: Hiding a Worksheet in Excel (that can not be un-hidden easily)

Code Window

There is a code window for each object that is listed in the Project Explorer. You can open the code window for an object by double-clicking on it in the Project Explorer area.

Code window is where you’ll write your code or copy paste a code from somewhere else.

When you record a macro, the code for it goes into the code window of a module. Excel automatically inserts a module to place the code in it when recording a macro.

Related: How to Run a Macro (VBA Code) in Excel.

Immediate Window

The Immediate window is mostly used when debugging code. One way I use the Immediate window is by using a Print.Debug statement within the code and then run the code.

It helps me to debug the code and determine where my code gets stuck. If I get the result of Print.Debug in the immediate window, I know the code worked at least till that line.

If you’re new to VBA coding, it may take you some time to be able to use the immediate window for debugging.

By default, the immediate window is not visible in the VB Editor. You can get it by using the keyboard shortcut Control + G (or can go to the View tab and click on ‘Immediate Window’).

Where to Add Code in the VB Editor

I hope you now have a basic understanding of what VB Editor is and what all parts it has.

In this section of this tutorial, I will show you where to add a VBA code in the Visual Basic Editor.

There are two places where you can add the VBA code in Excel:

  1. The code window for an object. These objects can be a workbook, worksheet, User Form, etc.
  2. The code window of a module.

Module Code Window Vs Object Code Window

Let me first quickly clear the difference between adding a code in a module vs adding a code in an object code window.

When you add a code to any of the objects, it’s dependent on some action of that object that will trigger that code. For example, if you want to unhide all the worksheets in a workbook as soon as you open that workbook, then the code would go in the ThisWorkbook object (which represents the workbook).

The trigger, in this case, is opening the workbook.

Similarly, if you want to protect a worksheet as soon as some other worksheet is activated, the code for that would go in the worksheet code window.

These triggers are called events and you can associate a code to be executed when an event occurs.

Related: Learn more about Events in VBA.

On the contrary, the code in the module needs to be executed either manually (or it can be called from other subroutines as well).

When you record a macro, Excel automatically creates a module and inserts the recorded macro code in it. Now if you have to run this code, you need to manually execute the macro.

Adding VBA Code in Module

While recording a macro automatically creates a module and inserts the code in it, there are some limitations when using a macro recorder. For example, it can not use loops or If Then Else conditions.

In such cases, it’s better to either copy and paste the code manually or write the code yourself.

A module can be used to hold the following types of VBA codes:

  1. Declarations: You can declare variables in a module. Declaring variables allows you to specify what type of data a variable can hold. You can declare a variable for a sub-routine only or for all sub-routines in the module (or all modules)
  2. Subroutines (Procedures): This is the code that has the steps you want VBA to perform.
  3. Function Procedures: This is a code that returns a single value and you can use it to create custom functions (also called User Defined Functions or UDFs in VBA)

By default, a module is not a part of the workbook. You need to insert it first before using it.

Adding a Module in the VB Editor

Below are the steps to add a module:

  1. Right-click on any object of the workbook (in which you want the module).Right click on any object
  2. Hover the cursor on the Insert option.
  3. Click on Module.Click on Module

This would instantly create a folder called Module and insert an object called Module 1. If you already have a module inserted, the above steps would insert another module.

Inserted Module in the VB Editor

Once the module is inserted, you can double click on the module object in the Project Explorer and it will open the code window for it.

Now you can copy-paste the code or write it yourself.

Removing the Module

Below are the steps to remove a module in Excel VBA:

  1. Right-click on the module that you want to remove.
  2. Click on Remove Module option.Remove Module for a Project in the VB Editor
  3. In the dialog box that opens, click on No.Prompt before a module is deleted

Note: You can export a module before removing it. It gets saved as a .bas file and you can import it in some other project. To export a module, right-click on the module and click on ‘Export file’.

Adding Code to the Object Code Window

To open the code window for an object, simply double-click on it.

When it opens, you can enter the code manually or copy-paste the code from other modules or from the internet.

Note that some of the objects allow you to choose the event for which you want to write the code.

For example, if you want to write a code for something to happen when selection is changed in the worksheet, you need to first select worksheets from the drop-down at the top left of the code window and then select the change event from the drop-down on the right.

Selection Change Event in VBA Code Window

Note: These events are specific to the object. When you open the code window for a workbook, you will see the events related to the workbook object. When you open the code window for a worksheet, you will see the events related to the worksheet object.

Customizing the VB Editor

While the default settings of the Visual Basic Editor are good enough for most users, it does allow you to further customize the interface and a few functionalities.

In this section of the tutorial, I will show you all the options you have when customizing the VB Editor.

To customize the VB Editor environment, click Tools in the menu bar and then click on Options.

This would open the Options dialog box which will give you all the customization options in the VB Editor. The ‘Options’ dialog box has four tabs (as shown below) that have various customizations options for the Visual Basic Editor.

Options to customize the Vb Editor

Let’s quickly go through each of these tabs and the important options in each.

Editor Tab

While the inbuilt settings work fine in most cases, let me still go through the options in this tab.

As you get more proficient working with VBA in Excel, you may want to customize the VB Editor using some of these options.

Auto Syntax Check

When working with VBA in Excel, as soon as you make a syntax error, you will be greeted by a pop-up dialog box (with some description about the error). Something as shown below:

Auto Syntax Check in Visual Basic Editor Options

If you disable this option, this pop-up box will not appear even when you make a syntax error. However, there would be a change in color in the code text to indicate that there is an error.

If you’re a beginner, I recommend you keep this option enabled. As you get more experienced with coding, you may start finding these pop-up boxes irritating, and then you can disable this option.

Require Variable Declaration

This is one option I recommend enabling.

When you’re working with VBA, you would be using variables to hold different data types and objects.

When you enable this option, it automatically inserts the ‘Option Explicit’ statement at the top of the code window. This forces you to declare all the variables that you’re using in your code. If you don’t declare a variable and try to execute the code, it will show an error (as shown below).

Varibale Not Declared Error in Excel VBA

In the above case, I used the variable Var, but I didn’t declare it. So when I try to run the code, it shows an error.

This option is quite useful when you have a lot of variables. It often helps me find misspelled variables names as they are considered as undeclared and an error is shown.

Note: When you enable this option, it does not impact the existing modules.

Auto List Member

This option is quite useful as it helps you get a list of properties of methods for an object.

For example, if I want to delete a worksheet (Sheet1), I need to use the line Sheet1.Delete.

While I am typing the code, as soon as I type the dot, it will show me all the methods and properties associated with the Worksheet object (as shown below).

Autolist Member Option in VB Editor

Auto list feature is great as it allows you to:

  • Quickly select the property and method from the list and saves time
  • Shows you all the properties and methods which you may not be aware of
  • Avoid making spelling errors

This option is enabled by default and I recommend keeping it that way.

Auto Quick Info Options

When you type a function in Excel worksheet, it shows you some information about the function – such as the arguments it takes.

Similarly, when you type a function in VBA, it shows you some information (as shown below). But for that to happen, you need to make sure the Auto Quick Info option is enabled (which it is by default).

Auto Quick Info Option in VB Editor

Auto Data Tips Options

When you’re going through your code line by line and place your cursor above a variable name, it will show you the value of the variable.

I find it quite useful when debugging the code or going through the code line by line which has loops in it.

Auto Data Tips Option in Visual Basic Editor Options

In the above example, as soon as I put the cursor over the variable (var), it shows the value it holds.

This option is enabled by default and I recommend you keep it that way.

Auto Indent

Since VBA codes can get long and messy, using indentation increases the readability of the code.

When writing code, you can indent using the tab key.

This option ensures that when you are done with the indented line and hit enter, the next line doesn’t start from the very beginning, but has the same indentation as the previous line.

Indentation enabled in the VB Editor code windows

In the above example, after I write the Debug.Print line and hit enter, it will start right below it (with the same indentation level).

I find this option useful and turning this off would mean manually indenting each line in a block of code that I want indented.

You can change the indentation value if you want. I keep it at the default value.

Drag and Drop Text Editing

When this option is enabled, it allows you to select a block of code and drag and drop it.

It saves time as you don’t have to first cut and then paste it. You can simply select and drag it.

This option is enabled by default and I recommend you keep it that way.

Default to Full Module View

When this option is enabled, you will be able to see all the procedures in a module in one single scrollable list.

If you disable this option, you will only be able to see one module at a time. You will have to make a selection of the module you want to see from the drop-down at the top right of the code window.

This option is enabled by default and I recommend keeping it that way.

One reason you may want to disable it when you have multiple procedures that are huge and scrolling across these is taking time, or when you have a lot of procedures and you want to quickly find it instead of wasting time in scrolling.

Procedure Separator

When this option is enabled, you will see a line (a kind of divider) between two procedures.

I find this useful as it visually shows when one procedure ends and the other one starts.

Procedure Separator Option in VB Editor

It’s enabled by default and I recommend keeping it that way.

Editor Format Tab

With the options in the Editor Format tab, you can customize the way your code looks in the code window.

Personally, I keep all the default options as I am fine with it. If you want, you can tweak this based on your preference.

To make a change, you need to first select an option in the Code Colors box. Once an option is selected, you can modify the foreground, background, and indicator color for it.

The font type and font size can also be set in this tab. It’s recommended to use a fixed-width font such as Courier New, as it makes the code more readable.

Note that the font type and size setting will remain the same for all code types (i.e., all the code types shown in the code color box).

Below is an image where I have selected Breakpoint, and I can change the formatting of it.

Editor Format Options in VB Editor

Note: The Margin Indicator Bar option when enabled shows a little margin bar to the left of the code. It’s helpful as it shows useful indicators when executing the code. In the above example, when you set a breakpoint, it will automatically show a red dot to the left of the line in the margin bar. Alternatively, to set a breakpoint, you can simply click on the margin bar on the left of the code line that you want as the breakpoint.

By default, Margin Indicator Bar is enabled and I recommend keeping it that way.

One of my VBA course students found this customization options useful and she was color blind. Using the options here, she was able to set the color and formats that made it easy for her to work with VBA.

General Tab

The General tab has many options but you don’t need to change any of it.

I recommend you keep all the options as is.

One important option to know about in this tab is Error Handling.

By default, ‘Break on Unhandled Errors’ is selected and I recommend keeping it that way.

This option means that if your code encounters an error, and you have not handled that error in your code already, then it will break and stop. But if you have addressed the error (such as by using On Error Resume Next or On Error Goto options), then it will not break (as the errors are not unhandled).

Docking Tab

In this tab, you can specify which windows you want to get docked.

Docking means that you can fix the position of a window (such as project explorer or the Properties window) so that it doesn’t float around and you can view all the different windows at the same time.

If you don’t dock, you will be able to view one window at a time in full-screen mode and will have to switch to the other one.

I recommend keeping the default settings.

Other Excel tutorials you may like:

  • How to Remove Macros From an Excel Workbook
  • Comments in Excel VBA (Add, Remove, Block Commenting)
  • Using Active Cell in VBA in Excel (Examples)

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

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

What is VBA used for in Excel?

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

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

How do I start with VBA in Excel?

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

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

How can I access VBA code?

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

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

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

What can VBA do?

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

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

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

An example of a loop

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

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

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

Are VB and VBA the same?

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

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

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

What is the difference between a macro and VBA?

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

VBA Coding Made Easy

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

automacro

Learn More

What is the difference between a macro and a script?

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

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

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

What does a VBA Developer do?

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

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

Why is VBA important?

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

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

VBA Programming | Code Generator does work for you!

Is VBA a good programming language?

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

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

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

Is VBA object-oriented?

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

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

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

Понравилась статья? Поделить с друзьями:
  • What is excel 365
  • What is excel 2010 starter
  • What is etymology of the word science
  • What is error checking in excel
  • What is error 2015 in excel vba