Is there any easy/short way to get the worksheet object of the new sheet you get when you copy a worksheet?
ActiveWorkbook.Sheets("Sheet1").Copy after:=someSheet
It turns out that the .Copy method returns a Boolean instead of a worksheet object. Otherwise, I could have done:
set newSheet = ActiveWorkbook.Sheets("Sheet1").Copy after:=someSheet
So, I wrote some 25 lines of code to get the object. List all sheets before the copy, list all sheets after, and figure out which one is in the second list only.
I am looking for a more elegant, shorter solution.
Copy all the data on the sheet by pressing CTRL+C. Open the workbook in which you want to paste the data, then click the + in the status bar to add a new blank worksheet. Click the first cell in the new worksheet, then press CTRL+V to paste the data into that worksheet.
Dim sht With ActiveWorkbook .Sheets("Sheet1").Copy After:= .Sheets("Sheet2") Set sht = .Sheets(.Sheets("Sheet2").Index + 1) End With
I believe I have finally nailed this issue - it's been driving me nuts, also! It really would have been nice if MS made Copy return a sheet object, same as the Add method...
The thing is, the index which VBA allocates a newly copied sheet is actually not determined... as others have noted, it very much depends on hidden sheets. In fact, I think the expression Sheets(n) is actually interpreted as "the nth visible sheet". So unless you write a loop testing every sheet's visible property, using this in code is fraught with danger, unless the workbook is protected so users cannot mess with sheets visible property. Too hard...
My solution to this dilemma is:
Here's my code - which now seems to be bullet-proof...
Dim sh as worksheet Dim last_is_visible as boolean With ActiveWorkbook last_is_visible = .Sheets(.Sheets.Count).Visible .Sheets(Sheets.Count).Visible = True .Sheets("Template").Copy After:=.Sheets(Sheets.Count) Set sh=.Sheets(Sheets.Count) if not last_is_visible then .Sheets(Sheets.Count-1).Visible = False sh.Move After:=.Sheets("OtherSheet") End With
In my case, I had something like this (H indicating a hidden sheet)
1... 2... 3(H)... 4(H)... 5(H)... 6... 7... 8(H)... 9(H)
.Copy After:=.Sheets(2) actually creates a new sheet BEFORE the next VISIBLE sheet - ie, it became the new index 6. NOT at index 3, as you might expect.
Hope that helps ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With