Создание, копирование, перемещение и удаление рабочих листов Excel с помощью кода VBA. Методы Sheets.Add, Worksheet.Copy, Worksheet.Move и Worksheet.Delete.
Создание новых листов
Создание новых рабочих листов осуществляется с помощью метода Sheets.Add.
Синтаксис метода Sheets.Add
expression.Add [Before, After, Count, Type]
где expression — переменная, представляющая собой объект Sheet.
Компоненты метода Sheets.Add
- Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлен новый.
- After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлен новый.
- Count — необязательный параметр типа данных Variant, указывающий, сколько листов будет добавлено (по умолчанию — 1).
- Type — необязательный параметр типа данных Variant, указывающий тип листа: xlWorksheet** (рабочий лист) или xlChart (диаграмма), по умолчанию — xlWorksheet.
*Если Before и After не указаны, новый лист, по умолчанию, будет добавлен перед активным листом.
**Для создания рабочего листа (xlWorksheet) можно использовать метод Worksheets.Add, который для создания диаграмм уже не подойдет.
Примеры создания листов
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
‘Создание рабочего листа: Sheets.Add Worksheets.Add ThisWorkbook.Sheets.Add After:=ActiveSheet, Count:=2 Workbooks(«Книга1.xlsm»).Sheets.Add After:=Лист1 Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(1) Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(«Лист1») ‘Создание нового листа с заданным именем: Workbooks(«Книга1.xlsm»).Sheets.Add.Name = «Мой новый лист» ‘Создание диаграммы: Sheets.Add Type:=xlChart ‘Добавление нового листа перед ‘последним листом рабочей книги Sheets.Add Before:=Sheets(Sheets.Count) ‘Добавление нового листа в конец Sheets.Add After:=Sheets(Sheets.Count) |
- Лист1 в After:=Лист1 — это уникальное имя листа, указанное в проводнике редактора VBA без скобок.
- Лист1 в After:=Worksheets(«Лист1») — это имя на ярлыке листа, указанное в проводнике редактора VBA в скобках.
Создаваемый лист можно присвоить объектной переменной:
Dim myList As Object ‘В активной книге Set myList = Worksheets.Add ‘В книге «Книга1.xlsm» Set myList = Workbooks(«Книга1.xlsm»).Worksheets.Add ‘Работаем с переменной myList.Name = «Listok1» myList.Cells(1, 1) = myList.Name ‘Очищаем переменную Set myList = Nothing |
Если создаваемый лист присваивается объектной переменной, он будет помещен перед активным листом. Указать дополнительные параметры невозможно.
Копирование листов
Копирование рабочих листов осуществляется с помощью метода Worksheet.Copy.
Синтаксис метода Worksheet.Copy
expression.Copy [Before, After]
где expression — переменная, представляющая собой объект Worksheet.
Компоненты метода Worksheet.Copy
- Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлена копия.
- After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлена копия.
*Если Before и After не указаны, Excel создаст новую книгу и поместит копию листа в нее. Если скопированный лист содержит код в проекте VBA (в модуле листа), он тоже будет перенесен в новую книгу.
Примеры копирования листов
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
‘В пределах активной книги ‘(уникальные имена листов) Лист1.Copy After:=Лист2 ‘В пределах активной книги ‘(имена листов на ярлычках) Worksheets(«Лист1»).Copy Before:=Worksheets(«Лист2») ‘Вставить копию в конец Лист1.Copy After:=Sheets(Sheets.Count) ‘Из одной книги в другую Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Copy _ After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1») ‘Один лист активной книги в новую книгу Лист1.Copy ‘Несколько листов активной книги в новую книгу* Sheets(Array(«Лист1», «Лист2», «Лист3»)).Copy ‘Все листы книги с кодом в новую книгу ThisWorkbook.Worksheets.Copy |
* Если при копировании в новую книгу нескольких листов хотя бы один лист содержит умную таблицу — копирование невозможно. Один лист, содержащий умную таблицу, копируется в новую книгу без проблем.
Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.
Перемещение листов
Перемещение рабочих листов осуществляется с помощью метода Worksheet.Move.
Синтаксис метода Worksheet.Move
expression.Move [Before, After]
где expression — переменная, представляющая собой объект Worksheet.
Компоненты метода Worksheet.Move
- Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет размещен перемещаемый лист.
- After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет размещен перемещаемый лист.
*Если Before и After не указаны, Excel создаст новую книгу и переместит лист в нее.
Примеры перемещения листов
Простые примеры перемещения листов:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
‘В пределах активной книги ‘(уникальные имена листов) Лист1.Move After:=Лист2 ‘В пределах активной книги ‘(имена листов на ярлычках) Worksheets(«Лист1»).Move Before:=Worksheets(«Лист2») ‘Размещение после последнего листа: Лист1.Move After:=Sheets(Sheets.Count) ‘Из одной книги в другую Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Move _ After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1») ‘В новую книгу Лист1.Move |
Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.
Перемещение листа «Лист4» в позицию перед листом, указанным как по порядковому номеру, так и по имени ярлыка:
Sub Peremeshcheniye() Dim x x = InputBox(«Введите имя или номер листа», «Перемещение листа «Лист4»») If IsNumeric(x) Then x = CLng(x) Sheets(«Лист4»).Move Before:=Sheets(x) End Sub |
Удаление листов
Удаление рабочих листов осуществляется с помощью метода Worksheet.Delete
Синтаксис метода Worksheet.Delete
expression.Delete
где expression — переменная, представляющая собой объект Worksheet.
Примеры удаления листов
‘По уникальному имени Лист1.Delete ‘По имени на ярлычке Worksheets(«Лист1»).Delete ‘По индексу листа Worksheets(1).Delete ‘В другой книге Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Delete |
Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.
Как обратиться к рабочему листу, переименовать, скрыть или отобразить его с помощью кода VBA Excel, смотрите в этой статье.
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Sheets.Add method (Excel) |
vbaxl10.chm152073 |
vbaxl10.chm152073 |
excel |
Excel.Sheets.Add |
db5de750-fd09-2b18-c52b-98d88eeb0ffc |
09/03/2019 |
medium |
Sheets.Add method (Excel)
Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet.
Syntax
expression.Add (Before, After, Count, Type)
expression A variable that represents a Sheets object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Before | Optional | Variant | An object that specifies the sheet before which the new sheet is added. |
After | Optional | Variant | An object that specifies the sheet after which the new sheet is added. |
Count | Optional | Variant | The number of sheets to be added. The default value is the number of selected sheets. |
Type | Optional | Variant | Specifies the sheet type. Can be one of the following XlSheetType constants: xlWorksheet, xlChart, xlExcel4MacroSheet, or xlExcel4IntlMacroSheet. If you are inserting a sheet based on an existing template, specify the path to the template. The default value is xlWorksheet. |
Return value
An Object value that represents the new worksheet, chart, or macro sheet.
Remarks
If Before and After are both omitted, the new sheet is inserted before the active sheet.
Example
This example inserts a new worksheet before the last worksheet in the active workbook.
ActiveWorkbook.Sheets.Add Before:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count)
This example inserts a new worksheet after the last worksheet in the active workbook, and captures the returned object reference in a local variable.
Dim sheet As Worksheet Set sheet = ActiveWorkbook.Sheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
[!NOTE]
In 32-bit Excel 2010, this method cannot create more than 255 sheets at one time.
[!includeSupport and feedback]
Once you start learning VBA one of the coolest things you can do is to write a VBA code to insert new a worksheet in a workbook.
Well, there is already a shortcut key to insert a new worksheet or you can also use the normal option but the benefit of using a VBA code is you can add multiple worksheets with a single click and you can also define that where you want to add it.
For this, you need to use the Sheets.Add method, and in this post, we will be learning how to use it to add one or more worksheets in a workbook.
Sheets.Add Method
Sheets.Add ([Before], [After], [Count], [Type])
- Before: To add a new sheet before a sheet.
- After: To add the new sheet before a sheet.
- Count: Number of sheets to add.
- Type: Type of the sheet you want to add (LINK)
Open the visual basic editor and follow these steps.
- First, you need to enter Sheets.Add method.
- Then you need to define the place to add the new sheet (Before or After).
- Next thing is to enter the count of worksheets.
- In the end, the type of sheet.
Different Ways to Add New Sheets in a Workbook using a VBA Code
Below you have different ways to add a new sheet to a workbook:
1. Add a Single Sheet
To add a single sheet, you can use the below code, where you didn’t specify any argument.
Sub SheetAddExample1()
ActiveWorkbook.Sheets.Add
End Sub
This code tells Excel to add a sheet in the active workbook, but as you don’t have any argument it will use the default values and add one worksheet(xlWorksheet) before the active sheet.
Here’s one more way to write this, check out the below code.
Sub SheetAddExample2()
Sheets.Add
End Sub
As you are already in the active workbook you can use the below code as well. It does the same thing.
2. Add Multiple Sheets
To add multiple sheets in one go, you just need to define the COUNT argument with the number of sheets you want to add.
Sub AddSheets3()
Sheets.Add Count:=5
End Sub
Now the count of the sheets that you have defined is 5, so when you run this code it instantly adds the five new sheets in the workbook.
3. Add a Sheet with a Name
If you want to rename the sheet after adding it, you can use the following code:
Sub AddNewSheetswithNameExample1()
Sheets.Add.Name = "myNewSHeet"
End Sub
In the above code, we have used the name object (LINK) which helps you to specify the name of a sheet.
4. Add a Sheet with a Name from a Cell
You can also take the value to use as the sheet’s name from a cell.
Sub AddNewSheetswithNameExample2()
Sheets.Add.Name = Range("A1")
End Sub
In the above code, cell A1 is used to get the name for the new sheet.
5. Add a Sheet After/Before a Specific Sheet
As these arguments are already there in the Sheets.Add where you can specify the sheet to add a new sheet before or after it.
Sub AddSheetsExample5()
Sheets.Add Before:=Worksheets("mySheet")
Sheets.Add After:=Worksheets("mySheet")
End Sub
Now in the above code, you have two lines of code that you have used before and after an argument in the Sheet.Add method. So, when you run this code it adds two sheets one is before and one is after the “mySheet”.
6. Add a New Sheet at Beginning
By using the before argument using you can also add a sheet at the beginning of the sheets that you have in the workbook.
So basically, what we are going to do is we’re going to specify the sheet number instead of the sheet name.
Sub AddSheetsExample6()
Sheets.Add Before:=Sheets(1)
End Sub
In the above code, you have used sheet number (1) that tells VBA to add the sheet before the sheet which is in the first position in all the worksheets. In this way, it will always add the new sheet at the beginning.
7. Add a New Sheet at the End (After the Last Sheet)
To add a new sheet in the end you need to write the code in a different way. So, for this, you need to know how many sheets there in the workbook are so that you can add a new sheet at the end.
Sub AddSheetsExample8()
Sheets.Add After:=Sheets(Sheets.Count)
End Sub
In the above code, Sheet.Count returns the count of the sheets that you have in the workbook, and as you have defined the after argument it adds the new sheet after the last sheet in the workbook.
8. Add Multiple Sheets and use Names from a Range
The following code counts rows from the range A1:A7. After that, it loops to add sheets according to the count from the range and uses values from the range to name the sheet while adding it.
Sub AddSheetsExample9()
Dim sheets_count As Integer
Dim sheet_name As String
Dim i As Integer
sheet_count = Range("A1:A7").Rows.Count
For i = 1 To sheet_count
sheet_name = Sheets("mySheet").Range("A1:A7").Cells(i, 1).Value
Worksheets.Add().Name = sheet_name
Next i
End Sub
But with the above code, there could be a chance that the sheet name you want to add already exists or you have a blank cell in the name range.
In that case, you need to write a code that can verify if the sheet with the same name already exists or not and whether the cell from where you want to take the sheet name is blank or not.
If both conditions are fulfilled only then it should add a new sheet. Let me put it in steps two steps:
First, you need to write an Excel User Defined Function to check if a sheet with the same name already exists or not.
Function SheetCheck(sheet_name As String) As Boolean
Dim ws As Worksheet
SheetCheck = False
For Each ws In ThisWorkbook.Worksheets
If ws.Name = sheet_name Then
SheetCheck = True
End If
Next
End Function
Second, you need to write a code using this function and that code should also check if the name cell is blank or not.
Sub AddMultipleSheet2()
Dim sheets_count As Integer
Dim sheet_name As String
Dim i As Integer
sheet_count = Range("A1:A7").Rows.Count
For i = 1 To sheet_count
sheet_name = Sheets("mySheet").Range("A1:A10").Cells(i, 1).Value
If SheetCheck(sheet_name) = False And sheet_name <> "" Then
Worksheets.Add().Name = sheet_name
End If
Next i
End Sub
Now in the above code, you have used the VBA IF Statement and in this statement, you have the sheet check function which checks for the sheet name and then you have a condition to check if the name cell has a blank value.
Sample File
More Tutorials on Worksheets
- VBA Worksheet – Excel VBA Examples – VBA Tutorial
На чтение 16 мин. Просмотров 14.5k.
Malcolm Gladwell
Мечтатель начинает с чистого листа бумаги и переосмысливает мир
Эта статья содержит полное руководство по использованию Excel
VBA Worksheet в Excel VBA. Если вы хотите узнать, как что-то сделать быстро, ознакомьтесь с кратким руководством к рабочему листу VBA ниже.
Если вы новичок в VBA, то эта статья — отличное место для начала. Мне нравится разбивать вещи на простые термины и объяснять их на простом языке.
Вы можете прочитать статью от начала до конца, так как она написана в логическом порядке. Или, если предпочитаете, вы можете использовать оглавление ниже и перейти непосредственно к теме по вашему выбору.
Содержание
- Краткое руководство к рабочему листу VBA
- Вступление
- Доступ к рабочему листу
- Использование индекса для доступа к рабочему листу
- Использование кодового имени рабочего листа
- Активный лист
- Объявление объекта листа
- Доступ к рабочему листу в двух словах
- Добавить рабочий лист
- Удалить рабочий лист
- Цикл по рабочим листам
- Использование коллекции листов
- Заключение
Краткое руководство к рабочему листу 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
Это означает, что вы пытались получить доступ к рабочему листу, который не существует. Это может произойти по следующим причинам:
- Имя Worksheet , присвоенное рабочим листам, написано неправильно.
- Название листа изменилось.
- Рабочий лист был удален.
- Индекс был большим, например Вы использовали рабочие листы (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).
Использование кодового имени рабочего листа
Лучший способ получить доступ к рабочему листу —
использовать кодовое имя. Каждый лист имеет имя листа и кодовое имя. Имя листа
— это имя, которое отображается на вкладке листа в Excel.
Изменение имени листа не приводит к изменению кодового имени, что означает, что ссылка на лист по кодовому имени — отличная идея.
Если вы посмотрите в окне свойств VBE, вы увидите оба имени.
На рисунке вы можете видеть, что кодовое имя — это имя вне скобок, а имя листа
— в скобках.
Вы можете изменить как имя листа, так и кодовое имя в окне
свойств листа (см. Изображение ниже).
Если ваш код ссылается на кодовое имя, то пользователь может
изменить имя листа, и это не повлияет на ваш код. В приведенном ниже примере мы
ссылаемся на рабочий лист напрямую, используя кодовое имя.
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
Резюме кодового имени
Ниже приведено краткое описание использования кодового имени:
- Кодовое имя рабочего листа может быть
использовано непосредственно в коде, например. Sheet1.Range - Кодовое имя будет по-прежнему работать, если имя
рабочего листа будет изменено. - Кодовое имя может использоваться только для
листов в той же книге, что и код. - Везде, где вы видите ThisWorkbook.Worksheets
(«имя листа»), вы можете заменить его кодовым именем рабочего листа. - Вы можете использовать функцию 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
Доступ к рабочему листу в двух словах
Из-за множества различных способов доступа к рабочему листу вы можете быть сбитыми с толку. Так что в этом разделе я собираюсь разбить его на простые термины.
- Если вы хотите использовать тот лист, который активен в данный момент, используйте 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 есть возможность создать лист, который является диаграммой. Для этого нужно:
- Создать диаграмму на любом листе.
- Щелкнуть правой кнопкой мыши на графике и выбрать «Переместить».
- Выбрать первый вариант «Новый лист» и нажмите «ОК».
Теперь у вас есть рабочая книга, в которой есть типовые листы и лист-диаграмма.
- Коллекция «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 увлекательнее.
This tutorial explains how to add new work sheets using Worksheets.Add Method in Excel VBA, or add new worksheets at the back or before specific worksheet
You may also want to read:
Excel VBA Worksheets.Copy Method to copy worksheet
Excel VBA Worksheets.Add Method is to add new worksheet in a workbook.
Syntax of Excel VBA Worksheets.Add Method
Worksheets.Add([Before],[After],[Count],[Type])
Before | Optional. Add new worksheet before specific worksheet | ||||
After | Optional, add new worksheet after specific worksheet | ||||
Count | Optional. Number of worksheets to add, default is 1 | ||||
Type | Optional. Worksheet type, default is xlWorksheet
|
If Before and After are not specified, worksheet is added before Active worksheet (the worksheet you selected before running the Add Method).
Example 1 – Add new worksheet after specific worksheet
The below code add new worksheet after Sheet8
Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets("Sheet8"))
Example 2 – Add new worksheet and move to the end of worksheet
The below code makes use of Worksheets(Worksheets.Count) to find the last worksheet. Worksheets(Index) returns the Nth worksheet from left to right.
Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count))
Example 3 – Add new worksheet and move to the first worksheet
Set newWS = ThisWorkbook.Worksheets.Add(Before:=Worksheets(1))
Example 4 – add new worksheet if not exist
The below code makes use of a custom Function called wsExist to check if a worksheet already exists, returns TRUE if exists, FALSE if not exist.
Sub createWS() Dim ws, newWS As Worksheet For Each ws In ActiveWorkbook.Worksheets If wsExists("worksheet1") Then counter = 1 End If Next ws If counter = 0 Then Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets(Worksheets.Count)) newWS.Name = "worksheet1" End If End Sub Function wsExists(wksName As String) As Boolean On Error Resume Next wsExists = CBool(Len(Worksheets(wksName).Name) > 0) On Error GoTo 0 End Function
Outbound References
https://msdn.microsoft.com/en-us/library/office/microsoft.office.interop.excel.worksheets.add.aspx?f=255&MSPPError=-2147217396
In this guide, we’re going to show you how to create and name a worksheet with VBA in Excel.
Download Workbook
Syntax
You can create and name a worksheet using the Sheets.Add and Worksheets.Add methods. Both methods work similarly and have 4 optional arguments and return a sheet object which can take a Name property.
Sheets.Add ([Before], [After], [Count], [Type])
Worksheets.Add ([Before], [After], [Count], [Type])
Name | Description |
Before | Optional. The sheet before which the new sheet is to be added. If omitted, Excel creates the new sheet(s) before the selected sheet(s). |
After | Optional. The sheet after which the new sheet is added. If omitted, Excel creates the new sheet(s) before the selected sheet(s). |
Count | The number of sheets to be added. The default is the number of selected sheets. |
Type | Specifies the sheet type. The default is xlWorksheet which represents a standard worksheet. |
Adding a single sheet
All arguments are optional. The method without arguments creates worksheet(s) equal to the number of selected worksheets before the first selected worksheet.
Sheets.Add
For example, if two sheets are selected, the method will add two worksheets. To ignore the selected sheets and set the sheet number to one (1), use 1 for the Count argument.
Sheets.Add Count:=1
Adding multiple sheets
You can set the Count argument to an integer greater than 1 to add multiple sheets at once. For example, the following code adds three (3) worksheets.
Sheets.Add Count:=3
Adding a sheet with a name
Sheets.Add method returns a sheet object and sets its name by updating the Name property. A property is an attribute of object that determines one of the object’s characteristics. The property of an object is addressed by entering the property name after the corresponding object and a dot(.). Just like calling the Add method for the Sheets object.
If all you need is to create worksheets and name them regardless of their position, use one of the following code lines.
Sheets.Add.Name = “My Sheet” Sheets.Add(Count:=1).Name = “My Sheet” ‘Use this line to ensure creating a single sheet
Adding a sheet before or after a specific sheet
If the new sheet’s position is important, use either the Before or After argument. Each argument accepts a sheet object. The new sheet will be created before or after the sheet you supplied based on the argument you are using.
You can call a sheet object by giving the sheet’s name or index to Sheets or Worksheets objects. It can be a variable which you have defined. Here are some examples:
Sheets.Add Before:=Worksheets("My Sheet") ‘Add sheet(s) before “My Sheet” Sheets.Add After:=Worksheets(3) ‘Add sheet(s) after the third sheet
Dim ws As Worksheet ‘Define a new worksheet object Set ws = Sheets.Add ‘Create and assign new sheet to the worksheet object Sheets.Add After:=ws ‘Add a new sheet after the recently added sheet (ws)
Creating and naming multiple worksheets
To name multiple worksheets, you have to use an array of names and a loop. Let’s say you have names in a range like A1:A5 in the worksheet named “Sheet1”. A loop should check each cell inside the range and create a worksheet from the corresponding name. Check out the following code:
Sub CreateAndNameMultipleSheets() Dim rng As Range 'Range object which defines a cell For Each rng In Sheets("Sheet1").Range("A1:A5") Sheets.Add.Name = rng.Value Next End Sub
This is our last tip for how to create and name a worksheet with VBA in Excel article. If you are new to loops in VBA, check out All You Need to Know on How to Create a VBA loop in Excel to understand and find more ways of looping.
In this Article
- What is a Collection in VBA?
- Collections Versus Arrays
- Scope of a Collection Object
- Create a Collection, Add Items, and Access Items
- Loop Through Collection
- Add Item to Collection
- Remove an Item from Collection
- Count the Number of Items in a Collection
- Test Collection for a Specific Value
- Pass a Collection to a Sub / Function
- Return a Collection from a Function
- Convert a Collection to an Array
- Convert an Array into a Collection
This tutorial will demonstrate how to use collections in VBA.
What is a Collection in VBA?
A collection is an object that holds a number of similar items that can easily be accessed and manipulated, even if there are a large number of items within the collection.
You can create your own collections, but VBA also comes with built in collections such as the Sheets Collection, which stores every sheet in the workbook. By using a For Each loop, you can iterate through each worksheet in the Sheets Collection.
Sub TestWorksheets()
Dim Sh As Worksheet
For Each Sh In Sheets
MsgBox Sh.Name
MsgBox Sh.Visible
Next Sh
End Sub
You can also address a specific worksheet in the collection using the index value (it’s position in the collection), or the actual name of the worksheet:
MsgBox Sheets(1).Name
MsgBox Sheets("Sheet1").Name
As worksheets are added or deleted so the Sheets collection grows or shrinks in size.
Note that with VBA collections the index number begins with 1 not with 0.
Collections Versus Arrays
Arrays and Collections can both store data, however they have several notable differences:
- Arrays are multidimensional whereas collections are only single dimension. You can dimension an array with several dimensions e.g.
Dim MyArray(10, 2) As String
This creates an array of 10 rows with 2 columns, almost like a worksheet. A collection is effectively a single column.
- When you populate your array, you need a separate line of code to put a value into each element of the array. If you had a two-dimensional array you would actually need 2 lines of code – one line to address the first column and one line to address the second column. With the Collection object, you simply use the Add method so that the new item is just added into the collection and the index value is automatically adjusted to suit.
- If you need to delete an item of data then it is more complicated in the array. You can set the values of an element to a blank value, but the element itself still exists within the array. If you are using a For Next loop to iterate through the array, the loop will return a blank value, which will need coding to make sure that the blank value is ignored. In a collection you use the Add or Remove methods, and all the indexing and re-sizing is automatically taken care of. The item that has been removed disappears completely. Arrays are useful for a fixed size of data, but collections are better for where the quantity of data is liable to change.
- Collections are Read Only whereas array values can be changed using VBA. With a collection, you would have to remove the value to be changed first and then add in the new changed value.
- In an array, you can only use a single data type for the elements which is set when you dimension the array. However, in the array you can use custom data types that you have designed yourself. You could have a very complicated array structure using a custom data type which in turn has several custom data types below it. In a collection, you can add use data types of data for each item. You could have a numeric value, a date, or a string – the collection object will take any data type. If you tried to put a string value in an array that was dimensioned as numeric, it would produce an error message.
- Collections are generally easier to use than arrays. In coding terms, when you create a collection object, it only has two methods (Add and Remove) and two properties (Count and Item), so the object is by no means complicated to program.
- Collections can use keys to locate data. Arrays do not have this function and require looping code to iterate through the array to find specific values.
- The size of an array needs to be defined when it is first created. You need to have an idea of how much data it is going to store. If you need to increase the size of the array you can use ‘ReDim’ to re-size it, but you need to use the keyword ‘Preserve’ if you do not want to lose the data already held in the array. A collection size does not need to be defined. It just grows and shrinks automatically as items are added or removed.
Scope of a Collection Object
In terms of scope, the collection object is only available whilst the workbook is open. It does not get saved when the workbook is saved. If the workbook is re-opened then the collection needs to be re-created using VBA code.
If you want your collection to be available to all the code in your code module, then you need to declare the collection object in the Declare section at the top of the module window.
This will ensure that all your code within that module can access the collection. If you want any module within your workbook to access the collection, then define it as a global object.
Global MyCollection As New Collection
Create a Collection, Add Items, and Access Items
A simple collection object can be created in VBA using the following code:
Sub CreateCollection()
'Create Collection
Dim MyCollection As New Collection
'Add Items to Collection
MyCollection.Add "Item1"
MyCollection.Add "Item2"
MyCollection.Add "Item3"
End Sub
The code creates a new object called ‘MyCollection’ and then the following lines of code use the Add method to add in 3 new values.
Loop Through Collection
You can then use code to iterate through each item in your collection:
For Each Item In MyCollection
MsgBox Item
Next Item
Or this code will get the size of the collection with .Count and loop through each index number:
For n = 1 To MyCollection.Count
MsgBox MyCollection(n)
Next n
The first For Each Loop is faster than the second For Next loop but it only works in one direction (low index to high). The For Next Loop has the advantage that you can use a different direction (high index to low) and you can also use the Step method to change the increment. This is useful when you want to delete several items since you will need to run the deletion from the end of the collection to the start as the index will change as the deletions take place.
Add Item to Collection
The Add method in a collection has 3 optional parameters – Key, Before, and After.
You can use the ‘Before’ and ‘After’ parameters to define the position of your new item relative to the others already in the collection.
This is done by specifying the index number that you want your new item to be relative to.
Sub CreateCollection()
Dim MyCollection As New Collection
MyCollection.Add "Item1"
MyCollection.Add "Item2", , 1
MyCollection.Add "Item3"
End Sub
In this example ‘Item2’ has been specified to be added before the first indexed item in the collection (which is ‘Item1’). When you iterate through this collection ‘Item2’ will appear first of all, followed by ‘Item1’ and ‘Item3’.
When you specify a ‘Before’ or ‘After’ parameter, the index value is automatically adjusted within the collection so that ‘Item2’ becomes index value of 1 and ‘Item1’ gets moved to an index value of 2.
You can also use the ‘Key’ parameter to add a reference value that you can use to identify the collection item. Note that a key value must be a string and must be unique within the collection.
Sub CreateCollection()
Dim MyCollection As New Collection
MyCollection.Add "Item1"
MyCollection.Add "Item2", "MyKey"
MyCollection.Add "Item3"
MsgBox MyCollection("MyKey")
End Sub
‘Item2’ has been given a ‘Key’ value of ‘MyKey’ so that you can refer to that item using the value of ‘MyKey’ instead of the index number (2).
Note that the ‘Key’ value has to be a string value. It cannot be any other data type. Note that the collection is Read Only, and you cannot update the key value once it has been set. Also, you cannot check if a key value exists for a specific item in the collection or view the key value which is a bit of a drawback.
The ‘Key’ parameter has the added advantage of making your code more readable, especially if it is being handed over to a colleague to support, and you do not have to iterate through the entire collection to find that value. Imagine if you had a collection of 10,000 items how difficult it would be to reference one specific item!
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Remove an Item from Collection
You can use the ‘Remove’ method to delete items from your collection.
MyCollection.Remove (2)
Unfortunately, it is not easy if the collection has a large number of items to work out the index of the item that you want to delete. This is where the ‘Key’ parameter comes in handy when the collection is being created.
MyCollection.Remove (“MyKey”)
When an item is removed from a collection the index values are automatically reset all the way through the collection. This is where the ‘Key’ parameter is so useful when you are deleting several items at once. For example, you could delete item index 105, and instantly item index 106 becomes index 105, and everything above this item has its index value moved down. If you use the Key parameter, there is no need to worry about which index value needs to be removed.
To delete all the collection items and create a new collection, you use the Dim statement again which creates an empty collection.
Dim MyCollection As New Collection
To remove the actual collection object completely, you can set the object to nothing.
Set MyCollection = Nothing
This is useful if the collection is no longer required by your code. Setting the collection object to nothing removes all reference to it and releases the memory that it was using. This can have important implications on speed of execution of your code, if a large object is sitting in memory that is no longer required.
Count the Number of Items in a Collection
You can easily find out the number of items in your collection by using the ‘Count’ property.
MsgBox MyCollection.Count
You would use this property if you were using a For Next Loop to iterate through the collection as it will provide you with the upper limit for the index number.
Test Collection for a Specific Value
You can iterate through a collection to search for a specific value for an item using a For Each Loop.
Sub SearchCollection()
Dim MyCollection as New Collection
MyCollection.Add "Item1"
MyCollection.Add "Item2"
MyCollection.Add "Item3"
For Each Item In MyCollection
If Item = "Item2" Then
MsgBox Item & " Found"
End If
Next
End Sub
The code creates a small collection, and then iterates through it looking for an item called ‘item2”. If found it displays a message box that it has found the specific item.
One of the drawbacks with this methodology is that you cannot access the index value or the key value.
If you use a For Next Loop instead, you can use the For Next counter to get the index value, although you still cannot get the ‘Key’ value.
Sub SearchCollection()
Dim MyCollection As New Collection
MyCollection.Add "Item1"
MyCollection.Add "Item2"
MyCollection.Add "Item3"
For n = 1 To MyCollection.Count
If MyCollection.Item(n) = "Item2" Then
MsgBox MyCollection.Item(n) & " found at index position " & n
End If
Next n
End Sub
The For Next counter (n) will provide the index position.
Sort Collection
There is no built-in functionality to sort a collection, but using some ‘out of the box’ thinking, code can be written to do a sort, utilizing Excel’s worksheet sorting function. This code uses a blank worksheet called ‘SortSheet’ to do the actual sorting.
Sub SortCollection()
Dim MyCollection As New Collection
Dim Counter As Long
'Build collection with random order items
MyCollection.Add "Item5"
MyCollection.Add "Item2"
MyCollection.Add "Item4"
MyCollection.Add "Item1"
MyCollection.Add "Item3"
'Capture number of items in collection for future use
Counter = MyCollection.Count
'Iterate through the collection copying each item to a consecutive cell on ‘SortSheet’ (column A)
For n = 1 To MyCollection.Count
Sheets("SortSheet").Cells(n, 1) = MyCollection(n)
Next n
'Activate the sortsheet and use the Excel sort routine to sort the data into ascending order
Sheets("SortSheet").Activate
Range("A1:A" & MyCollection.Count).Select
ActiveWorkbook.Worksheets("SortSheet").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("SortSheet"). Sort.SortFields.Add2 Key:=Range( _
"A1:A5"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("SortSheet").Sort
.SetRange Range("A1:A5")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Delete all the items in the collection – note that this For Next Loop runs in reverse order
For n = MyCollection.Count To 1 Step -1
MyCollection.Remove (n)
Next n
'Copy the cell values back into the empty collection object using the stored value (Counter) for the ‘loop
For n = 1 To Counter
MyCollection.Add Sheets("SortSheet").Cells(n, 1).Value
Next n
'Iterate through the collection to prove out the order that the items are now in
For Each Item In MyCollection
MsgBox Item
Next Item
'Clear the worksheet (sortsheet) – if necessary, delete it as well
Sheets("SortSheet").Range(Cells(1, 1), Cells(Counter, 1)).Clear
End Sub
This code first creates a collection with the items added in a random order. It then copies them into the first column on a worksheet (SortSheet).
The code then uses the Excel sort tool to sort the data in the column into ascending order. The code could also be modified to sort into descending order.
The collection is then emptied of data using a For Next Loop. Note that the step option is used so that it clears from the end of the collection to the start. This is because as it clears, the index values are reset, if it cleared from the start, it would not clear correctly (index 2 would become index 1)
Finally, using another For Next Loop, the item values are transferred back into the empty collection
A further For Each Loop proves out that the collection is now in good ascending order.
Unfortunately, this does not deal with any Key values that may have been entered originally, since the Key values cannot be read
VBA Programming | Code Generator does work for you!
Pass a Collection to a Sub / Function
A collection can be passed to a Sub or a Function in the same way as any other parameter
Function MyFunction(ByRef MyCollection as Collection)
It is important to pass the collection using ‘ByRef’. This means that the original collection is used. If the collection is passed using ‘ByVal’ then this creates a copy of the collection which can have unfortunate repercussions.
If a copy is created using ‘ByVal’ then anything that changes the collection within the function only happens on the copy and not on the original. For example, if within the function, a new item is added to the collection, this will not appear in the original collection, which will create a bug in your code.
Return a Collection from a Function
You can return a collection from a function in the same way as returning any object. You must use the Set keyword.
Sub ReturnFromFunction()
Dim MyCollection As Collection
Set MyCollection = PopulateCollection
MsgBox MyCollection.Count
End Sub
This code creates a sub routine which creates an object called ‘MyCollection’ and then uses the ‘Set’ keyword to effectively call the function to populate that collection. Once this is done then it displays a message box to show the count of 2 items.
Function PopulateCollection() As Collection
Dim MyCollection As New Collection
MyCollection.Add "Item1"
MyCollection.Add "Item2"
Set PopulateCollection = MyCollection
End Function
The function PopulateCollection creates a new collection object and populates it with 2 items. It then passes this object back to the collection object created in the original sub routine.
Convert a Collection to an Array
You may wish to convert your collection into an array. You may want to store the data where it can be changed and manipulated. This code creates a small collection and then transfers it into an array
Notice that the collection index starts at 1 whereas the array index starts at 0. Whereas the collection has 3 items, the array only needs to be dimensioned to 2 because there is an element 0
Sub ConvertCollectionToArray()
Dim MyCollection As New Collection
Dim MyArray(2) As String
MyCollection.Add "Item1"
MyCollection.Add "Item2"
MyCollection.Add "Item3"
For n = 1 To MyCollection.Count
MyArray(n - 1) = MyCollection(n)
Next n
For n = 0 To 2
MsgBox MyArray(n)
Next n
End Sub
Convert an Array into a Collection
You may want to convert an array into a collection. For example, you may wish to access the data in a faster and more elegant manner that using code to get an array element.
Bear in mind that this will only work for a single dimension of the array because the collection has only one dimension.
Sub ConvertArrayIntoCollection()
Dim MyCollection As New Collection
Dim MyArray(2) As String
MyArray(0) = "item1"
MyArray(1) = "Item2"
MyArray(2) = "Item3"
For n = 0 To 2
MyCollection.Add MyArray(n)
Next n
For Each Item In MyCollection
MsgBox Item
Next Item
End Sub
If you did wish to use a multi-dimensional array, you could concatenate the array values together for each row within the array using a delimiter character between the array dimensions, so that when reading the collection value, you could programmatically use the delimiter character to separate the values out.
You could also move the data into the collection on the basis that the first-dimension value is added (index 1), and then the next dimension value is added (index 2) and so on.
If the array had, say, 4 dimensions, every fourth value in the collection would be a new set of values.
You could also add array values to use as keys (providing that they are unique) which would add an easy way of locating specific data.