我在函数中有一堆循环,它们循环遍历我定义为动态范围的数组。下面是我想要实现的一些伪代码
Dim myArray As Range
myArray(x, j) 'So the array loops through each column and then each row in that column
For i = 1 to lastRow
If myArray(x, j).Value = myArray(x, i).Value Then
'Do something
我有一堆这样的循环,它的超级数据集超过100行。基本上我把myArray定义为Range的地方,我想把它改成Variant所以我可以a)遍历数组并且b)使用数组检查值是否相同而不是检查范围的范围,当有200行* 500列
时,这可能是性能问题的根本原因修改
如何将动态定义的范围转换为数组?
我需要做这样的事吗?
lastRow = UBound(myArray, 1)
lastColumn = UBound(myArray, 2)
然后
If myArray(x, j) = myArray(x, i) Then
'Do something
答案 0 :(得分:3)
将范围加载到数组中:
Dim RngArr() as Variant
RngArr = WorkSheets("Sheet1").Range("A1:D4").Value
这将创建4 x 4的数组。
使范围动态
Dim RngArr() as Variant
Dim lastrow as Long
Dim lastColumn as Long
lastrow = 10
lastColumn = 10
With WorkSheets("Sheet1")
RngArr = .Range(.Cells(1,1),.Cells(lastrow,lastColumn)).Value
End With
以这种方式加载数组时,两个维度的下限均为1,而不是0,否则为0。
迭代数组:
Dim i as long, j as long
For i = lbound(RngArr, 1) to Ubound(RngArr, 1)
For j = lbound(RngArr, 2) to Ubound(RngArr, 2)
'Do something with RngArr(i,j)
Next j
Next i
lbound和ubound的第二个标准是维度。