Excel VBA: 在数组中存储命名范围时出现应用程序或对象定义错误

Excel VBA: Application or object-defined error when storing named range in an array

我正在尝试将命名范围中的值存储到数组中,但在处理其中包含文本而非数字的命名范围时遇到了问题。 (这些命名范围是动态的,所以我希望能够使用命名范围来允许将其他值添加到列表中,并使用宏来合并它们。)

作为示例,我有两个命名范围:FruitQuantity。以下是每个范围内的值。

Fruit:苹果、橙子和香蕉(位于 B3:B5

Quantity:3、4 和 5(位于 C3:C5

下面是我想出的将 Fruit 存储在数组中的代码。

Sub FruitArray()
  Dim Fruits As Variant
  Dim Fruit As Variant

  Fruits = ThisWorkbook.Worksheets("Inventory").Range("Fruit") ' Run-time error '1004': Application-defined or object defined error

  For Each Fruit In Fruits
    Debug.Print Fruit
  Next
End Sub

当我 运行 这段代码时,我得到 "Run-time error '1004': Application-defined or object defined error" 并且调试器突出显示 Fruits = ThisWorkbook.Worksheets("Inventory").Range("Fruit") 行。

当我 运行 与 Quantity 几乎相同的代码时,它可以工作并在立即 window.

中打印 3, 4, 5
Sub QuantityArray()
  Dim Quantities As Variant
  Dim Quantity As Variant

  Quantities = ThisWorkbook.Worksheets("Inventory").Range("Quantity")

  For Each Quantity In Quantities
    Debug.Print Quantity
  Next
End Sub

起初我认为问题是我无法将范围内的文本存储在数组中,但是当我在代码中指定实际范围而不是命名范围时,它可以工作并打印 Apples、Oranges 和 Bananas。

Sub FruitArray()
  Dim Fruits As Variant
  Dim Fruit As Variant

  Fruits = ThisWorkbook.Worksheets("Inventory").Range("B3:B5")

  For Each Fruit In Fruits
    Debug.Print Fruit
  Next
End Sub

我是否缺少能够将基于文本的命名范围值存储在数组中的东西?

谢谢

如评论中所述:首先检查命名范围是否确实存在。

关于使用命名范围的更多一般观察:

对于Variant(我在想数组)

Fruits = ThisWorkbook.Worksheets("Inventory").Range("Fruit").Value

记住从 sheet 读入的范围是二维的,而不是一个。然后你会从LBound循环到UBound。

示例:

Sub test()
    Dim Fruits()
    Fruits = ThisWorkbook.Worksheets("Inventory").Range("Fruit").Value
    Dim i As Long, j As Long
    For i = LBound(Fruits, 1) To UBound(Fruits, 1)
        For j = LBound(Fruits, 2) To UBound(Fruits, 2)
            Debug.Print Fruits(i, j)
        Next j
    Next i
End Sub

对于Range对象:

如果您想实际使用 Range 对象以便可以使用 For Each Loop,那么您需要以下内容。

Option Explicit
Public Sub FruitArray()
  Dim Fruits As Range, Fruit As Range
  Set Fruits = ThisWorkbook.Worksheets("Inventory").Range("Fruit")

  For Each Fruit In Fruits
    Debug.Print Fruit '<== This takes advantage of default member .Value
  Next
End Sub

当我没有定义命名范围时,我可以重现错误:Fruit。 (检查拼写)

  1. 转到:公式选项卡

  2. 打开:名称管理器

  3. 确保:"Fruit" 是一个命名范围。

数量代码可能有效,因为命名范围已定义。

问题是动态命名范围公式确定范围使用 COUNT 函数的时间长度,这不适用于文本,因此它作为错误返回,而 VBA 不能'处理。将动态命名范围公式更改为使用 COUNTA 函数后,它能够读取范围并将其存储在数组中,问题得到解决。