【问题标题】:Runscript Error '9' Subscript out of rangeRunscript 错误“9”下标超出范围
【发布时间】:2019-02-06 09:52:57
【问题描述】:

我一直在尝试使用循环和数组来解决问题,并将下面的示例放在一起,该示例从工作表上的表中获取工作表名称并将它们存储在数组中,另一个循环从中运行以在单元格中添加值这些命名电子表格中的 A1 基于活动表上的单元格 D1 中的值。

我不断收到运行时错误,但我无法确定代码正在查找的值是什么,并且一直跳闸。

错误似乎位于这一行:

Sheets(myArray(x)).Range("A1").Value = EntryValue

非常感谢您对我未正确完成的事情的任何帮助。

谢谢。

代码如下:

Sub WorksheetListLoop()

    Dim myArray() As Variant
    Dim EntryValue As String
    Dim ListRange As Range
    Dim cell As Range
    Dim x As Long

    'Set the values to go into range
    Set ListRange = ActiveSheet.ListObjects("tblArrayList").DataBodyRange

    'Resize array prior to loading data
    ReDim myArray(ListRange.Cells.Count)

    'Loop through each cell in range and store sheetname in array
    For Each cell In ListRange.Cells
        myArray(x) = cell.Value
        x = x + 1
    Next cell

    'Use the value in this cell to put into the sheets in the array
    EntryValue = ActiveSheet.Range("D1").Value

    'Loop through list and add value to cell
    For x = LBound(myArray) To UBound(myArray)
        Sheets(myArray(x)).Range("A1").Value = EntryValue
    Next x

End Sub

【问题讨论】:

  • 这是错误的 ActiveSheet("Sheet4") 你是说 Activesheet 还是 Sheet4?
  • 尝试通过放置 on error 子句并在错误子句中放置断点来捕获错误。使用 resume 命令,光标将回到原来的行。

标签: arrays excel vba loops


【解决方案1】:

假设 ListRange.Cells.Count 是 9。默认情况下,数组是从零开始的,而不是从一开始的。

ReDim myArray(ListRange.Cells.Count) 重新调整为 0 到 9,一共 10 个数组元素。

以下代码将 myArray(0) 填充到 myArray(8)。

For Each cell In ListRange.Cells
    myArray(x) = cell.Value
    x = x + 1
Next cell

myArray(9) 为空。

此代码循环遍历每个元素,包括为空的元素。

For x = LBound(myArray) To UBound(myArray)
    Sheets(myArray(x)).Range("A1").Value = EntryValue
Next x

在最后一次迭代中,当 x 等于 UBound(myArray) 时,您正试图引用一个空数组元素。

最简单的解决方案:将Option Base 1Option Explicit 放在模块表的顶部,然后将x = x + 1 移动到myArray(x) = cell.Value 上方。

【讨论】:

  • 非常感谢以上内容。作为 VBA 的新手,我非常感谢您的帮助。
【解决方案2】:

您的数组基于 0,但您正在执行 0 to .Cell.Count,因此有一个空位置会导致错误。做.Cells.Count -1

ReDim myArray(ListRange.Cells.Count-1)

另外,使用显式工作表引用而不是 Activesheet 并更正

的语法
ActiveSheet("Sheet4")

也许,

Worksheets("Sheet4")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2015-01-01
    • 2019-12-15
    • 2015-05-08
    • 1970-01-01
    相关资源
    最近更新 更多