This macro is intended to get a range from one sheet and put it on a freshly created sheet, then get the next range and copy to another new sheet. It works correctly first time round, but on the second time at Select it gives a 1004 application- or object-definition error.
The debug.print shows that the row numbers are as expected in the second run.
Can anyone suggest a fix?
The debug.print shows that the row numbers are as expected in the second run.
Can anyone suggest a fix?
Code:
Sub ProcessStudies()
Dim firstrow As Long
Dim lastrow As Long
'requires UniqueItems function be placed in Modules
Set wbToAddSheetsTo = ActiveWorkbook
Dim rng As Range
Debug.Print "set rng"
Set rng = Sheet2.Range("H2:H1000")
'Set Studies = Range("H2:H" & lastRow & "")
Set Studies = Sheet2.Range("H2:H1000")
arrStudies = UniqueItems(Studies, False)
Dim i As Integer
For i = LBound(arrStudies) To UBound(arrStudies)
Debug.Print "starting " & arrStudies(i)
With wbToAddSheetsTo
firstrow = findValues("first", "" & arrStudies(i) & "", rng)
Debug.Print "firstrow " & firstrow
lastrow = findValues("last", "" & arrStudies(i) & "", rng)
Debug.Print "lastrow " & lastrow
Sheet2.Range("A" & firstrow & ":AH" & lastrow & "").Select
Debug.Print "copy"; ActiveSheet.Name
Selection.Copy
Debug.Print "add new sheet"
.Sheets.Add After:=.Sheets(.Sheets.Count)
Debug.Print "name as " & arrStudies(i)
ActiveSheet.Name = arrStudies(i)
Debug.Print "paste " & arrStudies(i)
ActiveSheet.Paste
Debug.Print "named new sheet as " & arrStudies(i)
End With
Next i
End Sub