Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

Tags:

excel

vba

I want to copy a sheet and add it to the end of all current sheets (regardless of whether the sheets are hidden).

Sheets(1).Copy After:=Sheets(Sheets.Count) Sheets(Sheets.Count).name = "copied sheet!" 

This works fine, except, when there are hidden sheets, the new sheet is only inserted after the last visible worksheet, so the name command renames the wrong sheet.

I have tried variations of the following to get a reference to the newly copied WorkSheet but none were successful and/or valid code.

Dim test As Worksheet Set test = Sheets(1).Copy(After:=Sheets(Sheets.Count)) test.Name = "copied sheet!" 
like image 391
enderland Avatar asked Aug 16 '12 15:08

enderland


People also ask

How do I move a worksheet to the end of a workbook in VBA?

VBA code: move active sheet to front of current workbookAfter pasting the code, press the F5 key to run the code. Then the active sheet will be moved to end or front of current workbook immediately.

How do you copy a sheet to the end?

On the Edit menu, click Sheet > Move or Copy Sheet. On the To book menu, click the workbook that you want to copy the sheet to. Tip: To create a new workbook that contains the moved sheet, click new book. In the Before sheet box, click the sheet that you want to insert the copied sheet before, or click move to end.

How do you copy a worksheet and place it at the end of the workbook?

Shift to the worksheet you want to copy to end of workbook, right click the sheet tab, and then click Move or Copy from the context menu. See screenshot: 2. In the Move or Copy dialog box, select (move to end) in the Before sheet box, and check the Create a copy box, then click the OK button.


2 Answers

Try this

Sub Sample()     Dim test As Worksheet     Sheets(1).Copy After:=Sheets(Sheets.Count)     Set test = ActiveSheet     test.Name = "copied sheet!" End Sub 

Looking back at this, a better approach would be

Set test = Sheets(Sheets.Count) 

As correctly mentioned in the comments below, there are lot of things that needs to be considered when copying and renaming a sheet. Would recommend checking the other answers as well.

like image 189
Siddharth Rout Avatar answered Sep 21 '22 01:09

Siddharth Rout


Make the source sheet visible before copying. Then copy the sheet so that the copy also stays visible. The copy will then be the active sheet. If you want, hide the source sheet again.

like image 35
sidnc86 Avatar answered Sep 23 '22 01:09

sidnc86