简体   繁体   中英

Subscript out of range within Do-Loop

I have the following partial code and my for loop breaks ONLY on the 35th tab when I try to activate. The code runs correctly for sheets 6-33. I deleted sheet 34 so I'm thinking it might be because it "jumps" to sheet 35. However, when I debug and place the cursor over endTab I see it contains the value 35. The activate for some reason doesn't work only on this sheet and breaks. Any thoughts?

Dim lastRow As Long
Dim startRow As Long
Dim currentRow As Long
Dim endTab As Integer

Sheets(4).activate

lastRow = Cells(Rows.Count, 2).End(xlUp).Row
startRow = 2

Range("A2:AB" & lastRow).Sort key1:=Range("AB2:AB" & lastRow), _
    order1:=xlAscending, Header:=xlNo

For i = startRow To lastRow
    Sheets(4).activate
    endTab = Range("AB" & startRow + i - 2)

    Range("A" & startRow + i - 2 & ":" & "AB" & startRow + i - 2).Copy
    Worksheets(endTab).activate
    Columns("A").Find("", Cells(Rows.Count, "A")).PasteSpecial xlPasteValues
Next

From comments:

Sheet code names are created when the sheet is first created - they do not adjust to match the order of the sheets in the workbook. Your code is addressing "the 35th sheet" (counting your sheet tabs from left to right) which is not the necessarily the sheet with the codename of "Sheet35"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM