Append to an array

M

maweilian

This is my best guess on how to do this:

Dim testvalue, testarray()
For testvalue = 50 To 100 Step 5
ReDim Preserve testarray(UBound(testarray) + 1)
testarray(UBound(testarray)) = testvalue
Next testvalue

So the goal is to start with an array of unknown size and simply add values
until complete.

I am sure this is very flawed. Would appreciate any help.

Will
 
J

Joel

What is wrong with your code. It is not flawed.

I found the code below to be useful. You code created an extra item in the
array. When you do redim testarray(1) it really creates two items in the
array. A zero index and a one index. My code makes the aray exactly the
same size as the data that is inside. it really doesn't make a difference
except when you create a UDF function. then it sometimes matters. for
example you returned an array to the worksheet function Average. The average
would not be correct because you would be dviding by one more item then you
really had.

Sub test()

Dim testvalue, testarray

For testvalue = 50 To 100 Step 5
If IsArray(testarray) Then
ReDim Preserve testarray(0 To (UBound(testarray) + 1))
Else
ReDim testarray(0 To 0)
End If
testarray(UBound(testarray)) = testvalue
Next testvalue

End Sub
 

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