Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a for each loop on an array?

Tags:

excel

vba

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?

like image 660
Alex Gordon Avatar asked Nov 19 '10 18:11

Alex Gordon


People also ask

Can you use a For Each loop on an array?

For-Each Loop is another form of for loop used to traverse the array. for-each loop reduces the code significantly and there is no use of the index or rather the counter in the loop. Syntax: For(<DataType of array/List><Temp variable name> : <Array/List to be iterated>){ System.

How do you loop through each element in an array?

How to Loop Through an Array with a forEach Loop in JavaScript. The array method forEach() loop's through any array, executing a provided function once for each array element in ascending index order. This function is known as a callback function.

How is for each loop used in Java with arrays?

How it works? The Java for-each loop traverses the array or collection until the last element. For each element, it stores the element in the variable and executes the body of the for-each loop.


1 Answers

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) 
like image 51
Bobsickle Avatar answered Sep 19 '22 17:09

Bobsickle