Цикл For Each… Next в VBA Excel, его синтаксис и описание отдельных компонентов. Примеры использования цикла For Each… Next.
Цикл For Each… Next в VBA Excel предназначен для выполнения блока операторов по отношению к каждому элементу из группы элементов (диапазон, массив, коллекция). Этот замечательный цикл применяется, когда неизвестно количество элементов в группе и их индексация, в противном случае, более предпочтительным считается использование цикла For…Next.
For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] |
В квадратных скобках указаны необязательные атрибуты цикла For Each… Next.
Компоненты цикла For Each… Next
Компонент | Описание |
---|---|
element | Обязательный атрибут в операторе For Each, необязательный атрибут в операторе Next. Представляет из себя переменную, используемую для циклического прохода элементов группы (диапазон, массив, коллекция), которая предварительно должна быть объявлена с соответствующим типом данных*. |
group | Обязательный атрибут. Группа элементов (диапазон, массив, коллекция), по каждому элементу которой последовательно проходит цикл For Each… Next. |
statements | Необязательный** атрибут. Операторы вашего кода. |
Exit For | Необязательный атрибут. Оператор выхода из цикла до его окончания. |
*Если цикл For Each… Next используется в VBA Excel для прохождения элементов коллекции (объект Collection) или массива, тогда переменная element должна быть объявлена с типом данных Variant, иначе цикл работать не будет.
**Если не использовать в цикле свой код, смысл применения цикла теряется.
Примеры циклов For Each… Next
Цикл для диапазона ячеек
На активном листе рабочей книги Excel выделите диапазон ячеек и запустите на выполнение следующую процедуру:
Sub test1() Dim element As Range, a As String a = «Данные, полученные с помощью цикла For Each… Next:» For Each element In Selection a = a & vbNewLine & «Ячейка « & element.Address & _ » содержит значение: « & CStr(element.Value) Next MsgBox a End Sub |
Информационное окно MsgBox выведет адреса выделенных ячеек и их содержимое, если оно есть. Если будет выбрано много ячеек, то полностью информация по всем ячейкам выведена не будет, так как максимальная длина параметра Prompt функции MsgBox составляет примерно 1024 знака.
Цикл для коллекции листов
Скопируйте следующую процедуру VBA в стандартный модуль книги Excel:
Sub test2() Dim element As Worksheet, a As String a = «Список листов, содержащихся в этой книге:» For Each element In Worksheets a = a & vbNewLine & element.Index _ & «) « & element.Name Next MsgBox a End Sub |
Информационное окно MsgBox выведет список наименований всех листов рабочей книги Excel по порядковому номеру их ярлычков, соответствующих их индексам.
Цикл для массива
Присвоим массиву список наименований животных и в цикле For Each… Next запишем их в переменную a. Информационное окно MsgBox выведет список наименований животных из переменной a.
Sub test3() Dim element As Variant, a As String, group As Variant group = Array(«бегемот», «слон», «кенгуру», «тигр», «мышь») ‘или можно присвоить массиву значения диапазона ячеек ‘рабочего листа, например, выбранного: group = Selection a = «Массив содержит следующие значения:» & vbNewLine For Each element In group a = a & vbNewLine & element Next MsgBox a End Sub |
Повторим ту же процедуру VBA, но всем элементам массива в цикле For Each… Next присвоим значение «Попугай». Информационное окно MsgBox выведет список наименований животных, состоящий только из попугаев, что доказывает возможность редактирования значений элементов массива в цикле For Each… Next.
Sub test4() Dim element As Variant, a As String, group As Variant group = Array(«бегемот», «слон», «кенгуру», «тигр», «мышь») ‘или можно присвоить массиву значения диапазона ячеек ‘рабочего листа, например, выделенного: group = Selection a = «Массив содержит следующие значения:» & vbNewLine For Each element In group element = «Попугай» a = a & vbNewLine & element Next MsgBox a End Sub |
Этот код, как и все остальные в этой статье, тестировался в Excel 2016.
Цикл для коллекции подкаталогов и выход из цикла
В этом примере мы будем добавлять в переменную a названия подкаталогов на диске C вашего компьютера. Когда цикл дойдет до папки Program Files, он добавит в переменную a ее название и сообщение: «Хватит, дальше читать не буду! С уважением, Ваш цикл For Each… Next.».
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
Sub test5() Dim FSO As Object, myFolders As Object, myFolder As Object, a As String ‘Создаем новый FileSystemObject и присваиваем его переменной «FSO» Set FSO = CreateObject(«Scripting.FileSystemObject») ‘Извлекаем список подкаталогов на диске «C» и присваиваем ‘его переменной «myFolders» Set myFolders = FSO.GetFolder(«C:») a = «Папки на диске C:» & vbNewLine ‘Проходим циклом по списку подкаталогов и добавляем в переменную «a« ‘их имена, дойдя до папки «Program Files«, выходим из цикла For Each myFolder In myFolders.SubFolders a = a & vbNewLine & myFolder.Name If myFolder.Name = «Program Files» Then a = a & vbNewLine & vbNewLine & «Хватит, дальше читать не буду!» _ & vbNewLine & vbNewLine & «С уважением,» & vbNewLine & _ «Ваш цикл For Each... Next.« Exit For End If Next Set FSO = Nothing MsgBox a End Sub |
Информационное окно MsgBox выведет список наименований подкаталогов на диске C вашего компьютера до папки Program Files включительно и сообщение цикла о прекращении своей работы.
В результате работы программы будут выведены не только наименования подкаталогов, видимых при переходе в проводнике к диску C, но и скрытые и служебные папки. Для просмотра списка всех подкаталогов на диске C, закомментируйте участок кода от If до End If включительно и запустите выполнение процедуры в редакторе VBA Excel.
I’ll show you how to loop through an array in VBA and macros in Excel. This is a fairly simple concept but it can be a little tricky.
First, I’m assuming you already know what an array is and how to create and array in VBA [LINK to Article]. Now, that you know that, let’s get to looping though arrays.
There are two main ways to loop through all of the elements of an array in VBA and both of those will be covered below.
Create the Array
First, we need to create an array, and then we can loop through it.
myarray = Array("red", "green", "blue")
Loop through Array Method 1 — LBound and UBound Method
We use this code to loop though the array:
For i = LBound(myarray) To UBound(myarray)
MsgBox "Array value: " & myarray(i)
Next i
The MsgBox part of this code is simply what creates output so that we can see that this loop is working.
The actual loop is just this part:
For i = LBound(myarray) To UBound(myarray)
'inside the loop
Next i
To get this loop to work with your array, you simply need to replace myarray with the name of your array. If you want a more detailed explanation of everything, continue reading.
There are a few things going on here, so let’s start first with LBound and UBound.
LBound is a function in VBA that will find the lowest point of the array. This generates a number equal to the lowest index key for the array. The array that you want this to work on is put within this function, in this case, myarray.
UBound is a function in VBA that will find the highest point of the array. It outputs a number equal to the highest index key for the array. The array that you want this to work on is put within this function, in this case, myarray.
Now, we use these two functions within a basic For Next loop.
The For Next loop does this:
It sets a variable, in this case i (but it could be any name you want), equal to the LBound function’s output. Then, it says that this loop should continue running up to when it gets to the number provided by the UBound function, which will be the last index number in the array.
You need to close the loop with Next and then the variable i so that it will continue the loop, adding 1 each time.
Accessing Data from the Array within the Loop
You need to be able to get the data from the array variable and here is how you do it using this method:
While inside the loop, you put the name of your array and then inside parenthesis you put i or whichever variable you used in the loop in place of i; this will get the output from the array within the loop.
Download the accompanying workbook and test out the loop to see how it works. The result of running this loop is that three message boxes will open and show you the data that is stored in the array variable. This loop is contained in the macro titled ArrayCreateLoop_1.
Loop through Array Method 2 — For Each …Next Loop Method
Using the For Each …Next method, we use this code to loop through the array:
For Each element In myarray
MsgBox "Array value: " & element
Next element
The name of the array is myarray and, in the middle of the loop, we have a line that starts with MsgBox that will output the contents of the array into a message box.
All you need to do to make this loop work for you is to change myarray to the name of your array variable.
If you want to learn more about the loop, keep reading.
This is the actual loop:
For Each element In myarray
'inside the loop
Next element
This loop will go through every part of the array and put it into a variable that we supply, in this case, the element variable.
You can name this variable whatever you want, you don’t have to call it «element». If you rename this, make sure to rename it in both paces, after where it says «For Each» and after «Next» — the «Next» part of the loop is what makes this a loop and tells the code to keep going through the variable until it is finished.
Accessing Data from the Array within the Loop
This is very easy to do using this method, simply use the variable that we used in the For Each loop, in this case element.
Anywhere you put this in the loop, the contents of the array will appear. You can see above how this was used in the line that starts with Msgbox.
Download the accompanying workbook and test out the loop to see how it works. The result of running this loop is that three message boxes will open and show you the data that is stored in the array variable. This loop is contained in the macro titled ArrayCreateLoop_2.
Notes
Both of these methods will work just fine for looping though a basic one dimensional array. For basic arrays, I would use the For Each loop since its syntax is quite a bit easier to understand and use.
However, don’t forget the LBound UBound method because you will often come across it when working with macros in Excel and it works great with more complex array functions.
Also, don’t forget to download the accompanying workbook so you can look at the code and play with it.
Similar Content on TeachExcel
Loop through All Worksheets in Excel using VBA and Macros
Tutorial: Ill show you how to loop through all of the worksheets in a workbook in Excel using VBA an…
Excel VBA — Create an Array — 3 ways
Tutorial: Ill show you three different ways to create an array in Excel VBA and Macros and how to ge…
How to Add a New Line to a Message Box (MsgBox) in Excel VBA Macros
Tutorial: I’ll show you how to create a message box popup window in Excel that contains text on mult…
Loop through a Range of Cells in Excel VBA/Macros
Tutorial: How to use VBA/Macros to iterate through each cell in a range, either a row, a column, or …
Data Validation List with Dynamic Arrays in Excel
Tutorial:
How to make a drop down menu list using data validation and dynamic arrays in Excel 365.
…
Select Cells in Excel using Macros and VBA
Tutorial: This is actually a very easy thing to do and only requires a couple lines of code. Below I…
Subscribe for Weekly Tutorials
BONUS: subscribe now to download our Top Tutorials Ebook!
Return to VBA Code Examples
In this Article
- For Each Item in Array
- For Next Loop
- Loop Through Part of Array
- Loop Through Entire Array
This tutorial will teach you how to loop through Arrays in VBA.
There are two primary ways to loop through Arrays using VBA:
- For Each Loop – The For Each Loop will loop through each item in the array.
- For Next Loop – The For Next Loop will loop through specified start and end positions of the array (We can use the UBound and LBound Functions to loop through the entire array).
For Each Item in Array
The For Each Loop enables you to loop through each element of the array.
Sub LoopForArrayStatic()
'declare a variant array
Dim strNames(1 To 4) As String
'populate the array
strNames(1) = "Bob"
strNames(2) = "Peter"
strNames(3) = "Keith"
strNames(4) = "Sam"
'declare a variant to hold the array element
Dim item as variant
'loop through the entire array
For Each item in strNames
'show the element in the debug window.
Debug.Print item
Next item
End Sub
The above procedure will loop through all the names in the array.
For Next Loop
The For Next Loop will loop through each item at a specified start and end position of the array.
Loop Through Part of Array
You can manually specify the start and end positions for your loop. This may be appropriate if you know your array size and/or you only want to loop through part of an array.
Sub LoopForNextStatic()
'declare a variant array
Dim strNames(1 To 4) As String
'populate the array
strNames(1) = "Bob"
strNames(2) = "Peter"
strNames(3) = "Keith"
strNames(4) = "Sam"
'declare an integer
Dim i As Integer
'loop from position 2 to position 3 of the array
For i = 2 To 3
'show the name in the immediate window
Debug.Print strNames(i)
Next i
End Sub
In the example above, we have looped through positions 2 and 3 of the array. The immediate window would return the names as follows.
Loop Through Entire Array
Next, we will use the UBound and LBound Functions to loop through an entire array. This is extremely useful if the start and end positions of the array might change (ex. a Dynamic Array):
Sub LoopForNextDynamic()
'declare a variant array
Dim strNames() As String
'initialize the array
ReDim strNames(1 to 4)
'populate the array
strNames(1) = "Bob"
strNames(2) = "Peter"
strNames(3) = "Keith"
strNames(4) = "Sam"
'declare an integer
Dim i As Integer
'loop from the lower bound of the array to the upper bound of the array - the entire array
For i = LBound(strNames) To UBound(strNames)
'show the name in the immediate window
Debug.Print strNames(i)
Next i
End Sub
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!
I have an array of Strings:
Dim sArray(4) as String
I am going through each String in the array:
for each element in sarray
do_something(element)
next element
do_something
takes a string as a parameter
I am getting an error passing the element as a String:
ByRef Argument Mismatch
Should I be converting the element to a String or something?
TylerH
20.6k64 gold badges76 silver badges97 bronze badges
asked Nov 19, 2010 at 18:22
Alex GordonAlex Gordon
55.8k284 gold badges666 silver badges1051 bronze badges
1
Element needs to be a variant, so you can’t declare it as a string. Your function should accept a variant if it is a string though as long as you pass it ByVal.
Public Sub example()
Dim sArray(4) As string
Dim element As variant
For Each element In sArray
do_something element
Next element
End Sub
Sub do_something(ByVal e As String)
End Sub
The other option is to convert the variant to a string before passing it.
do_something CStr(element)
BigBen
43.9k6 gold badges27 silver badges40 bronze badges
answered Nov 19, 2010 at 19:27
2
A for each loop structure is more designed around the collection object. A For..Each loop requires a variant type or object. Since your «element» variable is being typed as a variant your «do_something» function will need to accept a variant type, or you can modify your loop to something like this:
Public Sub Example()
Dim sArray(4) As String
Dim i As Long
For i = LBound(sArray) To UBound(sArray)
do_something sArray(i)
Next i
End Sub
answered Nov 19, 2010 at 18:51
FinkFink
3,31619 silver badges26 bronze badges
2
I use the counter variable like Fink suggests. If you want For Each and to pass ByRef (which can be more efficient for long strings) you have to cast your element as a string using CStr
Sub Example()
Dim vItm As Variant
Dim aStrings(1 To 4) As String
aStrings(1) = "one": aStrings(2) = "two": aStrings(3) = "three": aStrings(4) = "four"
For Each vItm In aStrings
do_something CStr(vItm)
Next vItm
End Sub
Function do_something(ByRef sInput As String)
Debug.Print sInput
End Function
answered Nov 19, 2010 at 20:39
Dick KusleikaDick Kusleika
32.5k4 gold badges51 silver badges73 bronze badges
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
answered Jun 17, 2014 at 7:24
If alternatives are acceptable for this case, I would rather suggest UBound :
For i = 1 to UBound(nameofthearray)
your code here
next i
answered Apr 28, 2021 at 23:55
A For Each loop is used to execute a statement or a set of statements for each element in an array or collection.
Syntax:
For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ]
The For…Each…Next statement syntax has the following three parts:
Part | Description |
---|---|
element | Required (Must be mentioned). Variable is used to iterate through the elements of the collection or array. For collections, the element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, the element can only be a Variant variable. |
group | Required(Must be mentioned). Name of an object collection or array (except an array of user-defined types). |
statement | Optional (May or may not be mentioned). One or more statements are executed on each item in the group. |
There are 4 basic steps to writing a For Each Next Loop in VBA:
- Declare a variable.
- Write the For Each Line with the variable and collection references.
- Add line(s) of code to repeat for each item in the collection.
- Write the Next line to terminate the loop.
The For…Each block is entered if there is at least one element in the group. Upon entering the loop, all the statements in the loop are executed for each element. When there are no more elements in the group, the loop is exited and execution continues with the statement following the Next statement. The next statement line terminates the loop.
Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example, If…Then, and transfers control to the statement immediately following Next.
You can also nest For…Each…Next loops by placing one For…Each…Next loop within another. However, each loop element must be unique in its way.
NOTE
- Execution continues as if element is included, if you omit element in a Next statement.
- An error occurs, If a Next statement is encountered before its corresponding For statement,
You can’t use the For…Each…Next statement with an array of user-defined types because a Variant can’t contain a user-defined type.
Example 1
Private Sub Demo_Loop()
students is an array
students = Array(“Akshit”, “Nikita”, “Ritesh”) //Initialising Array-> students
Dim studentnames As Variant // Variable is assigned
‘iterating using For each loop.
For Each Item In students
studentnames =studentnames & Item & Chr(10)
Next
MsgBox studentnames
End Sub
It would look somewhat like below:
When the above code is executed, it prints all the student names with one item in each line.