简体   繁体   中英

Need index for Each Loop with Array

I have an array which I populate with Varibles from an excel table. I then use an each loop to cycle through this array. The allocation of the array lines up with some cell I would like to populate.

'arRow is a Dynamic Array, that varies in size
For each vIndex in arRow
 if vIndex = 0 then
     'do nothing
   else
    'Populate corisponding cell
     Cells(2, ???).value = vIndex
  end if
next vindex

How would I find the index for the Each-Loop?

You can do this two ways. Both methods require a "counter" of sorts, as the array doesn't have any sort of indexed property you can access.

With a counter:

Dim i as Long
i = 0
For each vIndex in arRow
 i = i + 1
 if vIndex = 0 then
     'do nothing
   else
    'Populate corisponding cell
     Cells(2, i).value = vIndex
  end if
next vindex

Or with an indexed loop over the array (assumes a 1-dimensional array, but could be modified for multi-dimensional if needed):

Dim i
For i = LBound(arRow) to UBound(arRow)

   ...

Next

This fills B1:B3

arRow = Array(11, 22, 33)

For vIndex = 0 To UBound(arRow)
    Cells(vIndex + 1, 2).Value = arRow(vIndex)
Next

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM