The following code gives me an error 1004. (Note that iElements and iSortOrder() is well defined earlier in the code, and CopyHeader is a subroutine)
Dim page As Long
page = 0
For i = 0 To iElements
' Every five elements is a new page. Every new page, copy the header and update current page count.
If ((i Mod 5) - 1) = 0 Then
CopyHeader ((page * 34) + 1)
page = page + 1
End If
For m = 1 To 16
For n = 0 To 7
Sheet2.Cells((page * 4) + (i * 7) + n, m) = Sheet1.Cells((5 + (iSortOrder(i) * 9) + n), m)
Next n
Next m
Next i
If I change the single line within the nested loops to:
Sheet2.Cells((4) + (i * 7) + n, m) = Sheet1.Cells((5 + (iSortOrder(i) * 9) + n), m)
That is, I remove the reference to page in this line only, the code executes just fine.
This is baffling me. Why would referencing my "page" variable in this line not work? I thought it might be a scope issue-- like VBA doesn't allow variables defined outside of a for loop to be used in a for loop-- but "page" is utilized perfectly well earlier in the loop. So what's wrong?
In case it's not clear, the purpose of the code is to copy blocks of cells from sheet1 to sheet2 in a different order, stripping out some blank lines in the process (9 rows going down to 7 rows). Sheet1 has a single header at the beginning (the "5+"), Sheet2 needs a header on every page (the "(page*4)+").