Collection contains vba excel

Not my code, but I think it’s pretty nicely written. It allows to check by the key as well as by the Object element itself and handles both the On Error method and iterating through all Collection elements.

How to Check If a Collection Contains an Object

I’ll not copy the full explanation since it is available on the linked page. Solution itself copied in case the page eventually becomes unavailable in the future.

The doubt I have about the code is the overusage of GoTo in the first If block but that’s easy to fix for anyone so I’m leaving the original code as it is.

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT       : Kollection, the collection we would like to examine
'            : (Optional) Key, the Key we want to find in the collection
'            : (Optional) Item, the Item we want to find in the collection
'OUTPUT      : True if Key or Item is found, False if not
'SPECIAL CASE: If both Key and Item are missing, return False
Option Explicit
Public Function CollectionContains(Kollection As Collection, Optional Key As Variant, Optional Item As Variant) As Boolean
    Dim strKey As String
    Dim var As Variant

    'First, investigate assuming a Key was provided
    If Not IsMissing(Key) Then

        strKey = CStr(Key)

        'Handling errors is the strategy here
        On Error Resume Next
            CollectionContains = True
            var = Kollection(strKey) '<~ this is where our (potential) error will occur
            If Err.Number = 91 Then GoTo CheckForObject
            If Err.Number = 5 Then GoTo NotFound
        On Error GoTo 0
        Exit Function

CheckForObject:
        If IsObject(Kollection(strKey)) Then
            CollectionContains = True
            On Error GoTo 0
            Exit Function
        End If

NotFound:
        CollectionContains = False
        On Error GoTo 0
        Exit Function

    'If the Item was provided but the Key was not, then...
    ElseIf Not IsMissing(Item) Then

        CollectionContains = False '<~ assume that we will not find the item

        'We have to loop through the collection and check each item against the passed-in Item
        For Each var In Kollection
            If var = Item Then
                CollectionContains = True
                Exit Function
            End If
        Next var

    'Otherwise, no Key OR Item was provided, so we default to False
    Else
        CollectionContains = False
    End If

End Function

bulletproof_collection_check

Anyone who tells you they didn’t love this song is lying

How do you determine whether an object is a member of a Collection?

Folks with experience in other programming languages would probably assume that this functionality is built into VBA… And unfortunately, those folks would be wrong.

If you need a BULLETPROOF way to see if your Collection contains something (like a String, a Range, a Worksheet, etc.) look no further! The following Contains function:

  1. Attempts to find the object using a Key
  2. If no Key is provided, it loops through the Collection, checking each Item
  3. If no Key or Item is provided, it defaults to False

Here’s a link to the code above so you can review it side-by-side with the walk through below. Right-click, “Open in new window”.

Let’s dive in using our 4-step VBA process:

Step 1 – Setup
Step 2 – Exploration
Step 3 – Execution
Step 4 – Cleanup

The Step 1 – Setup in this function is minimal, and takes place entirely on lines 9 and 10 with the declaration of our variables: strKey and var. More on them later!

Step 2 – Exploration comes up in a hurry. Much like the set up, our Exploration phase is really short — in fact, it is essentially a single If / ElseIf / Else statement!

This statement starts on line 13, where we check to see if a Key was passed-in to the function. The ElseIf statement starts on line 39, where we check to see if an Item was passed-in to the function. Finally, on line 50, we default the Contains function to False if no Key or Item was passed-in. Easy cheesy!

easy_cheesy_emma

So far so good!

Step 3 – Execution is where things start to get interesting. As we said earlier, there are three branches our code can take:

  1. If the user passed-in a Key, we’ll use that to check the Collection
  2. If the user passed-in an Item, we’ll loop through the Collection, checking each contained item to see if it matches the passed-in Item
  3. If neither a Key or an Item is passed in, we return False by default

Let’s start with the easiest one first and work our way up!

3. If neither a Key or an Item is passed-in

This one’s a cinch. If the user calls Contains without passing in a Key or Item, we return False — lines 52 and 53 take care of that. Done!

2. If the user passed-in an Item

If the Collection in question does not make use of the (admittedly optional) Key parameter, then we will need to loop through the Collection and check each of its items against the passed in Item.

We tackle this on lines 41-49.

We start on line 41 by assuming that the passed-in Item will not be found, meaning Contains will return False. Don’t worry — we’ll set Contains to True if we do find the passed-in Item!

Collections support the For Each…Next loop construct with a Variant-type iterator, which we kick off on line 44. (That’s the var variable in this case.)

On line 45, we are checking each item (var) in the Collection to see if it matches the passed-in Item. As soon as a match is found, we set the Contains function to return True (on line 46) and exit (on line 47)!

1. If the user passed-in a Key

Jackpot — this one is absolutely the most fun of all, and it executes between lines 15 and 36.

The first thing we do is convert Key, which is technically a Variant, into a String on line 15. (Collections only allow for String-type keys, but we declare the optional input Key as Variant to allow the user to skip it if need be.)

Take a deep breath y’all — we’re about to enter Error Handling country…

On line 18, we use On Error Resume Next to ensure that VBA does not stop executing the code if an Error occurs. Why though?

y_tho

Why are we using On Error Resume Next?

Fortunately for us, the assignment on line 20 will (potentially) generate very predictable errors.

We start off this section by assuming the Key will be found, which is why we set Contains to True on line 19.

On line 20, as mentioned a moment ago, we attempt an assignment that might generate error.

On line 21, we check to see if Err.Number is 91 (which means an error occurred and the error number is 91). If so, the assignment itself failed! VBA throws this error when you attempt to assign an object without using the Set keyword — for example, if you wrote wks = ThisWorkbook.Sheets(1) instead of Set wks = ThisWorkbook.Sheets(1).

If the assignment failed, we jump to line 26 (CheckForObject), where we use the IsObject function on line 27 to properly check if an object (like a Worksheet or Workbook, for example) is stored in the Collection. If so, we can set Contains to True and exit!

What if we did not get error 91 though, and instead got error 5? (The error 5 case is what we are checking on line 22.)

VBA will throw a 5 error when the specified Key is not found in the Collection. In that case, we jump to line 33, where we set Contains to False and exit. Nice!

What if neither error 5 nor error 91 occurred? Well, in that case, we reset the error handling with On Error GoTo 0 on line 23 and exit the function with Contains still set to True, the way it was on line 19.

Phew! For such a small task, there were many edge cases to consider — fortunately, covered them all here and can use this function with confidence!

If you’d like to do some of your own checking on the Contains function, you can use my comprehensive test file to be 100% sure about how Contains works:

https://gist.github.com/danwagnerco/d1cf423c7a23b95949b97fe39cf03163

In the 9-minute video below, I do exactly that — walk through each test case!

Checking collections with confidence? If not, let me know and I’ll help you get what you need! And if you’d like more step-by-step, no-bullshit VBA guides delivered direct to your inbox, join my email newsletter below.

Get the VBA Toolbelt!

Quit digging through old projects and forums like a chump! Download the VBA Toolbelt and start with the most common Excel tasks already done for you.

The VBA Collection is a simple native data structure available in VBA to store (collect as you wish) objects. As Microsoft documentation explains Collections are objects containing an orders set of items. They are more flexible than VBA Arrays as they are not limited in their size at any point in time and don’t require manual re-sizing. Collections are also useful when you don’t want to leverage there more complex (but quite similar) Data Structures like the VBA ArrayList or even a VBA Dictionary.

Adding items to a VBA Collection

Let’s start by creating a New VBA Collection and adding some items to it.

Dim myCol As Collection

'Create New Collection
Set myCol = New Collection
    
'Add items to Collection
myCol.Add 10 'Items: 10
myCol.Add 20 'Items: 10, 20
myCol.Add 30 'Items: 10, 20, 30

Notice that the Collection is not typed in any way as we didn’t have to declare what types of objects it stores. This is because a Collection stores object of type Variant.

By default the Add procedure will push items to the end of the VBA Collection. However, you can also choose to insert items before or after any index in the Collection like so:
Before:

myCol.Add 10 'Items: 10
myCol.Add 20 'Items: 10, 20

myCol.Add 30, Before:= 1 'Items: 30, 10, 20

After:

myCol.Add 10 'Items: 10
myCol.Add 20 'Items: 10, 20

myCol.Add 30, After:= 1 'Items: 10, 30, 20

If you want to be able to reference a particular item in your VBA Collection by a certain string/name you can also define a key for object added to your VBA Collection like so:

myCol.Add 10, "Key10"
Debug.Print myCol("Key10") 'Returns 10

Removing items from a Collection

Removing items from a VBA Collection is equally easy. However, items are removed by specifying their index.

'Remove selected items from Collection
'Before Items: 10, 20, 30
myCol.Remove (2) 'Items: 10, 30
myCol.Remove (2) 'Items: 10

Be careful when removing items from a VBA Collection – items start indexing at 1 (not 0 as in most common programming languages.

When removing items in a loop do remember that the index of the remaining items in the VBA Collection will decrease by 1.

Clearing a Collection

To Clear all items (remove them) from a VBA Collection use the Clear function.

Dim myCol as Collection
Set myCol = New Collection
'...
myCol.Clear

Clearing all items from a Collection is similar to recreating a VBA Collection:

myCol.Clear
'...is similar to...
Set myCol = New Collection 

Counting items in a Collection

Similarly as with other VBA Data Structures the VBA Collection facilitates the Count function which returns the amount of items currently stored.

Dim myCol As Collection: Set myCol = New Collection

'Add 3 items to Collection
myCol.Add 10 'Items: 10
myCol.Add 20 'Items: 10, 20
myCol.Add 30 'Items: 10, 20, 30

Debug.Print myCol.Count '3 

Getting items in a Collection

To get a specific item in your VBA Collection you need to either specify it’s index or optionally it’s key (if it was defined).

Dim myCol As Collection
Set myCol = New Collection

'Add items to Collection
myCol.Add 10
myCol.Add 20, Key:="MyAge"
myCol.Add 30

'Get item at index 1
Debug.Print myCol(1) '20

'Get item with the specified key
Debug.Print myCol("MyAge") '20

Traversing a VBA Collection

As with VBA Arrays you can similarly traverse a VBA Collection using loops such as For, While etc. by indexing it’s items, or by traversing its items using the For Each loop (preferred).

Dim myCol As Collection: Set myCol = New Collection
myCol.Add 10: myCol.Add 20: myCol.Add 30

'Print items in Collection
Dim it As Variant
For Each it In myCol
  Debug.Print it '10, 20, 30
Next it

'Print items in Collection
Dim i As Long
For i = 1 To myCol.Count
  Debug.Print myCol(i) '10, 20, 30
Next i

Check if Collection contains item

Unfortunately, the VBA Collection object does not facilitate a Contains function. We can however easily write a simple Function that will extend this functionality. Feel free to use the Function below:

Function CollectionContains(myCol As Collection, checkVal As Variant) As Boolean
    On Error Resume Next
    CollectionContains = False
    Dim it As Variant
    For Each it In myCol
        If it = checkVal Then
            CollectionContains = True
            Exit Function
        End If
    Next
End Function

Usage example:

Dim myCol as Collection: Set myCol = New Collection
myColl.Add 10: myColl.Add 20: myColl.Add 30

Debug.Print CollectionContains(myCol, 20) 'True
Debug.Print CollectionContains(myCol, 40) 'False

Convert Collection to VBA Array

In some case you may want to convert your VBA Collection to a VBA Array e.g. if you would want to paste items from your Collection to a VBA Range. The Code below does that exactly that:

Function CollectionToArray(col As Collection) As Variant()
    Dim arr() As Variant, index As Long, it As Variant
    ReDim arr(col.Count - 1) As Variant
    For Each it In col
        arr(index) = it
        index = index + 1
    Next it
    CollectionToArray = arr
End Function

Below a test of how it works:

Sub TestCollectionToArray()
    Dim myCol As Collection, arr() as Variant
    Set myCol = New Collection
    myCol.Add 1
    myCol.Add 2
    myCol.Add 3
    arr = CollectionToArray(myCol)
End Sub 

Summary

The VBA Collection is an extremely useful data type in VBA. It is more versatile than the VBA Array allowing you to add and remove items more freely. The Key-Value store works also similarly as for the VBA Dictionary making it a useful alternative.

As an exercise – next time you will consider using a VBA Array consider replacing it with the Collection object. Hopefully it will guest in your VBA Code more often.

Содержание

  1. VBA Коллекции
  2. замечания
  3. Сравнение функций с массивами и словарями
  4. Добавление элементов в коллекцию
  5. Удаление элементов из коллекции
  6. Получение количества предметов коллекции
  7. Извлечение предметов из коллекции
  8. Определение наличия ключа или предмета в коллекции
  9. Ключи
  10. Предметы
  11. Очистка всех элементов из коллекции
  12. Generic way to check if a key is in a Collection in Excel VBA
  13. 6 Answers 6
  14. VBA Collections
  15. Remarks
  16. Feature Comparison with Arrays and Dictionaries
  17. Adding Items to a Collection
  18. Removing Items From a Collection
  19. Getting the Item Count of a Collection
  20. Retrieving Items From a Collection
  21. Determining if a Key or Item Exists in a Collection
  22. Items
  23. Clearing All Items From a Collection

VBA
Коллекции

замечания

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

Сравнение функций с массивами и словарями

Коллекция массив толковый словарь
Могут быть изменены да Иногда 1 да
Элементы заказаны да да Да 2
Элементы строго типизированы нет да нет
Элементы могут быть получены по порядковым номерам да да нет
Новые элементы могут быть вставлены по порядковому номеру да нет нет
Как определить, существует ли элемент Итерировать все элементы Итерировать все элементы Итерировать все элементы
Элементы могут быть получены ключом да нет да
Ключи чувствительны к регистру нет N / A Дополнительно 3
Как определить, существует ли ключ Обработчик ошибок N / A .Exists функция
Удалить все элементы Итерация и .Remove Erase , ReDim .RemoveAll функция

1 Могут быть изменены только динамические массивы и только последнее измерение многомерных массивов.

2 , лежащие в основе .Keys и .Items упорядочены.

3 Определяется свойством .CompareMode .

Добавление элементов в коллекцию

Элементы добавляются в Collection , вызывая метод .Add :

Синтаксис:

параметр Описание
вещь Элемент для хранения в Collection . Это может быть практически любое значение, которому может быть присвоена переменная, включая примитивные типы, массивы, объекты и Nothing .
ключ Необязательный. String которая служит уникальным идентификатором для извлечения элементов из Collection . Если указанный ключ уже существует в Collection , это приведет к ошибке времени выполнения 457: «Этот ключ уже связан с элементом этой коллекции».
до Необязательный. Существующий ключ ( String value) или индекс (числовое значение) для вставки элемента в Collection . Если задано значение, параметр after должен быть пустым или ошибка времени выполнения 5: «Неверный вызов или аргумент процедуры». Если передан String ключ, который не существует в Collection , это приведет к ошибке времени выполнения 5: «Неверный вызов или аргумент процедуры». Если числовой индекс передан, который не существует в Collection , это приведет к ошибке времени выполнения 9: «Подзаголовок вне диапазона».
после Необязательный. Существующий ключ ( String value) или индекс (числовое значение) для вставки элемента после в Collection . Если задано значение, параметр before должен быть пустым. Исправленные ошибки идентичны параметру before .

Заметки:

Ключи не чувствительны к регистру. .Add «Bar», «Foo» и .Add «Baz», «foo» приведет к столкновению клавиш.

Если ни один из необязательных параметров до или после не задан, элемент будет добавлен после последнего элемента Collection .

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

Пример использования:

Удаление элементов из коллекции

Элементы удаляются из Collection , вызывая ее метод .Remove :

Синтаксис:

параметр Описание
индекс Элемент для удаления из Collection . Если переданное значение является числовым или Variant с числовым подтипом, оно будет интерпретироваться как числовой индекс. Если переданное значение представляет собой String или Variant содержащий строку, это будет интерпретироваться как ключ a. Если передан String-ключ, который не существует в Collection , это приведет к ошибке времени выполнения 5: «Неверный вызов или аргумент процедуры». Если числовой индекс передан, который не существует в Collection , это приведет к ошибке времени выполнения 9: «Подзаголовок вне диапазона».

Заметки:

  • Удаление элемента из Collection изменит числовые индексы всех элементов после него в Collection . For циклов, которые используют числовые индексы и удаляющие элементы, должны работать в обратном направлении ( Step -1 ), чтобы исключить исключения в индексе и пропущенные элементы.
  • Элементы обычно не должны удаляться из Collection изнутри цикла For Each поскольку это может дать непредсказуемые результаты.

Пример использования:

Получение количества предметов коллекции

Количество элементов в Collection можно получить, вызвав ее функцию .Count :

Синтаксис:

Пример использования:

Извлечение предметов из коллекции

Элементы можно получить из Collection , вызвав функцию .Item .

Синтаксис:

параметр Описание
индекс Элемент для извлечения из Collection . Если переданное значение является числовым или Variant с числовым подтипом, оно будет интерпретироваться как числовой индекс. Если переданное значение представляет собой String или Variant содержащий строку, это будет интерпретироваться как ключ a. Если передан String-ключ, который не существует в Collection , это приведет к ошибке времени выполнения 5: «Неверный вызов или аргумент процедуры». Если числовой индекс передан, который не существует в Collection , это приведет к ошибке времени выполнения 9: «Подзаголовок вне диапазона».

Заметки:

  • .Item является членом Collection по умолчанию. Это обеспечивает гибкость в синтаксисе, как показано в примере использования ниже.
  • Числовые индексы основаны на 1.
  • Ключи не чувствительны к регистру. .Item(«Foo») и .Item(«foo») относятся к одному и тому же ключу.
  • Параметр индексне неявно приводится к числу из String или визы-Versa. Вполне возможно, что .Item(1) и .Item(«1») относятся к различным элементам Collection .

Пример использования (индексы):

Пример использования (ключи):

Пример использования (альтернативный синтаксис):

Обратите внимание, что синтаксис bang ( ! ) Разрешен, потому что .Item является членом по умолчанию и может принимать один аргумент String . Утилита этого синтаксиса сомнительна.

Ключи

В отличие от Scripting.Dictionary , в Collection нет способа определить, существует ли данный ключ или способ получить ключи, которые присутствуют в Collection . Единственный способ определить, присутствует ли ключ, — использовать обработчик ошибок:

Предметы

Единственный способ определить, содержится ли элемент в Collection — это перебирать Collection до тех пор, пока элемент не будет расположен. Обратите внимание, что поскольку Collection может содержать как примитивы, так и объекты, требуется дополнительная обработка, чтобы избежать ошибок во время сравнений:

Очистка всех элементов из коллекции

Самый простой способ очистить все элементы из Collection — просто заменить его на новую Collection а старая — выйти из области видимости:

Однако, если имеется несколько ссылок на Collection , этот метод даст вам только пустую Collection для назначенной переменной .

В этом случае самый простой способ очистить содержимое — это перебрать количество элементов в Collection и повторно удалить самый нижний элемент:

Источник

Generic way to check if a key is in a Collection in Excel VBA

I have different Collections in my code. Some hold Objects (of various kinds), others have types (like Long) within them.

Is there a way to check if a key is contained in the Collection that works for types as well as objects?

So far I have two functions.

The reason for the two functions is that ContainsObject does not seem to work if I pass a Collection that has Longs pairs (the function always returns False.)

P.S.: The first function is a copy of the third answer from Test or check if sheet exists

6 Answers 6

You should use a Variant in the first function. You can assign an Object to a Variant , e.g. this won’t error:

But this will give a Type Mismatch compile error i.e. trying to assign a Long to an Object :

So, for a generic function (along the lines of your code) to check if a Collection key is valid, you can use:

There is a useful article on MSDN regarding this. The context is VB6 but relates to VBA.

Few typos as per comments have already been corrected during edit of your post. In response to your question I would like to cover related aspects.
While Using keys in collections has mainly three advantages
— If the order changes your code will still access the correct item — You can directly access the item without reading through the entire collection
— It can make you code more readable.

*But at the same time there are mainly three issues with using keys in collections

You cannot check if the key exists

You cannot change the key

You cannot retrieve the key

As per Pearsons article the Keys of a Collection are write-only — there is no way to get a list of existing Keys of a Collection. Further going through quoted paragraph:-

Here, Coll is a Collection object in which we will store multiple CFile objects. The CollKeys Collection is used to store the keys of the CFile objects stored in the Coll Collection. We need this second Collection because the Keys of a Collection are write-only — there is no way to get a list of existing Keys of a Collection. One of the enhancements provided by CFiles is the ability to retrieve a list of Keys for the Collection.

One way is to iterate over the members of the collection and see if there is match for what you are looking for and the other way is to catch the Item not in collection error and then set a flag to say the item does not exist. Opinions differ on these approaches whereas some people feel it is not a good method to catch error while other section feels that it will be significantly faster than iteration for any medium to large collection.
So if we go for a method to catch error then error number we get depends on exactly what caused the error. We need a code routine to check the error. In a simplest way it could be.

Error catching routines proposed by various professionals differ in the error number they consider important and include in their routine.Various commonly occurring error numbers associated with collection object are:-

  • Error 5 Invalid procedure call or argument.This error can also occur if an attempt is made to call a procedure that isn’t valid on the current platform. For example, some procedures may only be valid for Microsoft Windows, or for the Macintosh, and so on.
  • error 438 «object doesn’t support this property or method An object is a class instance. A class instance supports some properties defined in that class type definition and does not support this one.
  • Error 457 This key is already associated with an element of this collection.You specified a key for a collection member that already identifies another member of the collection. Choose a different key for this member.
  • Error 91 Object variable or With block variable not set.There are two steps to creating an object variable. First you must declare the object variable. Then you must assign a valid reference to the object variable using the Set statement. You attempted to use an object variable that isn’t yet referencing a valid object.
  • Error 450 Wrong number of arguments or invalid property assignment.The number of arguments in the call to the procedure wasn’t the same as the number of required arguments expected by the procedure.If you tried to assign a value to a read-only property,

Among the above errors error number 438 has been considered important and the other one is 5. I am incorporating a Function routine in my sample testing program which was posted by Mark Nold 7 years back in 2008 vide SO question Determining whether an object is a member of a collection in VBA with due credit to him.

Some errors like error 457 won’t be allowed at the time of program test run. I tried to populated with duplicate keys data, it gave the error at the time of program testing itself as shown in the snapshot.

After removing it is showing correct output as shown in the snap shot.

It may not be possible to get the list of keys of a collection with a vanilla collection without storing the key values in an independent array. The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead. I have included this approach to get the list of keys in my program.
While populating Collection it is to be ensured that the key is the second parameter and must be a unique string.

Full code of my program is.

Final output as per program as shown in the Immediate window has been shown in the Snapshot.

Источник

VBA Collections

A Collection is a container object that is included in the VBA runtime. No additional references are required in order to use it. A Collection can be used to store items of any data type and allows retrieval by either the ordinal index of the item or by using an optional unique key.

Feature Comparison with Arrays and Dictionaries

Collection Array Dictionary
Can be resized Yes Sometimes 1 Yes
Items are ordered Yes Yes Yes 2
Items are strongly typed No Yes No
Items can be retrieved by ordinal Yes Yes No
New items can be inserted at ordinal Yes No No
How to determine if an item exists Iterate all items Iterate all items Iterate all items
Items can be retrieved by key Yes No Yes
Keys are case-sensitive No N/A Optional 3
How to determine if a key exists Error handler N/A .Exists function
Remove all items Iterate and .Remove Erase , ReDim .RemoveAll function

1 Only dynamic arrays can be resized, and only the last dimension of multi-dimensional arrays.

2 The underlying .Keys and .Items are ordered.

3 Determined by the .CompareMode property.

Adding Items to a Collection

Items are added to a Collection by calling its .Add method:

Syntax:

Parameter Description
item The item to store in the Collection . This can be essentially any value that a variable can be assigned to, including primitive types, arrays, objects, and Nothing .
key Optional. A String that serves as a unique identifier for retrieving items from the Collection . If the specified key already exists in the Collection , it will result in a Run-time error 457: «This key is already associated with an element of this collection».
before Optional. An existing key ( String value) or index (numeric value) to insert the item before in the Collection . If a value is given, the after parameter must be empty or a Run-time error 5: «Invalid procedure call or argument» will result. If a String key is passed that does not exist in the Collection , a Run-time error 5: «Invalid procedure call or argument» will result. If a numeric index is passed that is does not exist in the Collection , a Run-time error 9: «Subscript out of range» will result.
after Optional. An existing key ( String value) or index (numeric value) to insert the item after in the Collection . If a value is given, the before parameter must be empty. Errors raised are identical to the before parameter.

Notes:

Keys are not case-sensitive. .Add «Bar», «Foo» and .Add «Baz», «foo» will result in a key collision.

If neither of the optional before or after parameters are given, the item will be added after the last item in the Collection .

Insertions made by specifying a before or after parameter will alter the numeric indexes of existing members to match thier new position. This means that care should be taken when making insertions in loops using numeric indexes.

Sample Usage:

Removing Items From a Collection

Items are removed from a Collection by calling its .Remove method:

Syntax:

Parameter Description
index The item to remove from the Collection . If the value passed is a numeric type or Variant with a numeric sub-type, it will be interpreted as a numeric index. If the value passed is a String or Variant containing a string, it will be interpreted as the a key. If a String key is passed that does not exist in the Collection , a Run-time error 5: «Invalid procedure call or argument» will result. If a numeric index is passed that is does not exist in the Collection , a Run-time error 9: «Subscript out of range» will result.

Notes:

  • Removing an item from a Collection will change the numeric indexes of all the items after it in the Collection . For loops that use numeric indexes and remove items should run backwards ( Step -1 ) to prevent subscript exceptions and skipped items.
  • Items should generally not be removed from a Collection from inside of a For Each loop as it can give unpredictable results.

Sample Usage:

Getting the Item Count of a Collection

The number of items in a Collection can be obtained by calling its .Count function:

Syntax:

Sample Usage:

Retrieving Items From a Collection

Items can be retrieved from a Collection by calling the .Item function.

Syntax:

Parameter Description
index The item to retrieve from the Collection . If the value passed is a numeric type or Variant with a numeric sub-type, it will be interpreted as a numeric index. If the value passed is a String or Variant containing a string, it will be interpreted as the a key. If a String key is passed that does not exist in the Collection , a Run-time error 5: «Invalid procedure call or argument» will result. If a numeric index is passed that is does not exist in the Collection , a Run-time error 9: «Subscript out of range» will result.

Notes:

  • .Item is the default member of Collection . This allows flexibility in syntax as demonstrated in the sample usage below.
  • Numeric indexes are 1-based.
  • Keys are not case-sensitive. .Item(«Foo») and .Item(«foo») refer to the same key.
  • The index parameter is not implicitly cast to a number from a String or visa-versa. It is entirely possible that .Item(1) and .Item(«1») refer to different items of the Collection .

Sample Usage (Indexes):

Sample Usage (Keys):

Sample Usage (Alternate Syntax):

Note that bang ( ! ) syntax is allowed because .Item is the default member and can take a single String argument. The utility of this syntax is questionable.

Determining if a Key or Item Exists in a Collection

Unlike a Scripting.Dictionary, a Collection does not have a method for determining if a given key exists or a way to retrieve keys that are present in the Collection . The only method to determine if a key is present is to use the error handler:

Items

The only way to determine if an item is contained in a Collection is to iterate over the Collection until the item is located. Note that because a Collection can contain either primitives or objects, some extra handling is needed to avoid run-time errors during the comparisons:

Clearing All Items From a Collection

The easiest way to clear all of the items from a Collection is to simply replace it with a new Collection and let the old one go out of scope:

However, if there are multiple references to the Collection held, this method will only give you an empty Collection for the variable that is assigned.

In this case, the easiest way to clear the contents is by looping through the number of items in the Collection and repeatedly remove the lowest item:

Источник

# Getting the Item Count of a Collection

The number of items in a Collection can be obtained by calling its .Count function:

Syntax:

Sample Usage:

# Determining if a Key or Item Exists in a Collection

# Keys

Unlike a Scripting.Dictionary (opens new window), a Collection does not have a method for determining if a given key exists or a way to retrieve keys that are present in the Collection. The only method to determine if a key is present is to use the error handler:

# Items

The only way to determine if an item is contained in a Collection is to iterate over the Collection until the item is located. Note that because a Collection can contain either primitives or objects, some extra handling is needed to avoid run-time errors during the comparisons:

# Adding Items to a Collection

Items are added to a Collection by calling its .Add method:

Syntax:

Parameter Description
item The item to store in the Collection. This can be essentially any value that a variable can be assigned to, including primitive types, arrays, objects, and Nothing.
key Optional. A String that serves as a unique identifier for retrieving items from the Collection. If the specified key already exists in the Collection, it will result in a Run-time error 457: «This key is already associated with an element of this collection».
before Optional. An existing key (String value) or index (numeric value) to insert the item before in the Collection. If a value is given, the after parameter must be empty or a Run-time error 5: «Invalid procedure call or argument» will result. If a String key is passed that does not exist in the Collection, a Run-time error 5: «Invalid procedure call or argument» will result. If a numeric index is passed that is does not exist in the Collection, a Run-time error 9: «Subscript out of range» will result.
after Optional. An existing key (String value) or index (numeric value) to insert the item after in the Collection. If a value is given, the before parameter must be empty. Errors raised are identical to the before parameter.

Notes:

  • Keys are ****not**** case-sensitive. `.Add «Bar», «Foo»` and `.Add «Baz», «foo»` will result in a key collision.
  • If neither of the optional **before** or **after** parameters are given, the item will be added after the last item in the `Collection`.
  • Insertions made by specifying a **before** or **after** parameter will alter the numeric indexes of existing members to match thier new position. This means that care should be taken when making insertions in loops using numeric indexes.
  • Sample Usage:

    # Removing Items From a Collection

    Items are removed from a Collection by calling its .Remove method:

    Syntax:

    Parameter Description
    index The item to remove from the Collection. If the value passed is a numeric type or Variant with a numeric sub-type, it will be interpreted as a numeric index. If the value passed is a String or Variant containing a string, it will be interpreted as the a key. If a String key is passed that does not exist in the Collection, a Run-time error 5: «Invalid procedure call or argument» will result. If a numeric index is passed that is does not exist in the Collection, a Run-time error 9: «Subscript out of range» will result.

    Notes:

    • Removing an item from a Collection will change the numeric indexes of all the items after it in the Collection. For loops that use numeric indexes and remove items should run backwards (Step -1) to prevent subscript exceptions and skipped items.
    • Items should generally not be removed from a Collection from inside of a For Each loop as it can give unpredictable results.

    Sample Usage:

    # Retrieving Items From a Collection

    Items can be retrieved from a Collection by calling the .Item function.

    Syntax:

    Parameter Description
    index The item to retrieve from the Collection. If the value passed is a numeric type or Variant with a numeric sub-type, it will be interpreted as a numeric index. If the value passed is a String or Variant containing a string, it will be interpreted as the a key. If a String key is passed that does not exist in the Collection, a Run-time error 5: «Invalid procedure call or argument» will result. If a numeric index is passed that is does not exist in the Collection, a Run-time error 9: «Subscript out of range» will result.

    Notes:

    • .Item is the default member of Collection. This allows flexibility in syntax as demonstrated in the sample usage below.
    • Numeric indexes are 1-based.
    • Keys are not case-sensitive. .Item("Foo") and .Item("foo") refer to the same key.
    • The index parameter is not implicitly cast to a number from a String or visa-versa. It is entirely possible that .Item(1) and .Item("1") refer to different items of the Collection.

    Sample Usage (Indexes):

    Sample Usage (Keys):

    Sample Usage (Alternate Syntax):

    Note that bang (!) syntax is allowed because .Item is the default member and can take a single String argument. The utility of this syntax is questionable.

    # Clearing All Items From a Collection

    The easiest way to clear all of the items from a Collection is to simply replace it with a new Collection and let the old one go out of scope:

    However, if there are multiple references to the Collection held, this method will only give you an empty Collection for the variable that is assigned.

    In this case, the easiest way to clear the contents is by looping through the number of items in the Collection and repeatedly remove the lowest item:

    A Collection is a container object that is included in the VBA runtime. No additional references are required in order to use it. A Collection can be used to store items of any data type and allows retrieval by either the ordinal index of the item or by using an optional unique key.

    # Feature Comparison with Arrays and Dictionaries

    Collection Array (opens new window) Dictionary (opens new window)
    Can be resized Yes Sometimes1 Yes
    Items are ordered Yes Yes Yes2
    Items are strongly typed No Yes No
    Items can be retrieved by ordinal Yes Yes No
    New items can be inserted at ordinal Yes No No
    How to determine if an item exists Iterate all items Iterate all items Iterate all items
    Items can be retrieved by key Yes No Yes
    Keys are case-sensitive No N/A Optional3
    How to determine if a key exists Error handler N/A .Exists function
    Remove all items Iterate and .Remove Erase, ReDim .RemoveAll function

    1 Only dynamic arrays can be resized, and only the last dimension of multi-dimensional arrays.

    2 The underlying .Keys and .Items are ordered.

    3 Determined by the .CompareMode property.

    Понравилась статья? Поделить с друзьями:
  • Collect word from letters
  • Collect data in excel
  • Collapsing rows on excel
  • Collapse text box word
  • Coldest place in the word