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

标签 vba excel

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

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/

相关文章:

vba - Excel 中未分配的热键

excel - 如何使用 VBA 代码从列表中获取唯一的 30 个随机数

ms-access - VBA - 编译错误 : Expected: If or Select or Sub or Function or Property or Type or With or Enum or end of statement

vba - 根据工作表更改运行宏(单元格包含公式)

excel - 在调试 VBA 代码时,我在保存“第 8 行需要对象”时遇到错误

excel - 将标题分成单词并在标题中搜索

java - 如何用Java做Excel的 "Convert to Number"

excel - 如何获取 Excel VBA 中打开的 powerpoint 演示文稿的处理程序

Excel增加公式内单元格的行数

excel - 简化拖动 Excel 公式