我有一个数组和一个向量。我想用向量传递/替换数组中的行。
2d array, as below
arr = [[1, 2],
[3, 4],
[a, b]] <--- replace with vct here
...where vct = [[5, 6]]
虽然可以使用朴素循环不成熟地完成,但我想知道是否有任何创造性的解决方法。示例如下。
使用朴素循环:
For i = 1 to 2
arr(3, i) = vct(i)
Next i
......或者一些聪明的解决方法:
arr(3, :) = vct ...where ":" represents "all columns"
结果预期:
arr = [[1, 2],
[3, 4],
[5, 6]]
Tbh我对vba的期望很低,因为即使是简单的数组索引也不是真的。我只是希望,如果有人想要对此提出一个解决方案。 TQ
通过添加vba代码块进行编辑以提高问题清晰度。见下文
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 ":"
听起来你想要这样的东西
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
我建议使用基于数组计数0,因为您可以轻松使用Array(1, 2)
创建向量。
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
要直接访问其中一个向量,请使用:
Debug.Print Vectors(2)(0) '=5
Debug.Print Vectors(2)(1) '=6
或者提取例如第二矢量使用
Dim SecondVector() As Variant
SecondVector = Vectors(1)
Debug.Print SecondVector(0) '=3
有关使用数组的更多信息,我建议您阅读: The Complete Guide to Using Arrays in Excel VBA