程序错误下标超出范围...尝试错误恢复

时间:2017-07-13 14:52:40

标签: excel vba excel-vba

我遇到了下划线超出范围的问题:

datasheet = wbook.Sheets("Month and Year")

我曾尝试使用On Error Resume,但我可能做错了。

此代码假设建立月份和年份,以便稍后我可以在创建新工作表时使用它并参考前一个名称类似的“预测 ”。之后,它会查看3列以验证它是要复制和粘贴的行,然后在相应的工作表上建立它。

Sub repeatingrows()

Dim wbook As Workbook
Set wbook = Application.ActiveWorkbook

'CHECKS THE MONTH TO INCREASE THE YEAR
Dim datasheet As Worksheet
datasheet = wbook.Sheets("Month and Year")

Dim m As Integer
Dim y As Integer
Dim t As Integer

For t = 2 To 13
    For m = 1 To 13
        If m = 13 Then
            y = y + 1
            m = 1
        End If
    Next m
    m = .Cells(t, 1)
    .Cells(t, 1) = .Cells(t, 2)
Next t

'MAKE NEW SHEET AND RENAME IT

Dim oldsheet As Worksheet
Dim newsheet As Worksheet
Set oldsheet = Application.ActiveSheet

oldsheet = Sheets("Forecast " & m & " " & y)
newsheet = Sheets("Forecast " & (m + 1) & " " & y)

Sheets.Add.Name = "Forecast " & (m + 1) & " " & y



'CHECK IF the 3 columns ARE SIMILAIR TO PREVIOUS PAGE

Dim rrow As Integer

For rrow = 3 To 500
    If Sheets(3).Cell(rrow, 2) = Sheets(2).Cell(rrow, 2) Then
        If Sheets(3).Cell(rrow, 5) = Sheets(2).Cell(rrow, 5) Then
            If Sheets(3).Cell(rrow, 6) = Sheets(2).Cell(rrow, 6) Then
                With newsheet
                    oldsheet.Range(oldsheet.Cells(rrow, 16), oldsheet.Cells(rrow, 19)).Copy
                    .Range(.Cells(b, a), .Cells(99, 51)).PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd
                End With '^COPY AND PASTES THE ROW
            Else
            End If
        Else
        End If
    Else
    End If
Next rrow

End Sub

1 个答案:

答案 0 :(得分:2)

尝试:

Set datasheet = wbook.Sheets("Month and Year")

并检查工作表名称的拼写,并检查工作表是否存在于正确的工作簿中。
并且不要使用 .Cells()强>使用

(可能还有其他错误)