views:

221

answers:

1

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

+1  A: 
Steve Homer
Of course, it was right in front of me: How to capture worksheet being added through Copy/Paste in Excel VBA - also pointed this out. yet I did not think about doing it that way. What you suggest is what I believe to be the best way. Thanks a lot for this.
Vincent