Reputation: 105
I have an array, and a vector. I want to pass/replace a row in the array with the vector.
2d array, as below
arr = [[1, 2],
[3, 4],
[a, b]] <--- replace with vct here
...where vct = [[5, 6]]
While it can be done unsophisticatedly using the naive looping, I wonder if there is any creative workaround for it. Example as below.
Using naive looping:
For i = 1 to 2
arr(3, i) = vct(i)
Next i
...or some clever workaround:
arr(3, :) = vct ...where ":" represents "all columns"
Result expected:
arr = [[1, 2],
[3, 4],
[5, 6]]
Tbh I have low expectation for vba since even the simple array indexing isn't actually a thing. I just hope if anybody wanna take a stab on this to provide a solution. Tq
Edit to improve question clarity by adding vba code block. See below
Dim arr(1 to 3, 1 to 2) as Integer
Dim vct(1 to 2) as Integer
Dim i as Integer
' filling in arr
arr(1, 1) = 1
arr(1, 2) = 2
arr(2, 1) = 3
arr(2, 2) = 4
arr(3, 1) = 10
arr(3, 2) = 20
' filling in vct
vct(1) = 5
vct(2) = 6
' passing the vector vct into last row of arr using for loop
For i = 1 to 2
arr(3, i) = vct(i)
Next i
' as a result,
' arr(3, 1) = 5, and
' arr(3, 2) = 6
' which does its work perfectly
' but I am looking if there is any possibility
' to have a non-looping approach such as below
' arr(3, :) = vct
'
' this is because I am too accustomed to python syntax
' where it can be done as using ":"
Upvotes: 0
Views: 1228
Reputation: 57733
I recommend to use array counting 0 based because you can easily use Array(1, 2)
to create a vector.
Sub test()
Dim Vectors() As Variant
'fill it with 3 vectors (0 to 2)
Vectors = Array(Array(1, 2), Array(3, 4), Array("a", "b"))
'replace third vector with another one
Vectors(2) = Array(5, 6)
End Sub
To directly access one of these vectors use:
Debug.Print Vectors(2)(0) '=5
Debug.Print Vectors(2)(1) '=6
Or to extract eg the second vector use
Dim SecondVector() As Variant
SecondVector = Vectors(1)
Debug.Print SecondVector(0) '=3
For further information about using arrays I recommend reading:
The Complete Guide to Using Arrays in Excel VBA
Upvotes: 1
Reputation: 2055
It sound like you want something like this
Sub test()
Dim vaTest As Variant
vaTest = Array(Array(1, 2, 3), Array(4, 5, 6))
Debug.Print vaTest(0)(1) ' Prints 2
vaTest(0) = Array(7, 8, 9) ' changing first array
Debug.Print vaTest(0)(1) ' Prints 8
End Sub
Upvotes: 2