【问题标题】:Assigning values to a dynamically resized array in Excel VBA在 Excel VBA 中为动态调整大小的数组赋值
【发布时间】:2014-01-22 05:48:06
【问题描述】:

我正在尝试填充一个二维范围数组。我不知道数组需要多大,所以我使用 ReDim 和 Preserve 函数根据需要动态调整数组大小。

我在运行代码时遇到运行时错误 91:“对象变量或未设置块变量”。

我不是经验丰富的编码员,但我已经设法隔离了错误,并且确信它来自下面的伪代码。

谁能看到我犯的任何会产生运行时错误的错误?

    Dim ArrayName() as Range
    Dim counter as Integer

    If condition = True Then

        counter = counter + 1

        ReDim Preserve ArrayName(0, counter - 1) 
        ArrayName(0, counter - 1) = Cells(counter, counter) 'I get a runtime error here

    End If

谢谢。

【问题讨论】:

    标签: arrays excel preserve vba


    【解决方案1】:

    如果你想在你的数组中存储范围,你需要在问题行之前添加Set

    Set ArrayName(0, counter - 1) = Cells(counter, counter)
    

    但如果你想存储单元格的值,你需要将声明行更改为:

    Dim ArrayName() as Double 'or String or Variant depending on value type you need to keep in array
    

    【讨论】:

    • 我不敢相信它这么简单!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2019-02-26
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多