Working with vba in excel

Время на прочтение
7 мин

Количество просмотров 312K

Приветствую всех.

В этом посте я расскажу, что такое VBA и как с ним работать в Microsoft Excel 2007/2010 (для более старых версий изменяется лишь интерфейс — код, скорее всего, будет таким же) для автоматизации различной рутины.

VBA (Visual Basic for Applications) — это упрощенная версия Visual Basic, встроенная в множество продуктов линейки Microsoft Office. Она позволяет писать программы прямо в файле конкретного документа. Вам не требуется устанавливать различные IDE — всё, включая отладчик, уже есть в Excel.

Еще при помощи Visual Studio Tools for Office можно писать макросы на C# и также встраивать их. Спасибо, FireStorm.

Сразу скажу — писать на других языках (C++/Delphi/PHP) также возможно, но требуется научится читать, изменять и писать файлы офиса — встраивать в документы не получится. А интерфейсы Microsoft работают через COM. Чтобы вы поняли весь ужас, вот Hello World с использованием COM.

Поэтому, увы, будем учить Visual Basic.

Чуть-чуть подготовки и постановка задачи

Итак, поехали. Открываем Excel.

Для начала давайте добавим в Ribbon панель «Разработчик». В ней находятся кнопки, текстовые поля и пр. элементы для конструирования форм.

Появилась вкладка.

Теперь давайте подумаем, на каком примере мы будем изучать VBA. Недавно мне потребовалось красиво оформить прайс-лист, выглядевший, как таблица. Идём в гугл, набираем «прайс-лист» и качаем любой, который оформлен примерно так (не сочтите за рекламу, пожалуйста):

То есть требуется, чтобы было как минимум две группы, по которым можно объединить товары (в нашем случае это будут Тип и Производитель — в таком порядке). Для того, чтобы предложенный мною алгоритм работал корректно, отсортируйте товары так, чтобы товары из одной группы стояли подряд (сначала по Типу, потом по Производителю).

Результат, которого хотим добиться, выглядит примерно так:

Разумеется, если смотреть прайс только на компьютере, то можно добавить фильтры и будет гораздо удобнее искать нужный товар. Однако мы хотим научится кодить и задача вполне подходящая, не так ли?

Кодим

Для начала требуется создать кнопку, при нажатии на которую будет вызываться наша програма. Кнопки находятся в панели «Разработчик» и появляются по кнопке «Вставить». Вам нужен компонент формы «Кнопка». Нажали, поставили на любое место в листе. Далее, если не появилось окно назначения макроса, надо нажать правой кнопкой и выбрать пункт «Назначить макрос». Назовём его FormatPrice. Важно, чтобы перед именем макроса ничего не было — иначе он создастся в отдельном модуле, а не в пространстве имен книги. В этому случае вам будет недоступно быстрое обращение к выделенному листу. Нажимаем кнопку «Новый».

И вот мы в среде разработки VB. Также её можно вызвать из контекстного меню командой «Исходный текст»/«View code».

Перед вами окно с заглушкой процедуры. Можете его развернуть. Код должен выглядеть примерно так:

Sub FormatPrice()End Sub

Напишем Hello World:

Sub FormatPrice()
    MsgBox "Hello World!"
End Sub

И запустим либо щелкнув по кнопке (предварительно сняв с неё выделение), либо клавишей F5 прямо из редактора.

Тут, пожалуй, следует отвлечься на небольшой ликбез по поводу синтаксиса VB. Кто его знает — может смело пропустить этот раздел до конца. Основное отличие Visual Basic от Pascal/C/Java в том, что команды разделяются не ;, а переносом строки или двоеточием (:), если очень хочется написать несколько команд в одну строку. Чтобы понять основные правила синтаксиса, приведу абстрактный код.

Примеры синтаксиса

' Процедура. Ничего не возвращает
' Перегрузка в VBA отсутствует
Sub foo(a As String, b As String)
    ' Exit Sub ' Это значит "выйти из процедуры"
    MsgBox a + ";" + b
End Sub' Функция. Вовращает Integer
Function LengthSqr(x As Integer, y As IntegerAs Integer
    ' Exit Function
    LengthSqr = x * x + y * y
End FunctionSub FormatPrice()
    Dim s1 As String, s2 As String
    s1 = "str1"
    s2 = "str2"
    If s1 <> s2 Then
        foo "123""456" ' Скобки при вызове процедур запрещены
    End IfDim res As sTRING ' Регистр в VB не важен. Впрочем, редактор Вас поправит
    Dim i As Integer
    ' Цикл всегда состоит из нескольких строк
    For i = 1 To 10
        res = res + CStr(i) ' Конвертация чего угодно в String
        If i = 5 Then Exit For
    Next iDim x As Double
    x = Val("1.234"' Парсинг чисел
    x = x + 10
    MsgBox xOn Error Resume Next ' Обработка ошибок - игнорировать все ошибки
    x = 5 / 0
    MsgBox xOn Error GoTo Err ' При ошибке перейти к метке Err
    x = 5 / 0
    MsgBox "OK!"
    GoTo ne

Err:
    MsgBox 

"Err!"

ne:

On Error GoTo 0 ' Отключаем обработку ошибок

    ' Циклы бывает, какие захотите
    Do While True
        Exit DoLoop 'While True
    Do 'Until False
        Exit Do
    Loop Until False
    ' А вот при вызове функций, от которых хотим получить значение, скобки нужны.
    ' Val также умеет возвращать Integer
    Select Case LengthSqr(Len("abc"), Val("4"))
    Case 24
        MsgBox "0"
    Case 25
        MsgBox "1"
    Case 26
        MsgBox "2"
    End Select' Двухмерный массив.
    ' Можно также менять размеры командой ReDim (Preserve) - см. google
    Dim arr(1 to 10, 5 to 6) As Integer
    arr(1, 6) = 8Dim coll As New Collection
    Dim coll2 As Collection
    coll.Add "item""key"
    Set coll2 = coll ' Все присваивания объектов должны производится командой Set
    MsgBox coll2("key")
    Set coll2 = New Collection
    MsgBox coll2.Count
End Sub

Грабли-1. При копировании кода из IDE (в английском Excel) есь текст конвертируется в 1252 Latin-1. Поэтому, если хотите сохранить русские комментарии — надо сохранить крокозябры как Latin-1, а потом открыть в 1251.

Грабли-2. Т.к. VB позволяет использовать необъявленные переменные, я всегда в начале кода (перед всеми процедурами) ставлю строчку Option Explicit. Эта директива запрещает интерпретатору заводить переменные самостоятельно.

Грабли-3. Глобальные переменные можно объявлять только до первой функции/процедуры. Локальные — в любом месте процедуры/функции.

Еще немного дополнительных функций, которые могут пригодится: InPos, Mid, Trim, LBound, UBound. Также ответы на все вопросы по поводу работы функций/их параметров можно получить в MSDN.

Надеюсь, что этого Вам хватит, чтобы не пугаться кода и самостоятельно написать какое-нибудь домашнее задание по информатике. По ходу поста я буду ненавязчиво знакомить Вас с новыми конструкциями.

Кодим много и под Excel

В этой части мы уже начнём кодить нечто, что умеет работать с нашими листами в Excel. Для начала создадим отдельный лист с именем result (лист с данными назовём data). Теперь, наверное, нужно этот лист очистить от того, что на нём есть. Также мы «выделим» лист с данными, чтобы каждый раз не писать длинное обращение к массиву с листами.

Sub FormatPrice()
    Sheets("result").Cells.Clear
    Sheets("data").Activate
End Sub

Работа с диапазонами ячеек

Вся работа в Excel VBA производится с диапазонами ячеек. Они создаются функцией Range и возвращают объект типа Range. У него есть всё необходимое для работы с данными и/или оформлением. Кстати сказать, свойство Cells листа — это тоже Range.

Примеры работы с Range

Sheets("result").Activate
Dim r As Range
Set r = Range("A1")
r.Value = "123"
Set r = Range("A3,A5")
r.Font.Color = vbRed
r.Value = "456"
Set r = Range("A6:A7")
r.Value = "=A1+A3"

Теперь давайте поймем алгоритм работы нашего кода. Итак, у каждой строчки листа data, начиная со второй, есть некоторые данные, которые нас не интересуют (ID, название и цена) и есть две вложенные группы, к которым она принадлежит (тип и производитель). Более того, эти строки отсортированы. Пока мы забудем про пропуски перед началом новой группы — так будет проще. Я предлагаю такой алгоритм:

  1. Считали группы из очередной строки.
  2. Пробегаемся по всем группам в порядке приоритета (вначале более крупные)
    1. Если текущая группа не совпадает, вызываем процедуру AddGroup(i, name), где i — номер группы (от номера текущей до максимума), name — её имя. Несколько вызовов необходимы, чтобы создать не только наш заголовок, но и всё более мелкие.
  3. После отрисовки всех необходимых заголовков делаем еще одну строку и заполняем её данными.

Для упрощения работы рекомендую определить следующие функции-сокращения:

Function GetCol(Col As IntegerAs String
    GetCol = Chr(Asc("A") + Col)
End FunctionFunction GetCellS(Sheet As String, Col As Integer, Row As IntegerAs Range
    Set GetCellS = Sheets(Sheet).Range(GetCol(Col) + CStr(Row))
End FunctionFunction GetCell(Col As Integer, Row As IntegerAs Range
    Set GetCell = Range(GetCol(Col) + CStr(Row))
End Function

Далее определим глобальную переменную «текущая строчка»: Dim CurRow As Integer. В начале процедуры её следует сделать равной единице. Еще нам потребуется переменная-«текущая строка в data», массив с именами групп текущей предыдущей строк. Потом можно написать цикл «пока первая ячейка в строке непуста».

Глобальные переменные

Option Explicit ' про эту строчку я уже рассказывал
Dim CurRow As Integer
Const GroupsCount As Integer = 2
Const DataCount As Integer = 3

FormatPrice

Sub FormatPrice()
    Dim I As Integer ' строка в data
    CurRow = 1
    Dim Groups(1 To GroupsCount) As String
    Dim PrGroups(1 To GroupsCount) As String

    Sheets(

"data").Activate
    I = 2
    Do While True
        If GetCell(0, I).Value = "" Then Exit Do
        ' ...
        I = I + 1
    Loop
End Sub

Теперь надо заполнить массив Groups:

На месте многоточия

Dim I2 As Integer
For I2 = 1 To GroupsCount
    Groups(I2) = GetCell(I2, I)
Next I2
' ...
For I2 = 1 To GroupsCount ' VB не умеет копировать массивы
    PrGroups(I2) = Groups(I2)
Next I2
I =  I + 1

И создать заголовки:

На месте многоточия в предыдущем куске

For I2 = 1 To GroupsCount
    If Groups(I2) <> PrGroups(I2) Then
        Dim I3 As Integer
        For I3 = I2 To GroupsCount
            AddHeader I3, Groups(I3)
        Next I3
        Exit For
    End If
Next I2

Не забудем про процедуру AddHeader:

Перед FormatPrice

Sub AddHeader(Ty As Integer, Name As String)
    GetCellS("result", 1, CurRow).Value = Name
    CurRow = CurRow + 1
End Sub

Теперь надо перенести всякую информацию в result

For I2 = 0 To DataCount - 1
    GetCellS("result", I2, CurRow).Value = GetCell(I2, I)
Next I2

Подогнать столбцы по ширине и выбрать лист result для показа результата

После цикла в конце FormatPrice

Sheets("Result").Activate
Columns.AutoFit

Всё. Можно любоваться первой версией.

Некрасиво, но похоже. Давайте разбираться с форматированием. Сначала изменим процедуру AddHeader:

Sub AddHeader(Ty As Integer, Name As String)
    Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow)).Merge
    ' Чтобы не заводить переменную и не писать каждый раз длинный вызов
    ' можно воспользоваться блоком With
    With GetCellS("result", 0, CurRow)
        .Value = Name
        .Font.Italic = True
        .Font.Name = "Cambria"
        Select Case Ty
        Case 1 ' Тип
            .Font.Bold = True
            .Font.Size = 16
        Case 2 ' Производитель
            .Font.Size = 12
        End Select
        .HorizontalAlignment = xlCenter
    End With
    CurRow = CurRow + 1
End Sub

Уже лучше:

Осталось только сделать границы. Тут уже нам требуется работать со всеми объединёнными ячейками, иначе бордюр будет только у одной:

Поэтому чуть-чуть меняем код с добавлением стиля границ:

Sub AddHeader(Ty As Integer, Name As String)
    With Sheets("result").Range("A" + CStr(CurRow) + ":C" + CStr(CurRow))
        .Merge
        .Value = Name
        .Font.Italic = True
        .Font.Name = "Cambria"
        .HorizontalAlignment = xlCenterSelect Case Ty
        Case 1 ' Тип
            .Font.Bold = True
            .Font.Size = 16
            .Borders(xlTop).Weight = xlThick
        Case 2 ' Производитель
            .Font.Size = 12
            .Borders(xlTop).Weight = xlMedium
        End Select
        .Borders(xlBottom).Weight = xlMedium ' По убыванию: xlThick, xlMedium, xlThin, xlHairline
    End With
    CurRow = CurRow + 1
End Sub

Осталось лишь добится пропусков перед началом новой группы. Это легко:

В начале FormatPrice

Dim I As Integer ' строка в  data
CurRow = 0 ' чтобы не было пропуска в самом начале
Dim Groups(1 To GroupsCount) As String

В цикле расстановки заголовков

If Groups(I2) <> PrGroups(I2) Then
    CurRow = CurRow + 1
    Dim I3 As Integer

В точности то, что и хотели.

Надеюсь, что эта статья помогла вам немного освоится с программированием для Excel на VBA. Домашнее задание — добавить заголовки «ID, Название, Цена» в результат. Подсказка: CurRow = 0 CurRow = 1.

Файл можно скачать тут (min.us) или тут (Dropbox). Не забудьте разрешить исполнение макросов. Если кто-нибудь подскажет человеческих файлохостинг, залью туда.

Спасибо за внимание.

Буду рад конструктивной критике в комментариях.

UPD: Перезалил пример на Dropbox и min.us.

UPD2: На самом деле, при вызове процедуры с одним параметром скобки можно поставить. Либо использовать конструкцию Call Foo(«bar», 1, 2, 3) — тут скобки нужны постоянно.

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)

VBA (Visual Basic for Applications) is a programming language that empowers you to automate almost every in Excel. With VBA, you can refer to the Excel Objects and use the properties, methods, and events associated with them. For example, you can create a pivot table, insert a chart, and show a message box to the user using a macro.

what-is-vba

The crazy thing is:

For all the tasks which you perform manually in minutes, VBA can do it in seconds, with a single click, with the same accuracy. Even you can write VBA codes that can run automatically when you open a document, a workbook, or even at a specific time.

Let me show you a real-life example:

Every morning when I go to the office, the first thing I need to do is to create a pivot table for the month-to-date sales and present it to my boss. This includes the same steps, every day. But when I realized that I can use VBA to create a pivot table and insert it in a single click, it saved me 5 minutes every day.

Macro Codes To Create A Pivot Table

Note: VBA is one of the Advanced Excel Skills.

How VBA Works

VBA is an Object-Oriented Language and as an object-oriented language, in VBA, we structure our codes in a way where we are using objects and then defining their properties.

In simple words, first, we define the object and then the activity which we want to perform. There are objects, collections, methods, and properties which you can use in VBA to write your code.

how-vba-works

[icon name=”bell” class=””] Don’t miss this: Let’s say you want to tell someone to open a box. The words you will use would be “Open the Box”. It’s plain English, Right? But when it comes to VBA and writing a macro this will be:

Box.Open

As you can see, the above code is started with the box which is our object here, and then we have used the method “Open” for it. Let’s go a bit specific, let say if you want to open the box which is RED in color. And for this the code will be:

Boxes(“Red”).Open

In the above code, boxes are the collection, and open is the method. If you have multiple boxes we are defining a specific box here. Here’s another way:

Box(“Red”).Unlock = True

In the above code, again boxes are the collection, and Unlock is the property that is set to TRUE.

What is VBA used for in Excel?

In Excel, you can use VBA for different things. Here are a few:

  • Enter Data: You can enter data in a cell, range of cells. You can also copy and paste data from one section to another.
  • Task Automation: You can automate tasks that want you to spend a lot of time. The best example I can give is using a macro to create a pivot table.
  • Create a Custom Excel Function: With VBA, you can also create a Custom User Defined Function and use it in the worksheet.
  • Create Add-Ins: In Excel, you can convert your VBA codes into add-ins and share them with others as well.
  • Integrate with other Microsoft Applications: You can also integrate Excel with other Microsoft applications. Like, you can enter data into a text file.

Excel Programming Fundamentals

A procedure in VBA is a set of codes or a single line of code that performs a specific activity.

  1. SUB: Sub procedure can perform actions but doesn’t return a value (but you can use an object to get that value).
  2. Function: With the help of the Function procedure, you create your function, which you can use in the worksheet or the other SUB and FUNCTION procedures (See this: VBA Function).

2. Variables and Constants

You need variables and constants to use values in the code multiple times.

  • Variable: A Variable can store a value, it has a name, you need to define its data type, and you can change the value it stores. As the name suggests, “VARIABLE” has no fixed value. It is like a storage box that is stored in the system.
  • Constant:‌ A constant also can store a value, but you can’t change the value during the execution of the code.

3. Data Types

You need to declare the data type for VARIABLES and CONSTANTS.

define data type

When you specify the data type for a variable or a constant, it ensures the validity of your data. If you omit the data type, VBA applies the Variant data type to your variable (it’s the most flexible), VBA won’t guess what the data type should be.

Tip: VBA Option Explicit

4. Objects, Properties, and Methods

Visual Basic for Applications is an Object-Oriented language, and to make the best out of it; you need to understand Excel Objects.

The workbook you use in Excel has different objects, and with all those objects, there are several properties that you can access and methods that you can use.

5. Events

Whenever you do something in Excel, that’s an event: enter a value in a cell, insert a new worksheet, or insert a chart. Below is the classification of events based on the objects:

  1. Application Events: These are events that are associated with the Excel application itself.
  2. Workbook Events: These are events that are associated with the actions that happen in a workbook.
  3. Worksheet Events: These events are associated with the action that happens in a worksheet.
  4. Chart Events: These events are associated with the chart sheets (which are different from worksheets).
  5. Userform Events: These events are associated with the action that happens with a user form.
  6. OnTime Events: OnTime events are those which can trigger code at a particular point in time.
  7. OnKey Events: OnKey events are those which can trigger code when a particular key is pressed.

6. Range

The range object is the most common and popular way to refer to a range in your VBA codes. You need to refer to the cell address, let me tell you the syntax.

Worksheets(“Sheet1”).Range(“A1”)

7. Conditions

Just like any other programming language, you can also write codes to test conditions in VBA. It allows you to do it in two different ways.

  • IF THEN‌ ELSE‌: It’s an IF statement that you can use to test a condition and then run a line of code if that condition is TRUE. You can also write nesting conditions with it
  • SELEC‌T‌ CASE: In the select case, you can specify a condition and then different cases for outcomes to test to run different lines of code to run. It’s a little more structured than the IF statement.

8. VBA Loops

You can write codes that can repeat and re-repeat an action in VBA, and there are multiple ways that you can use to write code like this.

  • For Next: The best fit for using For Next is when you want to repeat a set of actions a fixed number of times.
  • For Each Next: It’s perfect to use when you want to loop through a group of objects from a collection of objects.
  • Do While Loop: The simple idea behind the Do While Loop is to perform an activity while a condition is true.
  • Do Until Loop: In the Do Until, VBA runs a loop and continues to run it if the condition is FALSE.

9. Input Box and Message Box

  • Input Box: The input Box is a function that shows an input box to the user and collects a response.
  • Message Box: Message Box helps you show a message to the user but, you have an option to add buttons to the message box to get the response of the user.

10. Errors

Excel has no luck when it comes to programming errors, and you have to deal with them, no matter what.

  1. Syntax Errors: It’s like typos that you do while writing codes, but VBA can help you by pointing out these errors.
  2. Compile Errors: It comes when you write code to perform an activity, but that activity is not valid.
  3. Runtime Errors: A RUNTIME error occurs at the time of executing the code. It stops the code and shows you the error dialog box.
  4. Logical Error: It’s not an error but a mistake while writing code and sometimes can give you nuts while finding and correcting them.

Write a Macro (VBA Program) in Excel

I have a strong belief that in the initial time when someone is starting programming in Excel, HE/SHE should write more and more codes from scratch. The more codes you write from scratch, the more you understand how VBA works.

But you need to start with writing simple codes instead of jumping into complex ones. That’s WHY I don’t want you to think about anything complex right now.

You can even write a macro code to create a pivot table, but right now, I don’t want you to think that far. Let’s think about an activity that you want to perform in your worksheet, and you can write code for it.

  1. Go to the Developer Tab and open the Visual Basic Editor from the “Visual Basic” button.
    1-visual-basic-button
  2. After that, insert a new module from the “Project Window” (Right-click ➢ Insert ➢ Module).
    2-insert-a-new-module
  3. After that, come to the code window and create a macro with the name “Enter Done” (we are creating a SUB procedure), just like I have below.
    3-code-window
  4. From here, you need to write a code which we have just discussed above. Hold for second and think like this: You need to specify the cell where you want to insert the value and then the value which you wish to enter.
  5. Enter the cell reference, and for this, you need to use RANGE object and specify the cell address in it, like below:
    4-cell-reference-range-object
  6. After that, enter a dot, and the moment you add a dot, you’ll have a list of properties that you can define and activities that you can do with the range.
    5-enter-a-dot
  7. From here, you need to select the “Value” property and set the text which you want to insert in the cell “A1” and when to do it, your code with look something like below.
    6-select-value
  8. Finally, above the line of code, enter the text (‘this code enters the value “Done” in the cell A5). It’s a VBA Comment that you can insert to define the line of code that you have written.
    7-enter-the-text-above-line-code
Sub Enter_Done()
'this code enters the value “Done” in the cell A5
Range("A1").Value = "Done"
End Sub

Let’s understand this…

You can split this code into two different parts.

  • In the FIRST part, we have specified the cell address by using the RANGE object. And, to refer to a cell using a range object you need to wrap the cell address with double quotes (you can also use square brackets).
  • In the SECOND part, we have specified the value to enter into the cell. What you have done is, you have defined the value property for cell A5 by using “.Value”. After that, the next thing that you have specified is the value against the value property. Whenever you are defining a value (if it’s text), you need to wrap that value inside double quotation marks.

Here I have listed some of the most amazing tutorials (not in any particular sequence) that can help you learn VBA in NO TIME.

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

Skip to content

How to Use the VBA Editor in Excel: Quick Guide (2023)

How to Use the VBA Editor in Excel: Quick Guide (2023)

Excel’s Visual Basic for Applications (VBA) editor is a very powerful tool.

It lets you write and edit custom scripts that automate actions in Excel.

In fact, when you record a macro it is stored in VBA code in the VBA editor.

But writing a macro from the VBA editor directly gives you more flexibility than recording a macro in the traditional manner.

You can create better VBA code and complete more complicated tasks by working directly with Visual Basic for Applications.

In this tutorial, I show you the basics of how to use Excel’s VBA editor. Let’s get into it!

What is the VBA editor?

The Visual Basic editor, also called the VBA editor, VB editor, or VBE, is an interface for creating scripts.

VBA (Visual Basic for Applications) is the coding language that’s used to create these scripts.

excel visual basic editor example

Visual Basic is a full-featured programming language, but Microsoft Office’s very own VBA programming language is easier to get the hang of, so you can get started with developing applications much more quicker.

Kasper Langmann, Microsoft Office Specialist

If you’ve done any programming in an integrated development environment (IDE), the VBA editor in Excel will look familiar. It lets you create, manage, and run VBA code on your Excel spreadsheet.

Let’s take a look at how to open the Visual Basic editor and do a few basic things.

How to use the VBA editor in Excel

Before you start coding, you’ll need to open the VBA editor. To do this, head to the Developer tab and click the Visual Basic button:

visual basic editor from the developer tab

If you don’t see the Developer tab, go to File > Options > Customize Ribbon and make sure that the developer tab is checked in the right pane. If you want a more thorough explanation of how to add the developer tab in Excel, read it here.

You can also open the VBA editor with the shortcut key Alt + F11.

As you can see, the VBA editor is packed full of buttons, menu bars, and options. Don’t worry—we’ll go through the important ones in this guide.

Kasper Langmann, Microsoft Office Specialist

In this guide, we’ll focus on the most basic parts of the Visual Basic editor.

The project view, in the left, vertical, menu bar in the VBA editor, has a folder called Modules.

excel vba code window for writing code

This folder holds Excel VBA modules, which are like containers for VBA code. When you record macros, they’re included in a module.

Modules also contain the code window where you’ll be writing code (if you’re not recording it).

To add a new, empty module, click the Insert menu button and select Module.

excel visual basic editor tool bar

If there was no Modules folder in VBAProject, the folder will be created and there will be a new module inside of it. This is where you’ll put your Excel VBA code when you’re ready to write it.

To delete a module, right-click it in the left pane and select Remove [module name].

excel vba editor module code window

Excel will ask you to confirm the removal. You may export the module if you’d like to save it.

Finally, let’s look at running a macro from the Visual Basic Editor window.

After you’ve created a macro, either by coding it directly or recording it from the standard Excel interface, you can run it from this view.

To run a macro, just click the Run Macro button in the menu bar:

visual basic editor code window for storing modules with excel vba code

You can also press the shortcut key F5 on your keyboard to run the macro from the VBA editor.

PRO TIP: Change the name of a module

If you’re developing big spreadsheets with lots of VBA, all the macro codes won’t be able to fit in one single module. You’ll need more. You can easily add those from the menu bar, but as you add more, it becomes increasingly more difficult to figure out what macros are in what modules.

Luckily, you can easily change the name of a module in the Properties window.

Add the Properties code window from the Insert button on the menu bar.

If the Project window is missing

If it looks like this when you open the Visual Basic editor:

visual basic editor in excel no project explorer visible - only menu bar

The code window is missing, there’s no left vertical menu bar. Nothing is visible except the horizontal menu bar on top 🤷

You need to click on the ‘View’ tab on the menu bar, and then click to show the ‘Project Explorer’ window.

That’s it – Now what?

This was a simple Excel tutorial on getting started with the Visual Basic editor in Excel and should get you on the right track to write code (or record it).

Mastering the Excel VBA editor is important for both beginners and advanced Excel users.

When you write more VBA code, you’ll see that the Excel VBA editor becomes a better help for you in your work.

For instance, it helps you autocomplete your VBA coding with IntelliSense, helps you find syntax errors with auto syntax check, debug with the immediate window, uses the object code window, and much more.

For now, play around with the VBA editor to get a feel for where the buttons and menus are, and start getting used to the structure of VBA.

If you want to dive deeper into VBA programming, check out my free 30-minute VBA course here.

Other resources

The VBA editor is just a tiny portion of what macros are all about. You definitely need to check out my big VBA guide here.

Frequently asked questions

To open the Visual Basic Editor in Excel, follow these steps:

  1. Click the Developer tab.
  2. Click the Visual Basic button in the Code group on the Developer tab. This opens the VBA editor.
  3. Alternatively, you can open the VBA editor by pressing the Alt + F11 shortcut keys.

There is no need to install the VBA editor. It should already be available in your Excel program.

But you might be missing the developer tab. To add it:

  1. Click the File tab and Options.
  2. Then click the Customize Ribbon tab.
  3. Under Customize the Ribbon, in the right pane, select the Developer check box.
  4. Click OK.

Kasper Langmann2023-01-30T19:50:45+00:00

Page load link

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.

title ms.prod ms.assetid ms.date ms.localizationpriority

Getting started with VBA in Office

office

7208a87a-a567-41d9-af5b-0df3884c58d9

08/14/2019

high

Are you facing a repetitive clean up of fifty tables in Word? Do you want a particular document to prompt the user for input when it opens? Are you having difficulty figuring out how to get your contacts from Microsoft Outlook into a Microsoft Excel spreadsheet efficiently?

You can perform these tasks and accomplish a great deal more by using Visual Basic for Applications (VBA) for Office—a simple, but powerful programming language that you can use to extend Office applications.

This article is for experienced Office users who want to learn about VBA and who want some insight into how programming can help them to customize Office.

The Office suite of applications has a rich set of features. There are many different ways to author, format, and manipulate documents, email, databases, forms, spreadsheets, and presentations. The great power of VBA programming in Office is that nearly every operation that you can perform with a mouse, keyboard, or a dialog box can also be done by using VBA. Further, if it can be done once with VBA, it can be done just as easily a hundred times. (In fact, the automation of repetitive tasks is one of the most common uses of VBA in Office.)

Beyond the power of scripting VBA to accelerate every-day tasks, you can use VBA to add new functionality to Office applications or to prompt and interact with the user of your documents in ways that are specific to your business needs. For example, you could write some VBA code that displays a pop up message that reminds users to save a document to a particular network drive the first time they try to save it.

This article explores some of the primary reasons to leverage the power of VBA programming. It explores the VBA language and the out-of-the-box tools that you can use to work with your solutions. Finally, it includes some tips and ways to avoid some common programming frustrations and missteps.

[!includeAdd-ins note]

When to use VBA and why

There are several principal reasons to consider VBA programming in Office.

Automation and repetition

VBA is effective and efficient when it comes to repetitive solutions to formatting or correction problems. For example, have you ever changed the style of the paragraph at the top of each page in Word? Have you ever had to reformat multiple tables that were pasted from Excel into a Word document or an Outlook email? Have you ever had to make the same change in multiple Outlook contacts?

If you have a change that you have to make more than ten or twenty times, it may be worth automating it with VBA. If it is a change that you have to do hundreds of times, it certainly is worth considering. Almost any formatting or editing change that you can do by hand, can be done in VBA.

Extensions to user interaction

There are times when you want to encourage or compel users to interact with the Office application or document in a particular way that is not part of the standard application. For example, you might want to prompt users to take some particular action when they open, save, or print a document.

Interaction between Office applications

Do you need to copy all of your contacts from Outlook to Word and then format them in some particular way? Or, do you need to move data from Excel to a set of PowerPoint slides? Sometimes simple copy and paste does not do what you want it to do, or it is too slow. Use VBA programming to interact with the details of two or more Office applications at the same time and then modify the content in one application based on the content in another.

Doing things another way

VBA programming is a powerful solution, but it is not always the optimal approach. Sometimes it makes sense to use other ways to achieve your aims.

The critical question to ask is whether there is an easier way. Before you begin a VBA project, consider the built-in tools and standard functionalities. For example, if you have a time-consuming editing or layout task, consider using styles or accelerator keys to solve the problem. Can you perform the task once and then use CTRL+Y (Redo) to repeat it? Can you create a new document with the correct format or template, and then copy the content into that new document?

Office applications are powerful; the solution that you need may already be there. Take some time to learn more about Office before you jump into programming.

Before you begin a VBA project, ensure that you have the time to work with VBA. Programming requires focus and can be unpredictable. Especially as a beginner, never turn to programming unless you have time to work carefully. Trying to write a «quick script» to solve a problem when a deadline looms can result in a very stressful situation. If you are in a rush, you might want to use conventional methods, even if they are monotonous and repetitive.

VBA Programming 101

Using code to make applications do things

You might think that writing code is mysterious or difficult, but the basic principles use every-day reasoning and are quite accessible. Microsoft Office applications are created in such a way that they expose things called objects that can receive instructions, in much the same way that a phone is designed with buttons that you use to interact with the phone. When you press a button, the phone recognizes the instruction and includes the corresponding number in the sequence that you are dialing. In programming, you interact with the application by sending instructions to various objects in the application. These objects are expansive, but they have their limits. They can only do what they are designed to do, and they will only do what you instruct them to do.

For example, consider the user who opens a document in Word, makes a few changes, saves the document, and then closes it. In the world of VBA programming, Word exposes a Document object. By using VBA code, you can instruct the Document object to do things such as Open, Save, or Close.

The following section discusses how objects are organized and described.

The Object Model

Developers organize programming objects in a hierarchy, and that hierarchy is called the object model of the application. Word, for example, has a top-level Application object that contains a Document object. The Document object contains Paragraph objects and so on. Object models roughly mirror what you see in the user interface. They are a conceptual map of the application and its capabilities.

The definition of an object is called a class, so you might see these two terms used interchangeably. Technically, a class is the description or template that is used to create, or instantiate, an object.

Once an object exists, you can manipulate it by setting its properties and calling its methods. If you think of the object as a noun, the properties are the adjectives that describe the noun and the methods are the verbs that animate the noun. Changing a property changes some quality of appearance or behavior of the object. Calling one of the object methods causes the object to perform some action.

The VBA code in this article runs against an open Office application where many of the objects that the code manipulates are already up and running; for example, the Application itself, the Worksheet in Excel, the Document in Word, the Presentation in PowerPoint, the Explorer and Folder objects in Outlook. Once you know the basic layout of the object model and some key properties of the Application that give access to its current state, you can start to extend and manipulate that Office application with VBA in Office.

Methods

In Word, for example, you can change the properties and invoke the methods of the current Word document by using the ActiveDocument property of the Application object. This ActiveDocument property returns a reference to the Document object that is currently active in the Word application. «Returns a reference to» means «gives you access to.»

The following code does exactly what it says; that is, it saves the active document in the application.

Application.ActiveDocument.Save

Read the code from left to right, «In this Application, with the Document referenced by ActiveDocument, invoke the Save method.» Be aware that Save is the simplest form of method; it does not require any detailed instructions from you. You instruct a Document object to Save and it does not require any more input from you.

If a method requires more information, those details are called parameters. The following code runs the SaveAs method, which requires a new name for the file.

Application.ActiveDocument.SaveAs ("New Document Name.docx")

Values listed in parentheses after a method name are the parameters. Here, the new name for the file is a parameter for the SaveAs method.

Properties

You use the same syntax to set a property that you use to read a property. The following code executes a method to select cell A1 in Excel and then to set a property to put something in that cell.

    Application.ActiveSheet.Range("A1").Select
    Application.Selection.Value = "Hello World"

The first challenge in VBA programming is to get a feeling for the object model of each Office application and to read the object, method, and property syntax. The object models are similar in all Office applications, but each is specific to the kind of documents and objects that it manipulates.

In the first line of the code snippet, there is the Application object, Excel this time, and then the ActiveSheet, which provides access to the active worksheet. After that is a term not as familiar, Range, which means «define a range of cells in this way.» The code instructs Range to create itself with just A1 as its defined set of cells. In other words, the first line of code defines an object, the Range, and runs a method against it to select it. The result is automatically stored in another property of the Application called Selection.

The second line of code sets the Value property of Selection to the text «Hello World», and that value appears in cell A1.

The simplest VBA code that you write might simply gain access to objects in the Office application that you are working with and set properties. For example, you could get access to the rows in a table in Word and change their formatting in your VBA script.

That sounds simple, but it can be incredibly useful; once you can write that code, you can harness all of the power of programming to make those same changes in several tables or documents, or make them according to some logic or condition. For a computer, making 1000 changes is no different from making 10, so there is an economy of scale here with larger documents and problems, and that is where VBA can really shine and save you time.

Macros and the Visual Basic Editor

Now that you know something about how Office applications expose their object models, you are probably eager to try calling object methods, setting object properties, and responding to object events. To do so, you must write your code in a place and in a way that Office can understand; typically, by using the Visual Basic Editor. Although it is installed by default, many users don’t know that it is even available until it is enabled on the ribbon.

All Office applications use the ribbon. One tab on the ribbon is the Developer tab, where you access the Visual Basic Editor and other developer tools. Because Office does not display the Developer tab by default, you must enable it by using the following procedure:

To enable the Developer tab

  1. On the File tab, choose Options to open the Options dialog box.

  2. Choose Customize Ribbon on the left side of the dialog box.

  3. Under Choose commands from on the left side of the dialog box, select Popular Commands.

  4. Under Customize the Ribbon on the right side of the dialog box, select Main Tabs in the drop down list box, and then select the Developer checkbox.

  5. Choose OK.

[!NOTE]
In Office 2007, you displayed the Developer tab by choosing the Office button, choosing Options, and then selecting the Show Developer tab in Ribbon check box in the Popular category of the Options dialog box.

After you enable the Developer tab, it is easy to find the Visual Basic and Macros buttons.

Figure 1. Buttons on the Developer tab

Buttons on the Developer tab

Security issues

To protect Office users against viruses and dangerous macro code, you cannot save macro code in a standard Office document that uses a standard file extension. Instead, you must save the code in a file with a special extension. For example you cannot save macros in a standard Word document with a .docx extension; instead, you must use a special Word Macro-Enabled Document with a .docm extension.

When you open a .docm file, Office security might still prevent the macros in the document from running, with or without telling you. Examine the settings and options in the Trust Center on all Office applications. The default setting disables macro from running, but warns you that macros have been disabled and gives you the option to turn them back on for that document.

You can designate specific folders where macros can run by creating Trusted Locations, Trusted Documents, or Trusted Publishers. The most portable option is to use Trusted Publishers, which works with digitally signed documents that you distribute. For more information about the security settings in a particular Office application, open the Options dialog box, choose Trust Center, and then choose Trust Center Settings.

[!NOTE]
Some Office applications, like Outlook, save macros by default in a master template on your local computer. Although that strategy reduces the local security issues on your own computer when you run your own macros, it requires a deployment strategy if you want to distribute your macro.

Recording a macro

When you choose the Macro button on the Developer tab, it opens the Macros dialog box, which gives you access to VBA subroutines or macros that you can access from a particular document or application. The Visual Basic button opens the Visual Basic Editor, where you create and edit VBA code.

Another button on the Developer tab in Word and Excel is the Record Macro button, which automatically generates VBA code that can reproduce the actions that you perform in the application. Record Macro is a terrific tool that you can use to learn more about VBA. Reading the generated code can give you insight into VBA and provide a stable bridge between your knowledge of Office as a user and your knowledge as a programmer. The only caveat is that the generated code can be confusing because the Macro editor must make some assumptions about your intentions, and those assumptions are not necessarily accurate.

To record a macro

  1. Open Excel to a new Workbook and choose the Developer tab in the ribbon. Choose Record Macro and accept all of the default settings in the Record Macro dialog box, including Macro1 as the name of the macro and This Workbook as the location.

  2. Choose OK to begin recording the macro. Note how the button text changes to Stop Recording. Choose that button the instant you complete the actions that you want to record.

  3. Choose cell B1 and type the programmer’s classic first string: Hello World. Stop typing and look at the Stop Recording button; it is grayed out because Excel is waiting for you to finish typing the value in the cell.

  4. Choose cell B2 to complete the action in cell B1, and then choose Stop Recording.

  5. Choose Macros on the Developer tab, select Macro1 if it is not selected, and then choose Edit to view the code from Macro1 in the Visual Basic Editor.

Figure 2. Macro code in Visual Basic Editor

Macro code in Visual Basic Editor

Looking at the code

The macro that you created should look similar to the following code.

Sub Macro1()
'
' Macro1 Macro
'
'
    Range("B1").Select
    ActiveCell.FormulaR1C1 = "Hello World"
    Range("B2").Select
End Sub

Be aware of the similarities to the earlier code snippet that selected text in cell A1, and the differences. In this code, cell B1 is selected, and then the string «Hello World» is applied to the cell that has been made active. The quotes around the text specify a string value as opposed to a numeric value.

Remember how you chose cell B2 to display the Stop Recording button again? That action shows up as a line of code as well. The macro recorder records every keystroke.

The lines of code that start with an apostrophe and colored green by the editor are comments that explain the code or remind you and other programmers the purpose of the code. VBA ignores any line, or portion of a line, that begins with a single quote. Writing clear and appropriate comments in your code is an important topic, but that discussion is out of the scope of this article. Subsequent references to this code in the article don’t include those four comment lines.

When the macro recorder generates the code, it uses a complex algorithm to determine the methods and the properties that you intended. If you don’t recognize a given property, there are many resources available to help you. For example, in the macro that you recorded, the macro recorder generated code that refers to the FormulaR1C1 property. Not sure what that means?

[!NOTE]
Be aware that Application object is implied in all VBA macros. The code that you recorded works with Application. at the beginning of each line.

Using Developer Help

Select FormulaR1C1 in the recorded macro and press F1. The Help system runs a quick search, determines that the appropriate subjects are in the Excel Developer section of the Excel Help, and lists the FormulaR1C1 property. You can choose the link to read more about the property, but before you do, be aware of the Excel Object Model Reference link near the bottom of the window. Choose the link to view a long list of objects that Excel uses in its object model to describe the Worksheets and their components.

Choose any one of those to see the properties and methods that apply to that particular object, along with cross references to different related options. Many Help entries also have brief code examples that can help you. For example, you can follow the links in the Borders object to see how to set a border in VBA.

Worksheets(1).Range("A1").Borders.LineStyle = xlDouble

Editing the code

The Borders code looks different from the recorded macro. One thing that can be confusing with an object model is that there is more than one way to address any given object, cell A1 in this example.

Sometimes the best way to learn programming is to make minor changes to some working code and see what happens as a result. Try it now. Open Macro1 in the Visual Basic Editor and change the code to the following.

Sub Macro1()
    Worksheets(1).Range("A1").Value = "Wow!"
    Worksheets(1).Range("A1").Borders.LineStyle = xlDouble
End Sub

[!TIP]
Use Copy and Paste as much as possible when working with code to avoid typing errors.

You don’t need to save the code to try it out, so return to the Excel document, choose Macros on the Developer tab, choose Macro1, and then choose Run. Cell A1 now contains the text Wow! and has a double-line border around it.

Figure 3. Results of your first macro

Results of your first macro

You just combined macro recording, reading the object model documentation, and simple programming to make a VBA program that does something. Congratulations!

Did not work? Read on for debugging suggestions in VBA.

Programming tips and tricks

Start with examples

The VBA community is very large; a search on the Web can almost always yield an example of VBA code that does something similar to what you want to do. If you cannot find a good example, try to break the task down into smaller units and search on each of those, or try to think of a more common, but similar problem. Starting with an example can save you hours of time.

That does not mean that free and well-thought-out code is on the Web waiting for you to come along. In fact, some of the code that you find might have bugs or mistakes. The idea is that the examples you find online or in VBA documentation give you a head start. Remember that learning programming requires time and thought. Before you get in a big rush to use another solution to solve your problem, ask yourself whether VBA is the right choice for this problem.

Make a simpler problem

Programming can get complex quickly. It’s critical, especially as a beginner, that you break the problem down to the smallest possible logical units, then write and test each piece in isolation. If you have too much code in front of you and you get confused or muddled, stop and set the problem aside. When you come back to the problem, copy out a small piece of the problem into a new module, solve that piece, get the code working, and test it to ensure that it works. Then move on to the next part.

Bugs and debugging

There are two main types of programming errors: syntax errors, which violate the grammatical rules of the programming language, and run-time errors, which look syntactically correct, but fail when VBA attempts to execute the code.

Although they can be frustrating to fix, syntax errors are easy to catch; the Visual Basic Editor beeps and flashes at you if you type a syntax error in your code.

For example, string values must be surrounded by double quotes in VBA. To find out what happens when you use single quotes instead, return to the Visual Basic Editor and replace the «Wow!» string in the code example with ‘Wow!’ (that is, the word Wow enclosed in single quotes). If you choose the next line, the Visual Basic Editor reacts. The error «Compile error: Expected: expression» is not that helpful, but the line that generates the error turns red to tell you that you have a syntax error in that line and as a result, this program will not run.

Choose OK and change the text back to»Wow!».

Runtime errors are harder to catch because the programming syntax looks correct, but the code fails when VBA tries to execute it.

For example, open the Visual Basic Editor and change the Value property name to ValueX in your Macro, deliberately introducing a runtime error since the Range object does not have a property called ValueX. Go back to the Excel document, open the Macros dialog box and run Macro1 again. You should see a Visual Basic message box that explains the run-time error with the text, «Object doesn’t support this property of method.» Although that text is clear, choose Debug to find out more.

When you return to the Visual Basic Editor, it is in a special debug mode that uses a yellow highlight to show you the line of code that failed. As expected, the line that includes the ValueX property is highlighted.

You can make changes to VBA code that is running, so change ValueX back to Value and choose the little green play button underneath the Debug menu. The program should run normally again.

It’s a good idea to learn how to use the debugger more deliberately for longer, more complex programs. At a minimum, learn a how to set break-points to stop execution at a point where you want to take a look at the code, how to add watches to see the values of different variables and properties as the code runs, and how to step through the code line by line. These options are all available in the Debug menu and serious debugger users typically memorize the accompanying keyboard shortcuts.

Using reference materials well

To open the Developer Reference that is built into Office Help, open the Help reference from any Office application by choosing the question mark in the ribbon or by pressing F1. Then, to the right of the Search button, choose the dropdown arrow to filter the contents. Choose Developer Reference. If you don’t see the table of contents in the left panel, choose the little book icon to open it, and then expand the Object Model Reference from there.

Figure 5. Filtering on developer Help applies to all Office applications

Filtering on developer Help applies to all Office applications

Time spent browsing the Object Model reference pays off. After you understand the basics of VBA syntax and the object model for the Office application that you are working with, you advance from guesswork to methodical programming.

Of course the Microsoft Office Developer Center is an excellent portal for articles, tips, and community information.

Searching forums and groups

All programmers get stuck sometimes, even after reading every reference article they can find and losing sleep at night thinking about different ways to solve a problem. Fortunately, the Internet has fostered a community of developers who help each other solve programming problems.

Any search on the Web for «office developer forum» reveals several discussion groups. You can search on «office development» or a description of your problem to discover forums, blog posts, and articles as well.

If you have done everything that you can to solve a problem, don’t be afraid to post your question to a developers forum. These forums welcome posts from newer programmers and many of the experienced developers are glad to help.

The following are a few points of etiquette to follow when you post to a developer forum:

  • Before you post, look on the site for an FAQ or for guidelines that members want you to follow. Ensure that you post content that is consistent with those guidelines and in the correct section of the forum.

  • Include a clear and complete code sample, and consider editing your code to clarify it for others if it is part of a longer section of code.

  • Describe your problem clearly and concisely, and summarize any steps that you have taken to solve the problem. Take the time to write your post as well as you can, especially if you are flustered or in a hurry. Present the situation in a way that will make sense to readers the first time that they read the problem statement.

  • Be polite and express your appreciation.

Going further with programming

Although this article is short and only scratches the surface of VBA and programming, it is hopefully enough to get you started.

This section briefly discusses a few more key topics.

Variables

In the simple examples in this article you manipulated objects that the application had already created. You might want to create your own objects to store values or references to other objects for temporary use in your application. These are called variables.

To use a variable in VBA, must tell VBA which type of object the variable represents by using the Dim statement. You then set its value and use it to set other variables or properties.

    Dim MyStringVariable As String
    MyStringVariable = "Wow!"
    Worksheets(1).Range("A1").Value = MyStringVariable

Branching and looping

The simple programs in this article execute one line at a time, from the top down. The real power in programming comes from the options that you have to determine which lines of code to execute, based on one or more conditions that you specify. You can extend those capabilities even further when you can repeat an operation many times. For example, the following code extends Macro1.

Sub Macro1()
    If Worksheets(1).Range("A1").Value = "Yes!" Then
        Dim i As Integer
        For i = 2 To 10
            Worksheets(1).Range("A" & i).Value = "OK! " & i
        Next i
    Else
        MsgBox "Put Yes! in cell A1"
    End If
End Sub

Type or paste the code into the Visual Basic Editor and then run it. Follow the directions in the message box that appears and change the text in cell A1 from Wow! to Yes! and run it again to see the power of looping. This code snippet demonstrates variables, branching and looping. Read it carefully after you see it in action and try to determine what happens as each line executes.

All of my Office applications: example code

Here are a few scripts to try; each solves a real-world Office problem.

Create an email in Outlook

Sub MakeMessage()
    Dim OutlookMessage As Outlook.MailItem
    Set OutlookMessage = Application.CreateItem(olMailItem)
    OutlookMessage.Subject = "Hello World!"
    OutlookMessage.Display
    Set OutlookMessage = Nothing
End Sub

Be aware that there are situations in which you might want to automate email in Outlook; you can use templates as well.

Delete empty rows in an Excel worksheet

Sub DeleteEmptyRows()
    SelectedRange = Selection.Rows.Count
    ActiveCell.Offset(0, 0).Select
    For i = 1 To SelectedRange
        If ActiveCell.Value = "" Then
            Selection.EntireRow.Delete
        Else
            ActiveCell.Offset(1, 0).Select
        End If
    Next i
End Sub

Be aware that you can select a column of cells and run this macro to delete all rows in the selected column that have a blank cell.

Delete empty text boxes in PowerPoint

Sub RemoveEmptyTextBoxes()
    Dim SlideObj As Slide
    Dim ShapeObj As Shape
    Dim ShapeIndex As Integer
    For Each SlideObj In ActivePresentation.Slides
        For ShapeIndex = SlideObj.Shapes.Count To 1 Step -1
            Set ShapeObj = SlideObj.Shapes(ShapeIndex)
            If ShapeObj.Type = msoTextBox Then
                If Trim(ShapeObj.TextFrame.TextRange.Text) = "" Then
                    ShapeObj.Delete
                End If
            End If
        Next ShapeIndex
    Next SlideObj
End Sub

Be aware that this code loops through all of the slides and deletes all text boxes that don’t have any text. The count variable decrements instead of increments because each time the code deletes an object, it removes that object from the collection, which reduces the count.

Copy a contact from Outlook to Word

Sub CopyCurrentContact()
   Dim OutlookObj As Object
   Dim InspectorObj As Object
   Dim ItemObj As Object
   Set OutlookObj = CreateObject("Outlook.Application")
   Set InspectorObj = OutlookObj.ActiveInspector
   Set ItemObj = InspectorObj.CurrentItem
   Application.ActiveDocument.Range.InsertAfter (ItemObj.FullName & " from " & ItemObj.CompanyName)
End Sub

Be aware that this code copies the currently open contact in Outlook into the open Word document. This code only works if there is a contact currently open for inspection in Outlook.

[!includeSupport and feedback]

Понравилась статья? Поделить с друзьями:
  • Worksheets for word order in sentences
  • Working with time excel
  • Worksheets for the in word family
  • Working with tables in word
  • Worksheets for microsoft excel