VBA - For each loop on an array...

RobbieC

Active Member
Joined
Dec 14, 2016
Messages
376
Office Version
  1. 2010
Platform
  1. Windows
Hi there, I want to run a 'For each loop' on an array.

I have the following code which will do what I need for a continuous string of numbers:

Code:
For i = 1 to 26

 'do something with i

next

but in this new case I only want several numbers : 1, 4, 9, 10, 15, 17, 23 etc

is it possible to run my above code with something like:

Code:
For i = array(1, 4, 9, 10, 15, 17, 23)

 'do something with i

next

If you can point me in the right direction, I'd be very grateful.

Thanks
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
Try:-
Code:
[COLOR="Navy"]Sub[/COLOR] MG26May29
[COLOR="Navy"]Dim[/COLOR] i [COLOR="Navy"]As[/COLOR] Variant
[COLOR="Navy"]For[/COLOR] [COLOR="Navy"]Each[/COLOR] i [COLOR="Navy"]In[/COLOR] Array(1, 4, 9, 10, 15, 17, 23)
    Debug.Print i
[COLOR="Navy"]Next[/COLOR]
[COLOR="Navy"]End[/COLOR] [COLOR="Navy"]Sub[/COLOR]
Regards Mick
 
Upvote 0
This code uses each element of the array and uses that number as a variable (ie rows, 1,4,9 etc).


Code:
Sub Loop_array()

Dim arr As Variant

Dim i As Long
Dim x As Long

arr = Array(1, 4, 9, 10, 15, 17, 19)



For i = LBound(arr) To UBound(arr)

x = arr(i)


Cells(x, 1).Value = 45

Next i

End Sub
 
Upvote 0
Brilliant Mick, works perfectly... that's gonna save me a whole load of time and code reproduction.

Thanks very much!
 
Upvote 0

Forum statistics

Threads
1,226,081
Messages
6,188,786
Members
453,499
Latest member
samdan87153

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top