Adding to Array

C

Charlotte E.

I have an array, which starts out like this:

PWL = Array("Data1", "Data2", "Data3")


Now I would like to add a value to this array?
As if it had started out like this:

PWL = Array("Data1", "Data2", "Data3", "Data4")


How do I add the "Data4" to the original array???


CE
 
J

joeu2004

Dim PWL As Variant
PWL = Array("Data1", "Data2", "Data3")
ReDim Preserve PWL(0 To 3)
PWL(3) = "Data4"

But if Option Base 1 were set, we would need ReDim Preserve PWL(1 to 4).

More generally:

ReDim Preserve PWL(LBound(PWL) to UBound(PWL)+1)

PS: If this is in a loop, I don't know how inefficient it is to increase an
array by just one. I usually increase by larger amounts, e.g.
2*UBound(PWL), and maintain variables, e.g. nPWL and nPWLmax, to track the
"active region" of the array. If/when it comes time to copy the array to a
worksheet, I would use Range("a1").Resize(,nPWL) = PWL.
 
J

Jim Cone

Good points.
I tend to limit the depth of a newsgroup response to the corresponding effort/detail put into the
question.
Jim Cone


"joeu2004" <[email protected]>
wrote in message
 
A

Auric__

joeu2004 said:
But if Option Base 1 were set, we would need ReDim Preserve PWL(1 to 4).

More generally:

ReDim Preserve PWL(LBound(PWL) to UBound(PWL)+1)

No need to specify the lower bound in this case:
ReDim Preserve PWL(UBound(PWL)+1)
 
C

Charlotte E.

And that concludes my lecture on arrays for today - thanks guys :)

CE


Den 23.10.2011 17:37, Charlotte E. skrev:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top