arrays - Excel VBA - 分配数组更改 LBound 和 UBound

标签 arrays excel vba bounds

我在 Excel 中有一些非常大的数据集,需要对其进行解析 - 在数组中进行解析比循环处理工作表中的数据更快。将所有数据加载到数组中会导致内存问题(数据集太大),因此我计划将数据子集加载到数组中,对其进行处理,然后加载另一个子集。我希望使用定义 LBound 和 UBound 的数组“功能”来帮助我跟踪我在工作表中的位置。但我发现将工作表值分配给数组会改变边界。 下面的代码演示了这个问题...

    Sub myTest3()
    Dim myRange As Range
    Dim myArray As Variant
    Dim myOffset As Long

        myOffset = 10
        Set myRange = Worksheets("RawData").Range("A1").CurrentRegion
        ReDim myArray(myOffset To myRange.Rows.Count, myRange.Columns.Count)
        MsgBox LBound(myArray, 1) & " to " & UBound(myArray)

        Set myRange = myRange.Offset(myOffset, 0).Resize(myRange.Rows.Count - myOffset, myRange.Columns.Count)

        myArray = myRange.Value2

        MsgBox LBound(myArray, 1) & " to " & UBound(myArray)

    End Sub

第一个 MsgBox 给我“10 到 10931”。 第二个 MsgBox 给我“1 到 10921”。

关于维持我最初定义的数组边界有什么想法吗?我知道循环遍历工作表来完成作业可以做到这一点,但速度会很慢。

提前致谢。

最佳答案

在这种情况下,Excel VBA 无法按您希望的方式工作。当您执行myArray = myRange.Value2时,myArray的原始内容被替换。 Redim med 数组被扔掉了。 Excel/VBA 不会查看目标,而是会替换目标,或者更正确地说,它会创建一个新数组并使 myaArray 变量指向该数组。

因此,您将需要更多代码才能到达您想要的位置。我会考虑将获取下一个 block 的代码放入一个单独的函数中,并在那里进行簿记:

Function ChunkAtOffset(rng As Range, rowsInChunk As Long, colsInChunk As Long, offsetRows As Long) As Variant
' Note: doesn't cater for the case where there are fewer than 'offsetRows' in the target    
Dim arr As Variant, result As Variant
Dim r As Long, c As Long

    arr = rng.offset(offsetRows).Resize(rowsInChunk, colsInChunk).Value2

    ReDim result(offsetRows To offsetRows + rowsInChunk - 1, 1 To colsInChunk)

    For r = 1 To rowsInChunk
        For c = 1 To colsInChunk
            result(offsetRows - 1 + r, c) = arr(r, c)
        Next
    Next

    ChunkAtOffset = result

End Function

如果我运行这个:

Sub myTest4()

    Dim curReg As Range, ary As Variant, offset As Long
    With Range("A1")
        Set curReg = .CurrentRegion
        Do
            ary = ChunkAtOffset(.CurrentRegion, 10, .CurrentRegion.Columns.Count, offset)
            Debug.Print LBound(ary, 1) & " to " & UBound(ary)
            offset = offset + 10
        Loop Until offset >= .CurrentRegion.Rows.Count
    End With

End Sub

...我现在明白了:

0 to 9
10 to 19
20 to 29

关于arrays - Excel VBA - 分配数组更改 LBound 和 UBound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19483124/

相关文章:

Javascript对象数组到字符串数组,更简单的方法?

excel - 使用 Dictionary 方法整合来自多个 csv 文件的数据

python - 使用 openpyxl 对齐图像

vba - 插入文本到 Activecell VBA

C#:有没有办法确定一个范围内的元素是否为空?

javascript - 删除关联数组中的元素

c - 如何将 uint8_t 数组从 C 发送到 GO

excel - 如果 (Aν = Bν+1) 则改变单元格颜色

excel - 在设置属性之前是否有任何理由检查它是否已设置?

ms-access - 为什么 VBA Access 中 134.605*100 不等于 13460.5?