Runscript错误“ 9”下标超出范围

时间:2018-08-31 11:09:23

标签: arrays excel vba loops

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

我一直遇到运行时错误,但我无法确定代码寻找的值会不断跳动。

错误似乎位于此行:

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

2 个答案:

答案 0 :(得分:2)

假设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 ExplicitOption Base 1放在模块工作表的顶部,然后将x = x + 1移到myArray(x) = cell.Value上方。

答案 1 :(得分:1)

您的数组基于0,但是您正在做0 to .Cell.Count,因此请留空位置,导致错误。对.Cells.Count -1

执行
ReDim myArray(ListRange.Cells.Count-1)

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

的语法
ActiveSheet("Sheet4")

也许

Worksheets("Sheet4")