Excel – Get Handle on last worksheet copied by Worksheet.Copy

excelexcel-2003vba

I'm trying to get a handle to the worksheet that was created by a copy operation. following code used to work:

Dim wsTempl As Worksheet, pageCount as Long
Set wsTempl = Sheets("Template")
For pageCount = 1 To 5
   wsTempl.Copy After:=Sheets(Sheets.Count)
   Set ws = Sheets(Sheets.Count)
   ws.Name = "p" & pageCount 
Next

But stopped when adding VeryHidden worksheets to the workbook. now my Sheets(Sheets.Count) is getting the VeryHidden sheet instead of the sheet I added last.

Of course I could use

Set ws = Sheets(wsTempl.Name & " (2)")
ws.Name = "p" & pageCount

But that seems so ugly, is this really the only way? Can somebody think of another way?

to replicate the issue:

  1. Open a New workbook, Name the first Sheet 'Template' & delete the other sheets
  2. alt-f11 – insert code module & paste the above code
  3. F5 should show you that it works.
  4. insert a worksheet, using the worksheet tabs drag it to the end of collection
  5. set it to VeryHidden in VBA IDE
  6. F5 again, the first code listing should fail

Reason seems to be that the Copy After:= does not copy after VeryHidden Sheets, thus the part of the code to rename the sheet always renames the VeryHidden Sheet

Best Answer

The Copy method of a worksheet makes the newly created sheet active so you should be able to do this.


Dim wsTempl As Worksheet, i as int
Set wsTempl = Sheets("Template")
For i = 1 To 5
   wsTempl.Copy After:=Sheets(Sheets.Count)
   Set ws = ThisWorkbook.ActiveSheet
   ws.Name = "p" & pageCount 
Next

Related Topic