不明白错误91的原因 - 对vba新

时间:2017-06-30 16:24:21

标签: excel vba excel-vba

我正在尝试添加6到80行的单元格,从表格7到Sheet.count的4到23列,并将附加值转储到表格5中。这是我到目前为止所做的帮助另一个SO成员。我无法弄清楚错误91的原因。

错误在此行:ar(i, j) = ar(i, j) + ws.Cells(i, j)

Sub Sample()
    Dim ws As Worksheet, wsSummation As Worksheet
    Dim startRow As Long, StartCol As Long
    Dim endRow As Long, endCol As Long
    Dim i As Long, j As Long
    Dim ar(6 To 80, 4 To 23) As Variant
    Dim myTotal As Variant
    Dim x As Long
    x = 7

    '~~> Start row and start column
    startRow = 6: StartCol = 4
    endRow = 6: endCol = 4
    'Set myTotal = Sheets.Count 'total sheet count

    '~~> Summary sheet
    'Set wsSummation = Sheet5

    '~~> Looping through each worksheet from Summation to end
    For x = 7 To ThisWorkbook.Worksheets.Count
        '~~> Check if it is not the summary sheet
        'If ws.Name <> wsSummation.Name Then
            '~~> Loop through the row and columns and
            '~~> Store it in an array
            For i = startRow To endRow
                For j = StartCol To endCol
                  ar(i, j) = ar(i, j) + ws.Cells(i, j)
                Next j
            Next i
        'End If
    Next x

    '~~> Write array to summary sheet
    wsSummation.Range("D6").Resize(UBound(ar), UBound(ar)).Value = ar
End Sub

1 个答案:

答案 0 :(得分:2)

我会写几行来帮助你理解@Mat's Mug试图解释的内容。

您正在遍历工作簿的工作表,但是您没有将ws对象设置为您尝试循环的工作表。因此,之后,您正在接收此行ar(i, j) = ar(i, j) + ws.Cells(i, j),因为ws从未正确设置,因此您收到错误。

尝试下面的 代码 循环:

'~~> Looping through each worksheet from Summation to end
For x = 7 To ThisWorkbook.Worksheets.Count
    ' ==== YOU NEED to SET the WORKSHEET OBJECT FIRST, BEFORE YOU USE IT
    '~~> Check if it is not the summary sheet
    Set ws = ThisWorkbook.Worksheets(x)
    With ws ' have a with statement to simplify your nested code
        'If ws.Name <> wsSummation.Name Then
        '~~> Loop through the row and columns and
        '~~> Store it in an array
        For i = startRow To endRow
            For j = StartCol To endCol
                ar(i, j) = ar(i, j) + .Cells(i, j)
            Next j
        Next i
        'End If
    End With
Next x