1

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I think the Lbound to Ubound is the more elegant of the two, and it works. Thank you.
0

This fills B1:B3

arRow = Array(11, 22, 33)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.