Thread: VBA arrays
View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.misc
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default VBA arrays

Option Explicit
Sub testme()

Dim myArr() As Double
Dim HowMany As Long
Dim iCtr As Long

HowMany = CLng(Application.InputBox(Prompt:="How many?", Type:=1))

'some minor validity
If HowMany < 1 _
Or HowMany 100 Then
MsgBox "that won't work!"
Exit Sub
End If

ReDim myArr(1 To HowMany)

Randomize 'shuffle
For iCtr = LBound(myArr) To UBound(myArr)
myArr(iCtr) = Rnd
Next iCtr

End Sub

You could add a number to any element in the array:

myArr(77) = myArr(77) + 5.32421

(assuming that you have 77 elements)

You may want to visit J.E. McGimpsey's site and grab a copy of his =RandInt()
function.
http://www.mcgimpsey.com/excel/udfs/randint.html



Matt wrote:

I'm trying to get my head around lists (arrays?) in VBA. Lets say I
want to create an array of random numbers whose length is defined by
the user. Is this the right idea?

1 - It would ask the user how long the array should be.
2 - Then starting with an empty array, it would run through a for loop
as many times as defined by the user, each time appending a new random
number to the end.

I can't seem to figure out the right way to use arrays in VBA. Is
array(a, b, c) the best way to create them? How then do you add
another number to it? Or access the nth value in the array?


--

Dave Peterson