在VBA中遍历范围的替代解决方案

问题描述

最近,我想知道是否可以通过切换下面的部分代码来加快程序的速度:

Dim cell as Variant
Dim myValues() as Double
ReDim myValues(myRange.Count - 1)
Dim i as Integer: i = 0

For Each cell in myRange.Cells

    myValue(i) = cell.Value
    i = i + 1

Next cell

进入一个循环,在该循环中,我可以直接引用每个单元格的值,而不是实例化一个单元格对象,而是从给定范围内为其分配一个单元格值,然后提取该单元格值。

在我看来,伪代码看起来像这样:

Dim cellValue as Double
Dim myValues() as Double
ReDim myValues(myRange.Count - 1)
Dim i as Integer: i = 0

For each cellValue in myRange.Cells.Values
    myValues(i) = cellValue
    i = i + 1
Next cellValue

如果从一开始我的整体概念是错误的,或者您无法更快地从Range获取单元格值,那么毫无疑问。 由于这是我的第一篇文章,因此我可能写错了一些东西/张贴约定错误。让我知道,我会修复它。

欢呼

解决方法

正如@SJR所指出的,这是不需逐个单元地访问范围内数据的一种常用方法。

Dim arr,i as long,rng As Range

Set rng = Activesheet.Range("A1:B20")

arr = rng.Value  'arr is now a 2D array (1 To 20,1 To 2)
                 'Note: base is 1 and not the more-typical 0

For i = 1 to ubound(arr,1)
     Debug.Print arr(i,1),arr(i,2)
Next i

arr(3,2) = 999

rng.value = arr 'put the data back to the range


,

如果原因是要摆脱2D数组,则可以使用如下功能:

Function VectorFromRange(rng As Range) As Variant
    Dim arrIn As Variant
    arr = rng.value 'Dumping the data from range
    Dim i As Long
    Dim item As Variant
    ReDim arrOut(1 To rng.Cells.Count) As Variant
    For Each item In arr
        i = i + 1
        arrOut(i) = item
    Next item
    VectorFromRange = arrOut
End Function