What is a macro worksheet in excel

На чтение 16 мин. Просмотров 14.8k.

VBA Worksheet

Malcolm Gladwell

Мечтатель начинает с чистого листа бумаги и переосмысливает мир

Эта статья содержит полное руководство по использованию Excel
VBA Worksheet в Excel VBA. Если вы хотите узнать, как что-то сделать быстро, ознакомьтесь с кратким руководством к рабочему листу VBA ниже.

Если вы новичок в VBA, то эта статья — отличное место для начала. Мне нравится разбивать вещи на простые термины и объяснять их на простом языке.

Вы можете прочитать статью от начала до конца, так как она написана в логическом порядке. Или, если предпочитаете, вы можете использовать оглавление ниже и перейти непосредственно к теме по вашему выбору.

Содержание

  1. Краткое руководство к рабочему листу VBA
  2. Вступление
  3. Доступ к рабочему листу
  4. Использование индекса для доступа к рабочему листу
  5. Использование кодового имени рабочего листа
  6.  Активный лист
  7. Объявление объекта листа
  8. Доступ к рабочему листу в двух словах
  9. Добавить рабочий лист
  10. Удалить рабочий лист
  11. Цикл по рабочим листам
  12. Использование коллекции листов
  13. Заключение

Краткое руководство к рабочему листу VBA

В следующей таблице приведен краткий обзор различных методов
Worksheet .

Примечание. Я использую Worksheet в таблице ниже, не указывая рабочую книгу, т.е. Worksheets, а не ThisWorkbook.Worksheets, wk.Worksheets и т.д. Это сделано для того, чтобы примеры были понятными и удобными для чтения. Вы должны всегда указывать рабочую книгу при использовании Worksheets . В противном случае активная рабочая книга будет использоваться по умолчанию.

Задача Исполнение
Доступ к рабочему листу по
имени
Worksheets(«Лист1»)
Доступ к рабочему листу по
позиции слева
Worksheets(2)
Worksheets(4)
Получите доступ к самому
левому рабочему листу
Worksheets(1)
Получите доступ к самому
правому листу
Worksheets(Worksheets.Count)
Доступ с использованием
кодового имени листа (только
текущая книга)
Смотри раздел статьи
Использование кодового имени
Доступ по кодовому имени
рабочего листа (другая рабочая
книга)
Смотри раздел статьи
Использование кодового имени
Доступ к активному листу ActiveSheet
Объявить переменную листа Dim sh As Worksheet
Назначить переменную листа Set sh = Worksheets(«Лист1»)
Добавить лист Worksheets.Add
Добавить рабочий лист и
назначить переменную
Worksheets.Add Before:=
Worksheets(1)
Добавить лист в первую
позицию (слева)
Set sh =Worksheets.Add
Добавить лист в последнюю
позицию (справа)
Worksheets.Add after:=Worksheets(Worksheets.Count)
Добавить несколько листов Worksheets.Add Count:=3
Активировать рабочий лист sh.Activate
Копировать лист sh.Copy
Копировать после листа sh1.Copy After:=Sh2
Скопировать перед листом sh1.Copy Before:=Sh2
Удалить рабочий лист sh.Delete
Удалить рабочий лист без
предупреждения
Application.DisplayAlerts = False
sh.Delete
Application.DisplayAlerts = True
Изменить имя листа sh.Name = «Data»
Показать/скрыть лист sh.Visible = xlSheetHidden
sh.Visible = xlSheetVisible sh.Name = «Data»
Перебрать все листы (For) Dim i As Long
For i = 1 To Worksheets.Count
  Debug.Print Worksheets(i).Name
Next i
Перебрать все листы (For Each) Dim sh As Worksheet
For Each sh In Worksheets
    Debug.Print sh.Name
Next

Вступление

Три наиболее важных элемента VBA — это Рабочая книга, Рабочий лист и Ячейки. Из всего кода, который вы пишете, 90% будут включать один или все из них.

Наиболее распространенное использование Worksheet в VBA для доступа к его ячейкам. Вы можете использовать его для защиты, скрытия, добавления, перемещения или копирования листа.

Тем не менее, вы будете в основном использовать его для выполнения некоторых действий с одной или несколькими ячейками на листе.

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

Доступ к рабочему листу

В VBA каждая рабочая книга имеет коллекцию рабочих листов. В этой коллекции есть запись для каждого рабочего листа. Эта коллекция называется просто Worksheets и используется очень похоже на коллекцию Workbooks. Чтобы получить доступ к рабочему листу, достаточно указать имя.

Приведенный ниже код записывает «Привет Мир» в ячейках A1 на листах: Лист1, Лист2 и Лист3 текущей рабочей книги.

Sub ZapisVYacheiku1()

    ' Запись в ячейку А1 в листе 1, листе 2 и листе 3
    ThisWorkbook.Worksheets("Лист1").Range("A1") = "Привет Мир"
    ThisWorkbook.Worksheets("Лист2").Range("A1") = "Привет Мир"
    ThisWorkbook.Worksheets("Лист3").Range("A1") = "Привет Мир"

End Sub

Коллекция Worksheets всегда принадлежит книге. Если мы не
указываем рабочую книгу, то активная рабочая книга используется по умолчанию.

Sub ZapisVYacheiku1()

    ' Worksheets относятся к рабочим листам в активной рабочей книге.
    Worksheets("Лист1").Range("A1") = "Привет Мир"
    Worksheets("Лист2").Range("A1") = "Привет Мир"
    Worksheets("Лист3").Range("A1") = "Привет Мир"

End Sub

Скрыть рабочий лист

В следующих примерах показано, как скрыть и показать лист.

ThisWorkbook.Worksheets("Лист1").Visible = xlSheetHidden

ThisWorkbook.Worksheets("Лист1").Visible = xlSheetVisible

Если вы хотите запретить пользователю доступ к рабочему
листу, вы можете сделать его «очень скрытым». Это означает, что это может быть
сделано видимым только кодом.

' Скрыть от доступа пользователя
ThisWorkbook.Worksheets("Лист1").Visible = xlVeryHidden

' Это единственный способ сделать лист xlVeryHidden видимым
ThisWorkbook.Worksheets("Лист1").Visible = xlSheetVisible

Защитить рабочий лист

Другой пример использования Worksheet — когда вы хотите защитить его.

ThisWorkbook.Worksheets("Лист1").Protect Password:="Мойпароль"

ThisWorkbook.Worksheets("Лист1").Unprotect Password:="Мойпароль"

Индекс вне диапазона

При использовании Worksheets вы можете получить сообщение об
ошибке:

Run-time Error 9 Subscript out of Range

VBA Subscript out of Range

Это означает, что вы пытались получить доступ к рабочему листу, который не существует. Это может произойти по следующим причинам:

  1. Имя Worksheet , присвоенное рабочим листам, написано неправильно.
  2. Название листа изменилось.
  3. Рабочий лист был удален.
  4. Индекс был большим, например Вы использовали рабочие листы (5), но есть только четыре рабочих листа
  5. Используется неправильная рабочая книга, например Workbooks(«book1.xlsx»).Worksheets(«Лист1») вместо
    Workbooks(«book3.xlsx»).Worksheets («Лист1»).

Если у вас остались проблемы, используйте один из циклов из раздела «Циклы по рабочим листам», чтобы напечатать имена всех рабочих листов коллекции.

Использование индекса для доступа к рабочему листу

До сих пор мы использовали имя листа для доступа к листу.
Указатель относится к положению вкладки листа в рабочей книге. Поскольку
положение может быть легко изменено пользователем, не рекомендуется
использовать это.

 В следующем коде показаны примеры использования индекса.

' Использование этого кода является плохой идеей, так как
' позиции листа все время меняются
Sub IspIndList()

    With ThisWorkbook
        ' Самый левый лист
        Debug.Print .Worksheets(1).Name
        ' Третий лист слева
        Debug.Print .Worksheets(3).Name
        ' Самый правый лист
        Debug.Print .Worksheets(.Worksheets.Count).Name
    End With

End Sub

В приведенном выше примере я использовал Debug.Print для печати в Immediate Window. Для просмотра этого окна выберите «Вид» -> «Immediate Window » (Ctrl + G).

ImmediateWindow

ImmediateSampeText

Использование кодового имени рабочего листа

Лучший способ получить доступ к рабочему листу —
использовать кодовое имя. Каждый лист имеет имя листа и кодовое имя. Имя листа
— это имя, которое отображается на вкладке листа в Excel.

Изменение имени листа не приводит к изменению кодового имени, что означает, что ссылка на лист по кодовому имени — отличная идея.

Если вы посмотрите в окне свойств VBE, вы увидите оба имени.
На рисунке вы можете видеть, что кодовое имя — это имя вне скобок, а имя листа
— в скобках.

code name worksheet

Вы можете изменить как имя листа, так и кодовое имя в окне
свойств листа (см. Изображение ниже).

Width

Если ваш код ссылается на кодовое имя, то пользователь может
изменить имя листа, и это не повлияет на ваш код. В приведенном ниже примере мы
ссылаемся на рабочий лист напрямую, используя кодовое имя.

Sub IspKodImya2()

    ' Используя кодовое имя листа
    Debug.Print CodeName.Name
    CodeName.Range("A1") = 45
    CodeName.Visible = True

End Sub

Это делает код легким для чтения и безопасным от изменения
пользователем имени листа.

Кодовое имя в других книгах

Есть один недостаток использования кодового имени. Он относится только к рабочим листам в рабочей книге, которая содержит код, т.е. ThisWorkbook.

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

Sub ИспЛист()

    Dim sh As Worksheet
    ' Получить рабочий лист под кодовым именем
    Set sh = SheetFromCodeName("CodeName", ThisWorkbook)
    ' Используйте рабочий лист
    Debug.Print sh.Name

End Sub

' Эта функция получает объект листа из кодового имени
Public Function SheetFromCodeName(Name As String, bk As Workbook) As Worksheet

    Dim sh As Worksheet
    For Each sh In bk.Worksheets
        If sh.CodeName = Name Then
           Set SheetFromCodeName = sh
           Exit For
        End If
    Next sh

End Function

Использование приведенного выше кода означает, что если
пользователь изменит имя рабочего листа, то на ваш код это не повлияет.

Существует другой способ получения имени листа внешней
рабочей книги с использованием кодового имени. Вы можете использовать элемент
VBProject этой Рабочей книги.

Вы можете увидеть, как это сделать, в примере ниже. Я включил это, как дополнительную информацию, я бы рекомендовал использовать метод из предыдущего примера, а не этот.

Public Function SheetFromCodeName2(codeName As String _
                             , bk As Workbook) As Worksheet

    ' Получить имя листа из CodeName, используя VBProject
    Dim sheetName As String
    sheetName = bk.VBProject.VBComponents(codeName).Properties("Name")

    ' Используйте имя листа, чтобы получить объект листа
    Set SheetFromCodeName2 = bk.Worksheets(sheetName)

End Function

Резюме кодового имени

Ниже приведено краткое описание использования кодового имени:

  1. Кодовое имя рабочего листа может быть
    использовано непосредственно в коде, например. Sheet1.Range
  2. Кодовое имя будет по-прежнему работать, если имя
    рабочего листа будет изменено.
  3. Кодовое имя может использоваться только для
    листов в той же книге, что и код.
  4. Везде, где вы видите ThisWorkbook.Worksheets
    («имя листа»), вы можете заменить его кодовым именем рабочего листа.
  5. Вы можете использовать функцию SheetFromCodeName
    сверху, чтобы получить кодовое имя рабочих листов в других рабочих книгах.

 Активный лист

Объект ActiveSheet ссылается на рабочий лист, который в данный момент активен. Вы должны использовать ActiveSheet только в том случае, если у вас есть особая необходимость ссылаться на активный лист.

В противном случае вы должны указать рабочий лист, который
вы используете.

Если вы используете метод листа, такой как Range, и не
упоминаете лист, он по умолчанию будет использовать активный лист.

' Написать в ячейку A1 в активном листе
ActiveSheet.Range("A1") = 99

' Активный лист используется по умолчанию, если лист не используется
Range("A1") = 99

Объявление объекта листа

Объявление объекта листа полезно для того, чтобы сделать ваш
код более понятным и легким для чтения.

В следующем примере показан код для обновления диапазонов
ячеек. Первый Sub не объявляет объект листа. Вторая подпрограмма объявляет
объект листа, и поэтому код намного понятнее.

Sub NeObyavObektList()

    Debug.Print ThisWorkbook.Worksheets("Лист1").Name
    ThisWorkbook.Worksheets("Лист1").Range("A1") = 6
    ThisWorkbook.Worksheets("Лист1").Range("B2:B9").Font.Italic = True
    ThisWorkbook.Worksheets("Лист1").Range("B2:B9").Interior.Color = rgbRed

End Sub
Sub ObyavObektList()

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("Лист1")

    sht.Range("A1") = 6
    sht.Range("B2:B9").Font.Italic = True
    sht.Range("B2:B9").Interior.Color = rgbRed

End Sub

Вы также можете использовать ключевое слово With с объектом
листа, как показано в следующем примере.

Sub ObyavObektListWith()

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("Лист1")

    With sht
        .Range("A1") = 6
        .Range("B2:B9").Font.Italic = True
        .Range("B2:B9").Interior.Color = rgbRed
    End With

End Sub

Доступ к рабочему листу в двух словах

Из-за множества различных способов доступа к рабочему листу вы можете быть сбитыми с толку. Так что в этом разделе я собираюсь разбить его на простые термины.

  1. Если вы хотите использовать тот лист, который активен в данный момент, используйте ActiveSheet.
ActiveSheet.Range("A1") = 55

2. Если лист находится в той же книге, что и код, используйте кодовое имя.

3. Если рабочая таблица находится в другой рабочей книге, сначала получите рабочую книгу, а затем получите рабочую таблицу.

' Получить рабочую книгу
Dim wk As Workbook
Set wk = Workbooks.Open("C:ДокументыСчета.xlsx", ReadOnly:=True)
' Затем получите лист
Dim sh As Worksheet
Set sh = wk.Worksheets("Лист1")

Если вы хотите защитить пользователя от изменения имени листа, используйте функцию SheetFromCodeName из раздела «Имя кода».

' Получить рабочую книгу
Dim wk As Workbook
Set wk = Workbooks.Open("C:ДокументыСчета.xlsx", ReadOnly:=True)

' Затем получите лист
Dim sh As Worksheet
Set sh = SheetFromCodeName("sheetcodename",wk)

Добавить рабочий лист

Примеры в этом разделе показывают, как добавить новую
рабочую таблицу в рабочую книгу. Если вы не предоставите никаких аргументов для
функции Add, то новый
рабочий лист будет помещен перед активным рабочим листом.

Когда вы добавляете рабочий лист, он создается с именем по умолчанию, например «Лист4». Если вы хотите изменить имя, вы можете легко сделать это, используя свойство Name.

В следующем примере добавляется новый рабочий лист и изменяется имя на «Счета». Если лист с именем «Счета» уже существует, вы получите сообщение об ошибке.

Sub DobavitList()

    Dim sht As Worksheet

    ' Добавляет новый лист перед активным листом
    Set sht = ThisWorkbook.Worksheets.Add
    ' Установите название листа
    sht.Name = "Счета"

    ' Добавляет 3 новых листа перед активным листом
    ThisWorkbook.Worksheets.Add Count:=3

End Sub

В предыдущем примере вы добавляете листы по отношению к
активному листу. Вы также можете указать точную позицию для размещения листа.

Для этого вам нужно указать, какой лист новый лист должен
быть вставлен до или после. Следующий код показывает вам, как это сделать.

Sub DobavitListPervPosl()

    Dim shtNew As Worksheet
    Dim shtFirst As Worksheet, shtLast As Worksheet

    With ThisWorkbook

        Set shtFirst = .Worksheets(1)
        Set shtLast = .Worksheets(.Worksheets.Count)

        ' Добавляет новый лист на первую позицию в книге
        Set shtNew = Worksheets.Add(Before:=shtFirst)
        shtNew.Name = "FirstSheet"

        ' Добавляет новый лист к последней позиции в книге
        Set shtNew = Worksheets.Add(After:=shtLast)
        shtNew.Name = "LastSheet"

    End With

End Sub

Удалить рабочий лист

Чтобы удалить лист, просто вызовите Delete.

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Лист12")
sh.Delete

Excel отобразит предупреждающее сообщение при удалении листа. Если вы хотите скрыть это сообщение, вы можете использовать код ниже:

Application.DisplayAlerts = False
sh.Delete
Application.DisplayAlerts = True

Есть два аспекта, которые нужно учитывать при удалении таблиц.

Если вы попытаетесь получить доступ к рабочему листу после
его удаления, вы получите ошибку «Subscript out of Range», которую мы видели в
разделе «Доступ к рабочему листу».

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Лист2")
sh.Delete

' Эта строка выдаст «Subscript out of Range», так как «Лист2» не существует
Set sh = ThisWorkbook.Worksheets("Лист2")

Вторая проблема — когда вы назначаете переменную листа. Если вы попытаетесь использовать эту переменную после удаления листа, вы получите ошибку автоматизации, подобную этой:

Run-Time error -21147221080 (800401a8′) Automation Error

Если вы используете кодовое имя рабочего листа, а не
переменную, это приведет к сбою Excel,
а не к ошибке автоматизации.

В следующем примере показано, как происходят ошибки автоматизации.

sh.Delete

' Эта строка выдаст ошибку автоматизации
Debug.Assert sh.Name

Если вы назначите переменную Worksheet действительному рабочему листу, он будет работать нормально.

sh.Delete

' Назначить sh на другой лист
Set sh = Worksheets("Лист3")

' Эта строка будет работать нормально
Debug.Assert sh.Name

Цикл по рабочим листам

Элемент «Worksheets» — это набор рабочих листов, принадлежащих рабочей книге. Вы можете просмотреть каждый лист в коллекции рабочих листов, используя циклы «For Each» или «For».

В следующем примере используется цикл For Each.

Sub CiklForEach()

    ' Записывает «Привет Мир» в ячейку A1 для каждого листа
    Dim sht As Worksheet
    For Each sht In ThisWorkbook.Worksheets
         sht.Range("A1") = "Привет Мир"
    Next sht 

End Sub

В следующем примере используется стандартный цикл For.

Sub CiklFor()
    
    ' Записывает «Привет Мир» в ячейку A1 для каждого листа
    Dim i As Long
    For i = 1 To ThisWorkbook.Worksheets.Count
         ThisWorkbook.Worksheets(i).Range("A1") = "Привет Мир"
    Next sht

End Sub

Вы видели, как получить доступ ко всем открытым рабочим книгам и как получить доступ ко всем рабочим листам в ThisWorkbook. Давайте сделаем еще один шаг вперед — узнаем, как получить доступ ко всем рабочим листам во всех открытых рабочих книгах.

Примечание. Если вы используете код, подобный этому, для записи на листы, то сначала сделайте резервную копию всего, так как в итоге вы можете записать неверные данные на все листы.

Sub NazvVsehStr()

    ' Печатает рабочую книгу и названия листов для
    ' всех листов в открытых рабочих книгах
    Dim wrk As Workbook
    Dim sht As Worksheet
    For Each wrk In Workbooks
        For Each sht In wrk.Worksheets
            Debug.Print wrk.Name + ":" + sht.Name
        Next sht
    Next wrk

End Sub

Использование коллекции листов

Рабочая книга имеет еще одну коллекцию, похожую на Worksheets под названием Sheets. Это иногда путает пользователей. Чтобы понять, в первую очередь, вам нужно знать о типе листа, который является диаграммой.

В Excel есть возможность создать лист, который является диаграммой. Для этого нужно:

  1. Создать диаграмму на любом листе.
  2. Щелкнуть правой кнопкой мыши на графике и выбрать «Переместить».
  3. Выбрать первый вариант «Новый лист» и нажмите «ОК».

Теперь у вас есть рабочая книга, в которой есть типовые листы и лист-диаграмма.

  • Коллекция «Worksheets » относится ко всем рабочим листам в рабочей книге. Не включает в себя листы типа диаграммы.
  • Коллекция Sheets относится ко всем листам, принадлежащим книге, включая листы типовой диаграммы.

Ниже приведены два примера кода. Первый проходит через все
листы в рабочей книге и печатает название листа и тип листа. Второй пример
делает то же самое с коллекцией Worksheets.

Чтобы опробовать эти примеры, вы должны сначала добавить лист-диаграмму в свою книгу, чтобы увидеть разницу.

Sub KollSheets()

    Dim sht As Variant
    ' Показать название и тип каждого листа
    For Each sht In ThisWorkbook.Sheets
        Debug.Print sht.Name & " is type " & TypeName(sht)
    Next sht

End Sub

Sub KollWorkSheets()

    Dim sht As Variant
    ' Показать название и тип каждого листа
    For Each sht In ThisWorkbook.Worksheets
        Debug.Print sht.Name & " is type " & TypeName(sht)
    Next sht

End Sub

Если у вас нет листов диаграмм, то использование коллекции Sheets — то же самое, что использование коллекции WorkSheets.

Заключение

На этом мы завершаем статью о Worksheet VBA. Я надеюсь, что было полезным.

Три наиболее важных элемента Excel VBA — это рабочие книги, рабочие таблицы, диапазоны и ячейки.

Эти элементы будут использоваться практически во всем, что вы делаете. Понимание их сделает вашу жизнь намного проще и сделает изучение VBA увлекательнее.

It’s an Excel 4.0 Macro sheet, part of the XLM macro language.
It’s included for backward compatibility to versions up to Excel 4.
The VBA language was introduced in Excel 5, and is vastly superior in every way, so XLM has been phased out.

To use it (not recommended), you write a series of XLM commands in a column. It will be executed top down. To declare it, you select the top cell of that range, then under the ‘insert’ menu, under the ‘name’ submenu, pick ‘define’. Give it a suitable name and hit ‘add’. Then select it within the same dialog, and radio buttons will appear below. They will offer ‘command’, ‘function’, or ‘none’. Choose command or function, as appropriate.

You may even call a VBA procedure from an Excel 4.0 XLM macro
by using XLM’s RUN function. For example, the following macro runs the Test subroutine contained in Module1 in workbook Book1.xls:

=RUN(Book1.xls!Module1.Test)

As said in this article :

thanks to Microsoft’s practice of “strategic incompatibility” and utter contempt for the investment made by their customers, these rudimentary macros have required specific modifications for every single new version of Excel in the decade since they were originally released, and things have gotten worse, not better, since Microsoft introduced the new Visual Basic programming language for Excel (itself a cesspool of release-to-release incompatibility)

If you wish to know more about XLM, here are some resources:

  • Working with Excel 4.0 macros
  • Help File for Excel 4.0 Macros (requires winhlp32)

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

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

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

How?

Icon image

Before you record a macro    

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

Developer tab on the ribbon

Icon image

Record a macro    

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

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

    Record Macro

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

  4. On the Developer tab, click Stop Recording.

    Stop Recording

Icon image

Take a closer look at the macro    

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

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

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

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

Next steps

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

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

How?

Icon image

Before you record a macro    

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

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

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

Icon image

Record a macro    

  1. On the Developer tab, click Record Macro.

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

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

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

Icon image

Take a closer look at the macro    

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

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

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

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

Need more help?

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

Need more help?

What is MACRO in Excel?

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

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

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

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

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

Enable the Developer tab

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

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

    Activate developer Tab step 1

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

    Activate developer Tab step 2

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

    Activate developer Tab step 3

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

    Activate developer Tab step 4

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

    Activate developer Tab step 5

Examples of Macros in Excel

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

Example #1

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

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

Macro Example 1

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

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

Macro Example 1-1

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

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

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

Macro Example 1-2

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

Macro Example 1-3

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

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

Shortcut key to Find

Macro Example 1-4

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

Macro Example 1-5

  • The final output is displayed in the below image.

Macro Example 1-6

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

Example #2

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

Macro Example 1-7

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

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

Macro Example 1-8

Adding the Macro Button

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

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

Macro Example 1-9

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

Macro Example 1-10

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

Macro Example 1-11

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

Macro Example 1-12

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

Macro Example 1-13

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

Macro Example 1-14

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

Macro Example 1-15

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

How to View the Code of Macros?

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

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

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

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

Macro Example 1-16

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

Macro Example 1-17

Creating Macro by Writing VBA Code

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

Macro Example 2-1

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

Generally, there are two types of macros.

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

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

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

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

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

Macro Example 2

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

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

Macro Example 2-1

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

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

Macro Example 2-2

  • The output is displayed in the succeeding image.

Macro Example 2-3

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

How to Save the Recorded Macro in Excel?

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

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

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

Save Macro

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

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

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

Macro Warning

How to Enable “Macro Security Settings”?

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

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

Macro Security Warning

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

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

Macro Security

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

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

Frequently Asked Questions (FAQs)

1. What are macros in Excel?

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

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

2. How to enable macros in Excel?

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

3. What is the difference between macro and VBA?

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

Recommended Articles

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

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

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

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

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

Why are Excel Macros Used in Excel?

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

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

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

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

What is VBA in a Layman’s Language?

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

Excel Macro Basics

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

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

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

The macro name should not contain any spaces.

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

Step by Step Example of Recording Macros in Excel

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

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

Introduction to Macros in Excel

You can download the above file here

Download the above CSV File & Macros

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

Enable Developer Option

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

Step 1)Go to main menu “FILE”

Select option “Options.”

How to Write Macros in Excel

What is VBA?

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

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

How to Write Macros in Excel

Step 3) Developer Tab

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

How to Write Macros in Excel

Step 4) Download CSV

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

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

How to Write Macros in Excel

Step 5) Record Macro

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

How to Write Macros in Excel

You will get the following dialogue window

Introduction to Macros in Excel

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

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

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

You will get the following dialogue window

How to Write Macros in Excel

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

You will get the following wizard

Introduction to Macros in Excel

Click on Next button after following the above steps

Introduction to Macros in Excel

Follow the above steps and click on next button

Introduction to Macros in Excel

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

Introduction to Macros in Excel

Step 7) Format the Data

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

How to Write Macros in Excel

Step 8) Stop Recording Macro

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

How to Write Macros in Excel

Step 9) Replay the Macro

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

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

How to Write Macros in Excel

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

You will get the following dialogue window

Introduction to Macros in Excel

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

You will get the following data

Introduction to Macros in Excel

Congratulations, you just created your first macro in Excel.

Summary

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

Понравилась статья? Поделить с друзьями:
  • What is a lookup function in excel
  • What is a french word family
  • What is a long vowel sound word
  • What is a free word group
  • What is a logo in microsoft word