【问题标题】:Alternative solution for looping through the Range in VBA在 VBA 中循环遍历 Range 的替代解决方案
【发布时间】:2020-08-12 22:00:59
【问题描述】:

最近我想知道通过切换下面的部分代码来加速程序的可能性:

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 中获取单元格值,那么毫无疑问。 由于这是我的第一篇文章,我可能写错了一些东西/在错误的发布约定中。告诉我,我会解决的。

干杯

【问题讨论】:

  • 我不确定你到底在问什么。您可以将范围分配给没有循环的数组,例如myValues=range("A1:A10").value。网上很多。

标签: excel vba optimization foreach range


【解决方案1】:

正如@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


【讨论】:

    【解决方案2】:

    如果原因是为了摆脱二维数组,这样的函数可能是解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      相关资源
      最近更新 更多