所以也许是星期一,也许我很愚蠢。。但是我无法终生想出一种从2D数组中的一行中获取1D数组的好方法。(也许这不是一个“真实的”二维数组?)
无论如何,我有一个这样定义的数组: dim myArr(2,4) as variant
我用值1-15填充它,所以看起来像:
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
所以现在我想要的是该数组的一行。我能弄清楚的唯一方法是这样做:
dim temp() as variant
ReDim temp(lbound(myArr,2) to ubound(myArr,2))
For i = 0 To 0
For j = LBound(myArr, 2) To UBound(myArr, 2)
temp(j) = myArr(i, j)
Next
Next
但是我不喜欢这样,因为如果数组很大,那么执行该操作所需的时间可能会更长。我认为我应该能够做到:
dim temp as variant
temp = myArr(0) 'since myArr(0) is a 1D array with 5 spots right?
但没有。我收到“错误的尺寸数”错误。
我还翻阅了之前的内容,发现了这个问题:如何比较工作表中的两行,蒂姆·托马斯(tim thomas)的答案显示了转置的使用,并提到如果您比较的是列,则只使用转置一次,但是不起作用..如果我像这样:dim myArr(2,0) as variant
转置起作用,但不是我现在拥有的方式。
我在其他语言(例如C ++和Python)中找到了无数的答案,但我都不熟悉,因此无法解释它们。
有更好的方法吗?还是我陷入了我不喜欢的双循环?
谢谢!
这是“切片”二维数组的一种方法的完整示例:
Sub ArraySlicing()
Dim arr(1 To 5, 1 To 5)
Dim slice
Dim x, y
Dim a As Application
'Populate a sample 2-D array with values...
For y = 1 To 5
For x = 1 To 5
arr(y, x) = "R" & y & ":C" & x
Next x
Next y
'...done setting up sample array
Set a = Application 'this is just to shorten the following lines
'Example 1: get the first "column"
slice = a.Transpose(a.Index(arr, 0, 1))
Debug.Print Join(slice, ", ") 'display what we got
'Example 2: get second "row" (note double transpose)
slice = a.Transpose(a.Transpose(a.Index(arr, 2, 0)))
Debug.Print Join(slice, ", ") 'display what we got
End Sub
Index()为您提供2维数组-(x,1)或(1,x)-Transpose()会将其转换为1维数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句