gpt4 book ai didi

vba - 将范围放入数组以获得更有效的循环

转载 作者:行者123 更新时间:2023-12-04 21:35:46 30 4
gpt4 key购买 nike

我在一个函数中有一堆循环,它们循环一个我定义为动态范围的数组。下面是我想要实现的一些伪代码

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

最佳答案

要将范围加载到数组中:

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,否则会如此。

遍历数组:
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 的第二个标准是维度。

关于vba - 将范围放入数组以获得更有效的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38644791/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com