Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign one dimension of a 2d array to a new 1d array in VBA

I need to be able to create a newarray and assign it to another2darray(atsomeelement)

Example

array1(0) = 1
array1(1) = 2

and now

array2(0) = array1

and therefore

array2(0)(0) = 1
array2(0)(1) = 2

Now I want to take make a new array and assign 1d of the array2 to it.

newarray = array2(0)

and therefore

newarray(0) = 1
newarray(1) = 1

I cannot do this in VBA code.
Code snippet below, works if you comment out the last section where I try and assign array2(1) to arraynew.

Function test()
    Dim array1(0 To 20) As String
    Dim array2(0 To 5) As Variant
    Dim count As Integer

    For count = 0 To UBound(array1)
     array1(count) = count
    Next count

    'now that array1 is filled i want to insert it into array2(1)
    array2(1) = array1

    ' test
    MsgBox (array2(1)(3))

    'now i want to create a new string array and assign it to array2(1)
    Dim arraynew(0 To 20) As String
    arraynew = array2(1)
    'this is what fails. 

End Function
like image 330
Aden Avatar asked Jan 13 '12 00:01

Aden


People also ask

How do you assign a single value to a 2D array?

int contents[][] = new int[2][2]; contents[0][0] = 1; contents[1][1] = 2; ... That will let you individual assign values to elements in your 2D array, one at a time.

Can you create a 2 dimensional array with different types?

You can even create a two-dimensional array where each subarray has a different length or different type, also known as a heterogeneous array in Java. This means it's possible to create a two-dimensional array with variable column length in Java.

How do you assign an array in VBA?

The other way is to assign the array returned by the Array function to a Variant variable, as shown in the following example. You identify the elements in an array of Variant values by index, no matter which technique you use to create the array.


1 Answers

You cannot assign to a fixed-size array. Declare it as a dynamic one.

Dim arraynew() As String
arraynew = array2(1) 
like image 98
GSerg Avatar answered Nov 04 '22 17:11

GSerg