我有一个数组和一个向量。我想用向量传递/替换数组中的一行。
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]]
我对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 ":"
答案 0 :(得分:2)
听起来你想要这样的东西
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
答案 1 :(得分:1)
我建议使用基于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