Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations SSS148 on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to define an Array?

Status
Not open for further replies.

feajob

Aerospace
Aug 19, 2003
161
Hi,

I would like to know how can I define an Array in VB (Excel)?

I tried the following commands:

Dim myArray(5) As Integer

myArray = Array(12,3,13,64,245,75)

But, I got a compile error as follows:

Can't assign to array

Please let me know what is the proper way for defining an Array?

Thanks,
A.A.Y.
 
Replies continue below

Recommended for you

The two statements don't work together.

You can either use:
Code:
myArray = Array(12, 3, 13, 64, 245, 75)
' (no dim statement)
' won't work if option explicit is included

Or else you can use:
Code:
dim myArray(5) As Integer
myArray(0) = 12
myArray(1) = 3
myArray(2) = 13
myArray(3) = 64
myArray(4) = 245
myArray(5) = 75

=====================================
Eng-tips forums: The best place on the web for engineering discussions.
 
Or dimension the array as a variant (which is the default if you don't dimension it). Then you can leave the Option Explicit statement in place.

You can also transfer the contents of a worksheet range to an array:

Code:
Dim MyArray as Variant

MyArray = Range("MyRange").Value2

Note that:
1. The array is automatically re-sized to the size of the range, so you don't need to specify the array size (in fact it won't work if you do).

2. Use .Value2 rather than .Value (the default) or nothing because it is quicker and it won't truncate values formatted as currency to 4 decimal places.

3. All arrays will be 2D, base 1, so a range of 1 row x 10 columns will come in as MyArray(1 to 1, 1 to 10).

Doug Jenkins
Interactive Design Services
 
ids said:
Or dimension the array as a variant (which is the default if you don't dimension it). Then you can leave the Option Explicit statement in place.
No, that doesn't work for me. The following code gives an error ("Compile Error: Can't Assign to Array"):
Code:
Dim myArray(5) As Variant
myArray = Array(12, 3, 13, 64, 245, 75)


=====================================
Eng-tips forums: The best place on the web for engineering discussions.
 
Pete - you didn't read my notes!

Either
Dim MyArray as variant
or
Dim MyArray() as variant

will work.


The array is automatically redimmed when you assign something to it.

Doug Jenkins
Interactive Design Services
 
Hi,

Thank you for your replies. They helped me to solve my bug.

A.A.Y.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor