When I add the sheet, the “range” becomes invalid… I’m not sure why this is happening.
I’m wanting to loop through a data set, and when a column value changes, create a new sheet and paste the values to that point in the new sheet. Right now with the code as it is it will do this once, but after the new sheet is created the range is all messed up.
<code> For i = 2 To lastrow
If ws.Cells(i, 6) <> ws.Cells(i + 1, 6) Then
' add a new sheet then copy and paste to the new sheet
'Set pastesheet = Sheets.Add
ws.Range(Cells(1, 1), Cells(i, 20)).Copy
Set pastesheet = Sheets.Add
pastesheet.Range("A1").PasteSpecial xlPasteValues
ws.Application.CutCopyMode = False
pastesheet.Application.CutCopyMode = False
End If
Next
</code>
<code> For i = 2 To lastrow
If ws.Cells(i, 6) <> ws.Cells(i + 1, 6) Then
' add a new sheet then copy and paste to the new sheet
'Set pastesheet = Sheets.Add
ws.Range(Cells(1, 1), Cells(i, 20)).Copy
Set pastesheet = Sheets.Add
pastesheet.Range("A1").PasteSpecial xlPasteValues
ws.Application.CutCopyMode = False
pastesheet.Application.CutCopyMode = False
End If
Next
</code>
For i = 2 To lastrow
If ws.Cells(i, 6) <> ws.Cells(i + 1, 6) Then
' add a new sheet then copy and paste to the new sheet
'Set pastesheet = Sheets.Add
ws.Range(Cells(1, 1), Cells(i, 20)).Copy
Set pastesheet = Sheets.Add
pastesheet.Range("A1").PasteSpecial xlPasteValues
ws.Application.CutCopyMode = False
pastesheet.Application.CutCopyMode = False
End If
Next
Right now with the code as it is it will do this once, but after the new sheet is created the range is all messed up.
4