Excel vba worksheet object methods

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

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 увлекательнее.

Skip to content

VBA Worksheet Methods

  • Excel VBA Worksheet Object11

Worksheet methods helps us to perform different actions with Excel Worksheets. For example, we can Activate a Worksheet and Delete a Worksheet or Move Worksheet. And also we can Protect and UnProtect Worksheets. Explore the various methods and examples on Excel VBA Worksheet using side navigation. Below are the most frequently used Excel VBA Worksheet methods.

Excel VBA Worksheet Object11

Excel VBA Worksheet Object Methods:

  • Activate: To Activate a Worksheet
  • Calculate: To Refresh the calculations of Worksheet
  • Copy: To Copy a Worksheet
  • Delete: To Delete a Worksheet
  • Move: To Move a Worksheet
  • Protect: To Protect a Worksheet
  • Select: To Select a Worksheet
  • UnProtect: To UnProtect a Worksheet
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates
  • Excel VBA Worksheet Object Methods:

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:
By PNRaoLast Updated: March 2, 2023

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Excel VBA Tutorial about Object MethodsIf you’re in the process of learning Visual Basic for Applications, there are a few basic topics you need to thoroughly understand. I have explained some of these in other blog posts that you can find at the Power Spreadsheets Archive.

However, at the most basic level, the following 3 topics are perhaps the most basic things you need to learn and understand in order to start making useful things with VBA:

  1. Objects.
  2. Object properties.
  3. Object methods.

You can read some of the tutorials I’ve written about the first 2 topics here, here (for objects), and here (for properties). This blog post focuses on the third item in the list above:

Methods.

More precisely, I explain the most important aspects you need to know in order to start working with object methods in VBA. You can use the following table of contents to navigate directly to any section you’re most interested in. Make sure to read the full post in any case 😉 .

OK. Let’s go straight into the topic of today’s post and take a closer look at…

What Are Object Methods In VBA And Why Are They Important

There’s no question that knowing about VBA objects is extremely important. To achieve something of practical value, you must do something with/to the object(s) you work with.

Therefore, you must know about VBA objects in order to become a great Excel VBA programmer. However, this isn’t enough on its own…

You also need to know and understand how you can manipulate those objects. And this is where object methods and object properties come in:

Methods are the actions or operations you perform with an object (by or on the object). Properties, on the other hand, are the attributes or characteristics you can use to describe the object.

According to a common analogy (between VBA and the parts of speech in the English language), you can think of:

  • Objects as akin to nouns.
  • Properties as analogous to adjectives.
  • Methods as corresponding to verbs.

It’s not possible to communicate fluently in English by just using nouns (without also using adjectives and verbs). Similarly, you can’t build appropriate VBA applications by just using objects (without also including properties and methods).

The ability of specifying the action to be applied to an object allows you to use methods for the following 2 main purposes:

  • Purpose #1: Make an object do something.
  • Purpose #2: Modify the properties of an object. Consider (for ex.) the Range.ClearContents method. The Range.ClearContents method:
    • Clears values and formulas from the applicable cell range.
    • (Generally) Results in a change to the applicable Range.Value property (the cell range’s value).

This applies to object collections as well. The reason for this, as explained here, is that collections are themselves objects.

However, in order to ensure that you do a great job with the object methods you’ll need to use, let’s take a look at…

How To Work With Object Methods In VBA

Let’s start to take a closer look at how you structure a statement that refers to (or calls/access) object methods. For these purposes, we’ll examine the following macro (called “Delete_Inactive_Worksheets”). The purpose of this Sub procedure is to delete all worksheets except for the one that’s currently active.

Sub Delete_Inactive_Worksheets()
    Dim my_Worksheet As Worksheet
    For Each my_Worksheet In ThisWorkbook.Worksheets
        If my_Worksheet.Name <> ThisWorkbook.ActiveSheet.Name Then
            Application.DisplayAlerts = False
            my_Worksheet.Delete
            Application.DisplayAlerts = True
        End If
    Next my_Worksheet
End Sub

This Excel VBA Methods Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following screenshot shows how the VBA code of the Delete_Inactive_Worksheets macro looks like in the Visual Basic Editor:

Example macro to illustrate VBA object properties

I won’t explain this particular macro line-by-line. For purposes of this Excel tutorial, we’ll focus on the following statement:

my_Worksheet.Delete

This statement is within the If…Then statement in the macro above. The relevant row of code is underlined in the following screenshot:

Macro example with highlighted VBA object method

This simple statement is enough to illustrate the basic rule to create references to object properties in Visual Basic for Applications:

You refer to (or call/access) a method by putting together the following 3 items:

  • Item #1: Name of the relevant VBA object. In the case above, this is the object variable my_Worksheet.
  • Item #2: A dot (.).
  • Item #3: Name of the method. In the case above, this is “Delete” or, more precisely, the Worksheet.Delete method.

In fact, most procedures have a number of lines following this basic structure:

Object.Method

Under this (basic) statement structure, the item after the dot (Method in the case above) acts on/with the item before the dot (Object in the case above).

One final note before we move on to the next section:

Note how, above, I mention specifically the Worksheet.Delete method instead of simply referring to the Delete method. This is important because a method may behave differently depending on the object it works with.

For example, when it comes to the Delete method, its syntax and precise behavior can be slightly different depending on whether it is applied to a Worksheet object (Worksheet.Delete method) or a Range object (Range.Delete method). Yes, in both cases the end result is that Excel deletes the relevant object. However:

  • When applied to a Range object, the Delete method has an extra argument (I explain method arguments below) which allows you to determine how Excel shifts the cells that replace any deleted cells.
  • When working with a Worksheet object, the method displays (by default) a dialog box asking you to confirm the worksheet deletion.

As you continue to work with Excel and Visual Basic for Applications, these nuances will become clearer. However, you may want to confirm that your choice of VBA object methods actually carry out the actions you want them to when working with the VBA objects you’re working with.

How To Work With The Arguments (Or Parameters) Of Object Methods In VBA

Arguments (also known as parameters) are, generally, what allows you to further determine the action that a method performs with an object.

In other words: Parameters allow you to determine “how” the action/method is carried out.

Going back to the parallel between VBA and the parts of speech of regular English, you can think of method arguments as being comparable to adverbs.

Some, but not all, object methods in VBA take arguments. Arguments can be mandatory or optional.

The topic of arguments is, actually, not as easy as you may think at first glance. In this section, we take a look at the most important aspects you must know in connection with this topic.

For purposes of illustrating how to work with the arguments of object methods in VBA, I make reference to the following simple macro (called “Copy_Main_Worksheet”). The Copy_Main_Worksheet macro (i) copies the worksheet called “Object Methods in VBA” and (ii) pastes the copy after the worksheet named “Sheet1”.

Sub Copy_Main_Worksheet()
    Worksheets("Object Methods In VBA").Copy After:=Worksheets("Sheet1")
End Sub

This Excel VBA Methods Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the macro above). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

The following image shows the VBA code of the Copy_Main_Worksheet within the Visual Basic Editor:

Example macro with object property argument

Let’s focus on the relevant statement of this macro, which is underlined in the image below:

VBA code example with object method arguments

You already know how to refer to object methods, the topic I explain above. Therefore, you probably identify the first part of the statement (“Worksheets(“Object Methods In VBA”).Copy”) as a reference that is divided in the following 3 items:

  • Item #1: “Worksheets(“Object Methods In VBA”)” makes reference to the Worksheet object named “Object Methods In VBA”.
  • Item #2: A dot (.) separates part #1 above from part #3 below.
  • Item #3: “Copy” makes reference to the Worksheet.Copy method.

The second part of the statement (“After:=Worksheets(“Sheet1″)”) is the part that sets the relevant method parameters. More precisely, it determines that the copied worksheet is placed after the sheet called “Sheet1”.

The Worksheet.Copy method has 2 optional but exclusive (you can only specify one of them) parameters:

  • Optional Parameter #1: “Before”, which determines which is the sheet in front of (or before) which the copied worksheet is placed.
  • Optional Parameter #2: “After”, which sets what is the sheet after which the copied worksheet is placed.
    • This is the parameter I use in this example. In other words: The copied worksheet is placed after “Sheet1”.

The following image breaks down the statement in the parts and items I explain above:

Macro explaining method arguments

This way of setting method parameters (which I explain below) isn’t the only syntax you can use. More precisely:

There are a few ways in which you can work with the arguments of object methods. In order to understand this better, let’s take a look at the most important ways in which you can specify the arguments for an object method in VBA:

Option #1: Basic Syntax To Specify Object Method Arguments

The Copy_Main_Worksheet macro that appears above doesn’t use the most basic form of syntax to specify method arguments. Although…

After going through this section you’ll probably:

  • Think that the basic syntax isn’t really that basic.
  • Understand why I use another syntax (which I explain below) in the version of the Copy_Main_Worksheet macro that appears above.

The following version of the Copy_Main_Worksheet macro uses the basic syntax to set the arguments of an object method. Notice the difference between both versions when it comes to referring to the method parameters.

Example of basic syntax VBA method property

I explain why there’s a comma (,) at the beginning of this part of the statement below. Excluding that comma, the basic syntax to specify arguments is relative straightforward:

Object.Method Argument_Value

In other words, to determine an argument for a VBA object method, you must:

  • Step #1: Refer to the object method appropriately by following the basic syntax explained above.
    • In the case above, this is “Worksheets(“Object Methods In VBA”).Copy”.
  • Step #2: Place a space ( ) after the name of the method.
  • Step #3: Place the relevant argument values.
    • In the example above, this is “, Worksheets(“Sheet1″)”.

You already know what “Worksheets(“Sheet1″)” does: It’s the After parameter that determines that the copied worksheet is placed after “Sheet1”.

That leaves the comma (,) at the beginning.

Syntax for several VBA object methods

This comma (,) appears because of the following 3 syntax rules:

  • When using more than 1 argument, use commas (,) to separate them.
  • When working with unnamed arguments, enter arguments in their default order.
  • When working with optional (and unnamed) arguments, use commas (,) to create blank placeholders for omitted arguments.
    • There are some cases where you don’t need to create placeholders for omitted arguments (for ex., when the argument you omit is at the end of the argument list).

In this case, the Worksheet.Copy method has 2 optional but exclusive arguments: Before and After. The Copy_Main_Worksheet uses only the second argument (After). Therefore, the VBA code that appears above includes a comma (,) and a blank placeholder for the unused Before argument.

As you see, the “basic” syntax to specify the arguments of a method isn’t that readable. And this was a single (and quite straightforward statement)…

Just imagine how it would be to work in a large and complex VBA application that uses this syntax and has plenty of methods with optional arguments and blank placeholders 😕 .

Fortunately, there is a second way in which you can set the parameters that clarify the action to be taken by a particular method. This is the syntax used in the original version of the Copy_Main_Worksheet macro above. Let’s take a look at it:

Option #2: Named Arguments

As implied by the description of this way of referring to the arguments of VBA object properties, you use the actual name of the argument when specifying it. More precisely, you use the following syntax:

Object.Method Argument_Name:=Argument_Value

In other words, when using named arguments you proceed as follows:

  • Step #1: Repeat the first 2 steps described above where I describe the basic syntax to specify the arguments of object methods.
    • In other words: (i) refer to the object method appropriately, and (ii) place a space after the name of the method.
  • Step #2: Write the (official) name of the argument.
  • Step #3: Place a colon and an equal sign (:=).
  • Step #4: Set the relevant argument value.

This is the syntax that I use in the first version of the Copy_Main_Worksheet macro that appears above.

Named argument for VBA object method

When you use named arguments for object methods in VBA, you don’t have to use any placeholder for the optional arguments that you don’t use. Therefore, in this case, there’s no placeholder at all for the missing Before argument of the Worksheets.Copy method.

You don’t need to use named arguments (is optional) and can get away with using the basic syntax described above. However, using named arguments has a few advantages over not using them, particularly the fact that named arguments improve the readability of your VBA code.

You can (theoretically):

  • Start specifying arguments using the basic syntax described above; and
  • Switch to named arguments at some point in the middle of the argument list. Once you include a named method argument, the remaining method arguments must (also) be named.

However, I don’t necessarily recommend this syntax.

Even though you can switch from non-named arguments to named arguments in the middle of a statement, you can’t do the opposite. In other words, you can’t start specifying parameters using named arguments and then switch to the basic syntax. Once you use named arguments once, you must continue working with named parameters for that particular line.

After comparing both syntax options for setting VBA object method parameters, you’ll probably agree that using named arguments is (as a general rule) a better practice.

Before we finish the topic of specifying arguments for object methods in VBA, let’s take a look at 2 additional clarifications regarding the syntax you use when setting VBA method arguments:

Referring To The Arguments Of Methods That Return A Value And Working With Default Argument Values

When working with methods that return a value or create new objects, you must (generally) wrap the arguments in parentheses. In such cases, as long as the arguments are within the parentheses, you can continue to use either of the 2 syntax options that I describe above (unnamed or named arguments).

Finally, note that several objects within Visual Basic for Applications have a particular default method value. You don’t necessarily have to provide a method value in such cases. This also applies to those methods that take more than 1 argument: some arguments may have default values while other don’t.

How To Access The Methods Of A Particular Object

A single object can have more than 1 associated method. In fact:

  • Some VBA objects have several dozen methods.
  • The Excel VBA Object Model contains thousands of methods.

But don’t feel overwhelmed!

In practice, you’re likely to work with a relatively small amount of VBA object methods over and over again. This is partly due to the fact that a single method can be associated to several VBA objects.

In other words: You’re unlikely to (in practice) work with certain methods.

However, it’s quite likely that (from time to time) you’ll need to search for a particular method while working with macros. Therefore, let’s take a look at some of the most common strategies you can use to find out the best VBA object method to achieve your goals in a particular situation.

In addition to the 3 strategies I explain below, you can also use the macro recorder to get some guidance about the objects, properties and methods you need.

Strategy #1: How To Make The Visual Basic Editor Display A List Of Methods

This is probably the easiest and most convenient way to explore the properties available for a particular VBA object. However, it only works if the Auto List Members setting of your Visual Basic Editor is enabled. In case you don’t have this setting enabled, I explain how to do it in this Excel tutorial.

In order to understand how you can make the VBE display a list of available methods, let’s go back to the code for the Delete_Inactive_Worksheets. More particularly, let’s assume that you’re typing the statement “my_Worksheet.Delete” (which I explain above) and you’re standing at the point where we must type the dot.

VBA code before VBE displays methods

Once you type the dot, the VBE displays a list of items that can be associated with that particular object. Therefore, in the case above, once you type the dot that follows my_Worksheet, the following list is shown:

VBA object method list displayed by VBE

This gives you a great idea of the properties and methods that you can use when working with a particular object. For example, if you scroll down enough, you can find the Delete method. This is the appropriate method to complete the statement above.

Delete method in list within VBE

In order to be able to take advantage of this setting, your Visual Basic Editor must have the Auto List Members setting option enabled.

Strategy #2: Use The Object Browser

As explained by Chandoo (in the webpage I link to above), the Object Browser is a “helpful screen” that allows you to browse and understand VBA objects, properties and methods.

You can use the Object Browser to obtain all the available properties and methods for a particular object in 3 simple steps:

Step #1: Open The Object Browser

There are a few ways to access the Object Browser from within the Visual Basic Editor:

Step #2: Select The Excel Library

The drop-down list that appears on the top left corner of the Visual Basic Editor (“<All Libraries>”) displays all the object libraries that are available. Click on this drop-down menu and select Excel.

Select Excel library in Object Browser

Step #3: Select The Relevant Object Class

The Object Browser is divided in 2 sections:

  • Left section: Lists all the Excel objects.
  • Right section: Displays all the properties and methods that are available for the object that is currently selected on the left.

Therefore, in order to access the VBA methods of a particular object, search the object you want to explore on the left side of the Object Browser and click on it.

For example, in the case of sample macros used throughout this Excel tutorial, it’s interesting to see what happens when clicking on “Worksheet”. As you can see in the image below, the Object Browser displays a list of its members. This list includes both the Copy and Delete methods used by the Copy_Main_Worksheet and Delete_Inactive_Worksheets macro (respectively).

Methods available for Worksheet object in VBA

Strategy #3: Visit Microsoft’s Official Documentation

Microsoft’s Official Documentation has a massive amount of content regarding VBA objects and methods (among others).

One of the things you can use Microsoft’s Official Documentation for, is to get a list of all the methods that are available for a particular VBA object. To do this, simply follow these 4 easy steps:

Step #1: Type The Name Of An Object In The Visual Basic Editor

As an example, let’s go back to the Copy_Main_Worksheets used as an example above. Assume that you’re typing the only statement of this Sub procedure. Therefore, you type the relevant object which, in this case, is “Worksheets(“Object Methods In VBA”)”.

Example of object within macro

However, now that you’ve identified the VBA object, you want to see which methods can be used on that particular object.

Step #2: Place The Cursor On The Object

In the case above you can, for example, place the cursor within the word “Worksheets”, as shown below:

Cursor on object within VBE

Step #3: Press The F1 Key

F1 is the keyboard shortcut for opening the help system. In other words, this keyboard shortcut generally should either:

  • Take you to the relevant page within Microsoft’s Official Documentation; or
  • Ask you to confirm what the topic you want to help on is. This is the case, generally, when the Visual Basic Editor finds multiple instances of the word that you’ve selected.

In this particular case, once I press the F1 key, I’m led to the page about the Application.Worksheets property within the Microsoft Dev Center.

Help for VBE in MSDN

Step #4: Navigate To The Methods Of The Relevant Object

In some cases (such as the example above), you may need to do some navigation before you actually get to the appropriate object. The reason for this is that, most objects within VBA are accessed by using a property.

For example in the case above, the Application.Worksheets property is used to return a Worksheet object. Therefore, we’re originally taken to the webpage belonging to this particular property.

However, this navigation is usually not very complicated. In the case of the Application.Worksheets property, notice how Microsoft’s Official Documentation immediately explains that the property returns a collection (which is an object itself) representing worksheets. It also includes a link leading to the Sheet object (see image below).

Example of page in MSDN

In turn, the page covering the Sheets object explains how this collection “can contain Chart or Worksheet objects”. The website, again, displays a conspicuous link that you can click to get to the Worksheets object.

Example of MSDN website

In the case above, it took a little bit longer than usual to get to the appropriate page. However, once you’re in the page that makes reference to the relevant object, you can get Microsoft’s Official Documentation to show you all the available methods by expanding the list that appears on the left side of the page.

Methods in Microsoft Developer Network

In the case above, one of those available methods is indeed the Worksheet.Copy method used by the Copy_Main_Worksheet sample macro.

Access Worksheet.Copy method in MSDN

Conclusion

I mentioned at the beginning of this blog post that having a good understanding about VBA objects, properties and methods is essential in order to do any meaningful work with Visual Basic for Applications. This Excel tutorial has provided you with the fundamental knowledge you need in order to start using methods when coding in VBA. Among other topics, we’ve covered:

  • What are object methods in VBA, and why are they important.
  • How do you create references for a method.
  • How can you set the parameters or arguments of a particular method.
  • 3 different strategies you can use to find out what are the properties you can use when working with a particular VBA object.

Home / VBA / VBA Objects / VBA Worksheet Object -Working with Excel Worksheet in VBA

In VBA, the worksheet object represents a single worksheet that is a part of the workbook’s worksheets (or sheets) collection. Using the worksheet object, you can refer to the worksheet in a VBA code, and refer to a worksheet you can also get access to the properties, methods, and events related to it.

Here’s a small snapshot of where a worksheet stands in the Excel object hierarchy.

Application Workbook Worksheets Worksheet

In this tutorial, we will learn about using and referring to a worksheet in Excel using a VBA code.

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Sheets Vs. Worksheets

First thing first. This is important to understand the difference between a worksheet and a sheet. In Excel, you have types of sheets that you can insert into a workbook, and a worksheet is one of those types. As you can see in the below snapshot when you insert a new sheet Excel asks you to select the sheet type.

Here’s the point to understand: When you use the word “Sheets” you are referring to all the sheets (Worksheets, Macro Sheets, and Chart Sheets), but when you use the word “Worksheet” you are referring only to the worksheets (see also).

Accessing a Worksheet (Sheet) using VBA

VBA gives you different ways to access a worksheet from a workbook, and ahead, we will see different ways to do that.

1. Refer to a Sheet using the Name

Every sheet has its name to identify it, and you can use it to refer to that sheet as well. Let’s say you want to refer to the “Sheet1”, the code would be:

Sheets(“Sheet1”)
Worksheets(“Sheet1”)

Both above codes refer to the “Sheet1”.

2. Refer to Sheet using Number

You can also use a sheet’s number to refer to it. Let’s if a sheet is at the fifth position in the workbook then you can use this number to refer to it.

Sheets (5)
Worksheets (5)

Now here above two lines of code work in two different ways. The first line refers to the 5th sheet, and the second line refers to the 5th worksheet in the workbook.

3. Refer to the ActiveSheet

If a sheet is already active, then you can refer to it, using the keyword “Activesheet” instead of its name.

ActiveSheet

If you want to perform an activity in the ActiveSheet, you can use the “Activesheet” object, but if you skip using it, VBA will still perform the activity in the active sheet.

Read: Select a Range using VBA

4. Refer to a Sheet using Code Window Name

Each sheet has its code window, and there’s a name to that code window. Usually, a user can change the sheet name from the tab, but the name that you have in the code window can’t be changed unless you do it from the properties.

Open the Visual Basic Editor from the Developer Tab, and in the properties section, you can see the name of the sheet that you have selected.

And you can also change this name from the properties section.

Now you can refer to it by using the code window name.

mySheet

5. Refer to More than One Sheet

You can also refer to more than one sheet in one go using a single line of code. For this, you can use an array, just like the following code.

Sheets(Array("Sheet1", "Sheet2"))

This code refers to “Sheet1” and “Sheet2”, but, there’s one thing that you need to understand when you refer to more than one sheet, there are a few methods and properties that you can’t use.

6. Refer to Sheet in a Different Workbook

A worksheet or a sheet is a part of the worksheets collection in a workbook, and if you want to refer to a specific sheet other than the active workbook, then you need to refer to that workbook first.

Workbooks("Book1").Sheets("Sheet1")

To run this code, you need to have “Book1” open.

Properties, Methods, and Events Related to a Sheet or a Worksheet

In VBA, each Excel object has some properties, methods, and events that you can use, and in the same way, you can access the properties and methods that come with it. Once you specify a worksheet, type a dot (.), and you’ll get the list.

In this list, all the icons where you can see a hand are properties, and where you have green brick are methods.

Property Example

Let’s say you want to change the color of the worksheet’s tab, in this case, you can use the TAB property of the worksheet.

mySheet.Tab.ThemeColor = xlThemeColorAccent2

In the above line of code, you have the tab property and further theme color property to change the tab color of the worksheet.

Method Example

In the same way, you can use the methods that come with worksheets. One of the most common methods is the “Select” method that you can use to select a sheet.

mySheet.Select

The moment you run this code, it selects the “mySheet” from the active workbook.

Event Example

Some events are associated with a worksheet. For example, when you activate a sheet, that’s an event, and in the same way, when you change something within the sheet. See the following code where you have code to run when an event (change in the worksheet) happens.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range("A1").Value = Range("A1").Value + 1
End Sub

This code enters a value in the cell A1 of the sheet every time you make a change in the worksheet.

Declaring a Worksheet Object

You can also declare a variable as a worksheet, making it easy to use that worksheet in a VBA code. First, use the DIM keyword, and then the name of the variable. After that, specify the object type as a worksheet.

More on VBA Worksheets

Activate a Sheet | Add a New Sheet | Copy a Sheet | Rename a Sheet | Hide a Sheet | Delete Sheet | Protect Sheet | Clear a Sheet | Check IF Sheet Exists | Loop Through Each Sheet in the Workbook | Count Sheets

  • VBA Tutorial

 
“The visionary starts with a clean sheet of paper, and re-imagines the world” – Malcolm Gladwell

 
This post provides a complete guide to using the Excel VBA Worksheet in Excel VBA. If you want to know how to do something quickly then check out the quick guide to the VBA Worksheet below.

If you are new to VBA then this post is a great place to start. I like to break things down into simple terms and explain them in plain English without the jargon.

You can read through the post from start to finish as it is written in a logical order. If you prefer, you can use the table of contents below and go directly to the topic of your choice.

A Quick Guide to the VBA Worksheet

The following table gives a quick run down to the different worksheet methods.

Note: I use Worksheets in the table below without specifying the workbook i.e.Worksheets rather than ThisWorkbook.Worksheets, wk.Worksheets etc. This is to make the examples clear and easy to read. You should always specify the workbook when using Worksheets. Otherwise the active workbook will be used by default.

Task How to
Access worksheet by name Worksheets(«Sheet1»)
Access worksheet by position from left Worksheets(2)
Worksheets(4)
Access the left most worksheet Worksheets(1)
Access the right most worksheet Worksheets(Worksheets.Count)
Access using worksheet code name(current workbook only) see Code Name section below
Access using worksheet code name(other workbook) see Code Name section below
Access the active worksheet ActiveSheet
Declare worksheet variable Dim sh As Worksheet
Assign worksheet variable Set sh = Worksheets(«Sheet1»)
Add worksheet Worksheets.Add
Add worksheet and assign to variable Set sh =Worksheets.Add
Add worksheet to first position(left) Worksheets.Add Before:=Worksheets(1)
Add worksheet to last position(right) Worksheets.Add after:=Worksheets(Worksheets.Count)
Add multiple worksheets Worksheets.Add Count:=3
Activate Worksheet sh.Activate
Copy Worksheet sh.Copy
Copy after a worksheet sh1.Copy After:=Sh2
Copy before a worksheet sh1.Copy Before:=Sh2
Delete Worksheet sh.Delete
Delete Worksheet without warning Application.DisplayAlerts = False
sh.Delete
Application.DisplayAlerts = True
Change worksheet name sh.Name = «Data»
Show/hide worksheet sh.Visible = xlSheetHidden
sh.Visible = xlSheetVisible
Loop through all worksheets(For) Dim i As Long
For i = 1 To Worksheets.Count
    Debug.Print Worksheets(i).Name
Next i
Loop through all worksheets(For Each) Dim sh As Worksheet
For Each sh In Worksheets
    Debug.Print sh.Name
Next

Introduction

The three most important elements of VBA are the Workbook, the Worksheet and Cells. Of all the code your write, 90% will involve one or all of them.

The most common use of the worksheet in VBA is for accessing its cells. You may use it to protect, hide, add, move or copy a worksheet. However, you will mainly use it to perform some action on one or more cells on the worksheet.

 
Using Worksheets is more straightforward than using workbooks. With workbooks you may need to open them, find which folder they are in, check if they are in use and so on. With a worksheet, it either exists in the workbook or it doesn’t.

Accessing the Worksheet

In VBA, each workbook has a collection of worksheets. There is an entry in this collection for each worksheet in the workbook. This collection is simply called Worksheets and is used in a very similar way to the Workbooks collection. To get access to a worksheet all you have to do is supply the name.

 
The code below writes “Hello World” in Cell A1 of Sheet1, Sheet2 and Sheet3 of the current workbook.

' https://excelmacromastery.com/
Public Sub WriteToCell1()

    ' Write To cell A1 In Sheet1,Sheet2 And Sheet3
    ThisWorkbook.Worksheets("Sheet1").Range("A1") = "Hello World"
    ThisWorkbook.Worksheets("Sheet2").Range("A1") = "Hello World"
    ThisWorkbook.Worksheets("Sheet3").Range("A1") = "Hello World"

End Sub

 
The Worksheets collection is always belong to a workbook. If we don’t specify the workbook then the active workbook is used by default.

' https://excelmacromastery.com/
Public Sub WriteToCell1()

    ' Worksheets refers to the worksheets in the active workbook
    Worksheets("Sheet1").Range("A1") = "Hello World"
    Worksheets("Sheet2").Range("A1") = "Hello World"
    Worksheets("Sheet3").Range("A1") = "Hello World"

End Sub

Hide Worksheet

The following examples show how to hide and unhide a worksheet

ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetHidden

ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetVisible

 
If you want to prevent a user accessing the worksheet, you can make it “very hidden”. This means it can only be made visible by the code.

' Hide from user access
ThisWorkbook.Worksheets("Sheet1").Visible = xlVeryHidden

' This is the only way to make a xlVeryHidden sheet visible
ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetVisible

Protect Worksheet

Another example of using the worksheet is when you want to protect it

ThisWorkbook.Worksheets("Sheet1").Protect Password:="MyPass"

ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="MyPass"

Subscript Out of Range

When you use Worksheets you may get the error:

Run-time Error 9 Subscript out of Range

 
VBA Subscript out of Range

 
This means you tried to access a worksheet that doesn’t exist. This may happen for the following reasons

  1. The worksheet name given to Worksheets is spelled incorrectly.
  2. The name of the worksheet has changed.
  3. The worksheet was deleted.
  4. The index was to large e.g. You used Worksheets(5) but there are only four worksheets
  5. The wrong workbook is being used e.g. Workbooks(“book1.xlsx”).Worksheets(“Sheet1”) instead of Workbooks(“book3.xlsx”).Worksheets(“Sheet1”).

 
If you still have issues then use one of the loops from Loop Through The Worksheets section to print the names of all worksheets the collection.

Using the Index  to Access the Worksheet

So far we have been using the sheet name to access the sheet. The index refers to the sheet tab position in the workbook. As the position can easily be changed by the user it is not a good idea to use this.

 
The following code shows examples of using the index

' https://excelmacromastery.com/
' Using this code is a bad idea as
' sheet positions changes all the time
Public Sub UseSheetIdx()

    With ThisWorkbook
        ' Left most sheet
        Debug.Print .Worksheets(1).Name
        ' The third sheet from the left
        Debug.Print .Worksheets(3).Name
        ' Right most sheet
        Debug.Print .Worksheets(.Worksheets.Count).Name
    End With

End Sub

 
In the example above, I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)

ImmediateWindow

ImmediateSampeText

Using the Code Name of a Worksheet

The best method of accessing the worksheet is using the code name. Each worksheet has a sheet name and a code name. The sheet name is the name that appears in the worksheet tab in Excel.

Changing the sheet name does not change the code name meaning that referencing a sheet by the code name is a good idea.

 
If you look in the VBE property window you will see both names. In the image you can see that the code name is the name outside the parenthesis and the sheet name is in the parenthesis.

code name worksheet

 
 
You can change both the sheet name and the code name in the property window of the sheet(see image below).

 
If your code refers to the code name then the user can change the name of the sheet and it will not affect your code. In the example below we reference the worksheet directly using the code name.

' https://excelmacromastery.com/
Public Sub UseCodeName2()

    ' Using the code name of the worksheet
    Debug.Print CodeName.Name
    CodeName.Range("A1") = 45
    CodeName.Visible = True

End Sub

 
This makes the code easy to read and safe from the user changing the sheet name.

Code Name in other Workbooks

There is one drawback to using the code name. It can only refer to worksheets in the workbook that contains the code i.e. ThisWorkbook.

 
However, we can use a simple function to find the code name of a worksheet in a different workbook.

' https://excelmacromastery.com/
Public Sub UseSheet()

    Dim sh As Worksheet
    ' Get the worksheet using the codename
    Set sh = SheetFromCodeName("CodeName", ThisWorkbook)
    ' Use the worksheet
    Debug.Print sh.Name

End Sub

' This function gets the worksheet object from the Code Name
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

 
Using the above code means that if the user changes the name of the worksheet then your code will not be affected.

There is another way of getting the sheet name of an external workbook using the code name. You can use the VBProject element of that Workbook.

 
You can see how to do this in the example below. I have included this for completeness only and I would recommend using the method in the previous example rather than this one.

' https://excelmacromastery.com/
Public Function SheetFromCodeName2(codeName As String _
                             , bk As Workbook) As Worksheet

    ' Get the sheet name from the CodeName using the VBProject
    Dim sheetName As String
    sheetName = bk.VBProject.VBComponents(codeName).Properties("Name")

    ' Use the sheet name to get the worksheet object
    Set SheetFromCodeName2 = bk.Worksheets(sheetName)

End Function

Code Name Summary

The following is a quick summary of using the Code Name

  1. The code name of the worksheet can be used directly in the code e.g. Sheet1.Range
  2. The code name will still work if the worksheet name is changed.
  3. The code name can only be used for worksheets in the same workbook as the code.
  4. Anywhere you see ThisWorkbook.Worksheets(“sheetname”) you can replace it with the code name of the worksheet.
  5. You can use the SheetFromCodeName function from above to get the code name of worksheets in other workbooks.

The Active Sheet

The ActiveSheet object refers to the worksheet that is currently active. You should only use ActiveSheet if you have a specific need to refer to the worksheet that is active.

Otherwise you should specify the worksheet you are using.

If you use a worksheet method like Range and don’t mention the worksheet, it will use the active worksheet by default.

' Write to Cell A1 in the active sheet
ActiveSheet.Range("A1") = 99

' Active sheet is the default if no sheet used
Range("A1") = 99

Declaring a Worksheet Object

Declaring a worksheet object is useful for making your code neater and easier to read.

The next example shows code for updating ranges of cells. The first Sub does not declare a worksheet object. The second sub declares a worksheet object and the code is therefore much clearer.

' https://excelmacromastery.com/
Public Sub SetRangeVals()

    Debug.Print ThisWorkbook.Worksheets("Sheet1").Name
    ThisWorkbook.Worksheets("Sheet1").Range("A1") = 6
    ThisWorkbook.Worksheets("Sheet1").Range("B2:B9").Font.Italic = True
    ThisWorkbook.Worksheets("Sheet1").Range("B2:B9").Interior.Color = rgbRed

End Sub
' https://excelmacromastery.com/
Public Sub SetRangeValsObj()

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("Sheet1")

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

End Sub

 
You could also use the With keyword with the worksheet object as the next example shows.

' https://excelmacromastery.com/
Public Sub SetRangeValsObjWith()

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("Sheet1")

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

End Sub

Accessing the Worksheet in a Nutshell

With all the different ways to access a worksheet, you may be feeling overwhelmed or confused. So in this section, I am going to break it down into simple terms

 
1. If you want to use whichever worksheet is currently active then use ActiveSheet.

ActiveSheet.Range("A1") = 55

 
2. If the worksheet is in the same workbook as the code then use the Code Name.

Sheet1.Range("A1") = 55

 
3. If the worksheet is in a different workbook then first get workbook and then get the worksheet.

' Get workbook
Dim wk As Workbook
Set wk = Workbooks.Open("C:DocsAccounts.xlsx", ReadOnly:=True)

' Then get worksheet
Dim sh As Worksheet
Set sh = wk.Worksheets("Sheet1")

 
If you want to protect against the user changing the sheet name then use the SheetFromCodeName function from the Code Name section.

' Get workbook
Dim wk As Workbook
Set wk = Workbooks.Open("C:DocsAccounts.xlsx", ReadOnly:=True)

' Then get worksheet
Dim sh As Worksheet
Set sh = SheetFromCodeName("sheetcodename",wk)

Add Worksheet

The examples in this section show you how to add a new worksheet to a workbook. If you do not supply any arguments to the Add function then the new worksheet will be placed before the active worksheet.

When you add a Worksheet, it is created with a default name like “Sheet4”. If you want to change the name then you can easily do this using the Name property.

 
The following example adds a new worksheet and changes the name to “Accounts”. If a worksheet with the name “Accounts” already exists then you will get an error.

' https://excelmacromastery.com/
Public Sub AddSheet()

    Dim sht As Worksheet

    ' Adds new sheet before active sheet
    Set sht = ThisWorkbook.Worksheets.Add
    ' Set the name of sheet
    sht.Name = "Accounts"

    ' Adds 3 new sheets before active sheet
    ThisWorkbook.Worksheets.Add Count:=3

End Sub

 
In the previous example, you are adding worksheets in relation to the active worksheet. You can also specify the exact position to place the worksheet.

 
To do this you need to specify which worksheet the new one should be inserted before or after. The following code shows you how to do this.

' https://excelmacromastery.com/
Public Sub AddSheetFirstLast()

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

    With ThisWorkbook

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

        ' Adds new sheet to first position in the workbook
        Set shtNew = Worksheets.Add(Before:=shtFirst)
        shtNew.Name = "FirstSheet"

        ' Adds new sheet to last position in the workbook
        Set shtNew = Worksheets.Add(After:=shtLast)
        shtNew.Name = "LastSheet"

    End With

End Sub

Delete Worksheet

To delete a worksheet you simply call the Delete member.

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Sheet12")
sh.Delete

 
Excel will display a warning message when you delete a worksheet. If you want to hide this message you can use the code below

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

 
There are two issues to watch out for when it comes to deleting worksheets.

If you try to access the worksheet after deleting it you will get the “Subscript out of Range” error we saw in the Accessing the Worksheet section.

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Sheet2")
sh.Delete

' This line will give 'Subscript out of Range' as "Sheet2" does not exist
Set sh = ThisWorkbook.Worksheets("Sheet2")

 
The second issue is when you assign a worksheet variable. If you try to use this variable after the worksheet is deleted then you will get an Automation error like this

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

If you are using the Code Name of the worksheet rather than a variable, then this will cause Excel to crash rather than give the automation error.

 
The following example shows how an automation errors occurs

sh.Delete

' This line will give Automation error
Debug.Assert sh.Name

If you assign the Worksheet variable to a valid worksheet it will work fine

sh.Delete

' Assign sh to another worksheet
Set sh = Worksheets("sheet3")

' This line will work fine
Debug.Assert sh.Name

Loop Through the Worksheets

The Worksheets member of Workbooks is a collection of worksheets belonging to a workbook. You can go through each sheet in the worksheets collection using a For Each Loop or a For Loop.

 
The following example uses a For Each loop.

' https://excelmacromastery.com/
Public Sub LoopForEach()

    ' Writes "Hello World" into cell A1 for each worksheet
    Dim sht As Worksheet
    For Each sht In ThisWorkbook.Worksheets
         sht.Range("A1") = "Hello World"
    Next sht 

End Sub

 
The next example uses the standard For loop

' https://excelmacromastery.com/
Public Sub LoopFor()
    
    ' Writes "Hello World" into cell A1 for each worksheet
    Dim i As Long
    For i = 1 To ThisWorkbook.Worksheets.Count
         ThisWorkbook.Worksheets(i).Range("A1") = "Hello World"
    Next sht

End Sub

 
You have seen how to access all open workbooks and how to access all worksheets in ThisWorkbook. Lets take it one step further. Lets access all worksheets in all open workbooks.

Note: If you use code like this to write to worksheets then back everything up first as you could end up writing the incorrect data to all the sheets.

' https://excelmacromastery.com/
Public Sub AllSheetNames()

    ' Prints the workbook and sheet names for
    ' all sheets in open workbooks
    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

Using the Sheets Collection

The workbook has another collection similar to Worksheets called Sheets. This causes confusion at times among users. To explain this first you need to know about a sheet type that is a chart.

 
It is possible in Excel to have a sheet that is a chart. To do this

  1. Create a chart on any sheet.
  2. Right click on the chart and select Move.
  3. Select the first option which is “New Sheet” and click Ok.

 
Now you have a workbook with sheets of type worksheet and one of type chart.

  • The Worksheets collection refers to all worksheets in a workbook. It does not include sheets of type chart.
  • The Sheets collection refers to all sheets belonging to a workbook including sheets of type chart.

 
There are two code examples below. The first goes through all the Sheets in a workbook and prints the name of the sheet and type of sheet it is. The second example does the same with the Worksheets collection.

 
To try out these examples you should add a Chart sheet to your workbook first so you will see the difference.

' https://excelmacromastery.com/
Public Sub CollSheets()

    Dim sht As Variant
    ' Display the name and type of each sheet
    For Each sht In ThisWorkbook.Sheets
        Debug.Print sht.Name & " is type " & TypeName(sht)
    Next sht

End Sub

Public Sub CollWorkSheets()

    Dim sht As Variant
    ' Display the name and type of each sheet
    For Each sht In ThisWorkbook.Worksheets
        Debug.Print sht.Name & " is type " & TypeName(sht)
    Next sht

End Sub

 
If do not have chart sheets then using the Sheets collection is the same as using the Worksheets collection.

Conclusion

This concludes the post on the VBA Worksheet. I hope you found it useful.

The three most important elements of Excel VBA are Workbooks, Worksheets and Ranges and Cells. These elements will be used in almost everything you do.  Understanding them will make you life much easier and make learning VBA much simpler.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

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

Понравилась статья? Поделить с друзьями:
  • Excel vba worksheet hidden
  • Excel vba this workbook save
  • Excel vba workbooks методы
  • Excel vba workbooks worksheets
  • Excel vba this workbook open