Copy a sheet from excel with vba

In this Article

  • Copy Worksheet to New Workbook
    • Copy ActiveSheet to New Workbook
  • Copy Multiple Sheets to New Workbook
  • Copy Sheet Within Same Workbook
    • Copy Sheet Before Another Sheet
    • Copy Sheet Before First Sheet
    • Copy Sheet After Last Sheet
  • Move Sheet
  • Copy and Name Sheet
    • Copy and Name Sheet Based on Cell Value
  • Copy Worksheet to Another Workbook
  • Copy Worksheet to a Closed Workbook
  • Copy Sheet from Another Workbook Without Opening it
  • Duplicate Excel Sheet Multiple times

This tutorial will cover how to copy a Sheet or Worksheet using VBA.

Copy Worksheet to New Workbook

To copy a Worksheet to a new Workbook:

Sheets("Sheet1").Copy

Copy ActiveSheet to New Workbook

To copy the ActiveSheet to a new Workbook:

ActiveSheet.Copy

Copy Multiple Sheets to New Workbook

To copy multiple Sheets to a new workbook:

ActiveWindow.SelectedSheets.Copy

Copy Sheet Within Same Workbook

We started off by showing you the most simple copy Sheets example: copying Sheet(s) to a new Workbook.  These examples below will show you how to copy a Sheet within the same Workbook. When copying a Sheet within a Worbook, you must specify a location.  To specify a location, you will tell VBA to move the Worksheet BEFORE or AFTER another Worksheet.

Copy Sheet Before Another Sheet

Here we will specify to copy and paste the Sheet before Sheet2

Sheets("Sheet1").Copy Before:=Sheets("Sheet2")

Copy Sheet Before First Sheet

Instead of specifying the Sheet name, you can also specify the Sheet position. Here we are copying and pasting a Sheet before the first Sheet in the Workbook.

Sheets("Sheet1").Copy Before:=Sheets(1)

The newly created Sheet will now be the first Sheet in the Workbook.
vba copy sheet before first sheet

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Copy Sheet After Last Sheet

Use the After property to tell VBA to paste the Sheet AFTER another sheet. Here we will copy and paste a Sheet after the last Sheet in the Workbook:

Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)

Notice that we used Sheets.Count to count the number of Sheets in the Workbook.

vba copy after last sheet

Move Sheet

You can also move a Sheet within a Workbook using similar syntax. This code will move Sheet1 to the end of the Workbook:

Sheets("Sheet1").Move After:=Sheets(Sheets.Count)

Copy and Name Sheet

After copying and pasting a Sheet, the newly created sheet becomes the ActiveSheet. So to rename our new sheet, simply use ActiveSheet.Name:

Sub CopySheetRename1()

Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "LastSheet"

End Sub

If the Sheet name already exists, the above code will generate an error.  Instead we can use “On Error Resume Next” to tell VBA to ignore naming the Sheet and proceed with the rest of the procedure:

Sub CopySheetRename2()

    Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = "LastSheet"
    On Error GoTo 0

End Sub

Or use our RangeExists Function to test if the Sheet name already exists before attempting to copy the sheet:

Sub CopySheetRename3()

    If RangeExists("LastSheet") Then
        MsgBox "Sheet already exists."
    Else
        Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
        ActiveSheet.Name = "LastSheet"
    End If

End Sub

Function RangeExists(WhatSheet As String, Optional ByVal WhatRange As String = "A1") As Boolean
    Dim test As Range
    On Error Resume Next
    Set test = ActiveWorkbook.Sheets(WhatSheet).Range(WhatRange)
    RangeExists = Err.Number = 0
    On Error GoTo 0
End Function

VBA Programming | Code Generator does work for you!

Copy and Name Sheet Based on Cell Value

You might also want to copy and name a Sheet based on a Cell Value.  This code will name the Worksheet based on the Cell value in A1

Sub CopySheetRenameFromCell()

    Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = Range("A1").Value
    On Error GoTo 0

End Sub

Copy Worksheet to Another Workbook

So far we’ve worked with copying Sheets within a Workbook. Now we will cover examples to copy and paste Sheets to other Workbooks. This code will copy a Sheet to the beginning of another workbook:

Sheets("Sheet1").Copy Before:=Workbooks("Example.xlsm").Sheets(1)

This will copy a Worksheet to the end of another Workbook.

Sheets("Sheet1").Copy After:=Workbooks("Example.xlsm").Sheets(Workbooks("Example.xlsm").Sheets.Count)

Notice we replaced 1 with Workbooks(“Example.xlsm”).Sheets.Count to get the last Worksheet.

Copy Worksheet to a Closed Workbook

You might also want to copy a Worksheet to a Workbook that is closed.  This code will open a closed Workbook so that you can copy a Sheet into it.

Sub CopySheetToClosedWB()
Application.ScreenUpdating = False

    Set closedBook = Workbooks.Open("D:Dropboxexcelarticlesexample.xlsm")
    Sheets("Sheet1").Copy Before:=closedBook.Sheets(1)
    closedBook.Close SaveChanges:=True

Application.ScreenUpdating = True
End Sub

Copy Sheet from Another Workbook Without Opening it

Conversely, this code will copy a Worksheet FROM a closed Workbook without you needing to manually open the workbook.

Sub CopySheetFromClosedWB()
Application.ScreenUpdating = False

    Set closedBook = Workbooks.Open("D:Dropboxexcelarticlesexample.xlsm")
    closedBook.Sheets("Sheet1").Copy Before:=ThisWorkbook.Sheets(1)
    closedBook.Close SaveChanges:=False

Application.ScreenUpdating = True
End Sub

Notice that in both these examples we disabled ScreenUpdating so the process runs in the background.

Duplicate Excel Sheet Multiple times

You can also duplicate an Excel Sheet multiple times by using a Loop.

Sub CopySheetMultipleTimes()
Dim n As Integer
Dim i As Integer
On Error Resume Next

    n = InputBox("How many copies do you want to make?")

    If n > 0 Then
        For i = 1 To n
            ActiveSheet.Copy After:=ActiveWorkbook.Sheets(Worksheets.Count)
        Next
    End If

End Sub

vba duplicate sheet

So, what I want to do, generally, is make a copy of a workbook. However, the source workbook is running my macros, and I want it to make an identical copy of itself, but without the macros. I feel like there should be a simple way to do this with VBA, but have yet to find it. I am considering copying the sheets one by one to the new workbook, which I will create. How would I do this? Is there a better way?

Martijn Pieters's user avatar

asked Jul 28, 2011 at 18:34

Brian's user avatar

1

I would like to slightly rewrite keytarhero’s response:

Sub CopyWorkbook()

Dim sh as Worksheet,  wb as workbook

Set wb = workbooks("Target workbook")
For Each sh in workbooks("source workbook").Worksheets
   sh.Copy After:=wb.Sheets(wb.sheets.count) 
Next sh

End Sub

Edit: You can also build an array of sheet names and copy that at once.

Workbooks("source workbook").Worksheets(Array("sheet1","sheet2")).Copy _
         After:=wb.Sheets(wb.sheets.count)

Note: copying a sheet from an XLS? to an XLS will result into an error. The opposite works fine (XLS to XLSX)

answered Jul 28, 2011 at 21:05

iDevlop's user avatar

iDevlopiDevlop

24.6k11 gold badges89 silver badges147 bronze badges

3

Someone over at Ozgrid answered a similar question. Basically, you just copy each sheet one at a time from Workbook1 to Workbook2.

Sub CopyWorkbook()

    Dim currentSheet as Worksheet
    Dim sheetIndex as Integer
    sheetIndex = 1

    For Each currentSheet in Worksheets

        Windows("SOURCE WORKBOOK").Activate 
        currentSheet.Select
        currentSheet.Copy Before:=Workbooks("TARGET WORKBOOK").Sheets(sheetIndex) 

        sheetIndex = sheetIndex + 1

    Next currentSheet

End Sub

Disclaimer: I haven’t tried this code out and instead just adopted the linked example to your problem. If nothing else, it should lead you towards your intended solution.

Community's user avatar

answered Jul 28, 2011 at 19:05

Chris Flynn's user avatar

Chris FlynnChris Flynn

9536 silver badges11 bronze badges

2

You could saveAs xlsx. Then you will loose the macros and generate a new workbook with a little less work.

ThisWorkbook.saveas Filename:=NewFileNameWithPath, Format:=xlOpenXMLWorkbook

answered Jul 28, 2011 at 20:55

Brad's user avatar

BradBrad

11.9k4 gold badges44 silver badges70 bronze badges

2

I was able to copy all the sheets in a workbook that had a vba app running, to a new workbook w/o the app macros, with:

ActiveWorkbook.Sheets.Copy

Prashant Kumar's user avatar

answered Feb 28, 2014 at 17:50

George Ziniewicz's user avatar

Assuming all your macros are in modules, maybe this link will help. After copying the workbook, just iterate over each module and delete it

Community's user avatar

answered Jul 28, 2011 at 18:59

raven's user avatar

ravenraven

4376 silver badges17 bronze badges

Try this instead.

Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
    ws.Copy
Next

ZygD's user avatar

ZygD

21k39 gold badges77 silver badges98 bronze badges

answered Jan 17, 2013 at 21:28

Ch3knraz3's user avatar

You can simply write

Worksheets.Copy

in lieu of running a cycle.
By default the worksheet collection is reproduced in a new workbook.

It is proven to function in 2010 version of XL.

iDevlop's user avatar

iDevlop

24.6k11 gold badges89 silver badges147 bronze badges

answered Feb 17, 2015 at 14:25

Hors2force's user avatar

Hors2forceHors2force

1011 silver badge2 bronze badges

    Workbooks.Open Filename:="Path(Ex: C:ReportsClientWiseReport.xls)"ReadOnly:=True


    For Each Sheet In ActiveWorkbook.Sheets

        Sheet.Copy After:=ThisWorkbook.Sheets(1)

    Next Sheet

answered Feb 22, 2013 at 11:39

Sainath J's user avatar

Here is one you might like it uses the Windows FileDialog(msoFileDialogFilePicker) to browse to a closed workbook on your desktop, then copies all of the worksheets to your open workbook:

Sub CopyWorkBookFullv2()
Application.ScreenUpdating = False

Dim ws As Worksheet
Dim x As Integer
Dim closedBook As Workbook
Dim cell As Range
Dim numSheets As Integer
Dim LString As String
Dim LArray() As String
Dim dashpos As Long
Dim FileName As String

numSheets = 0

For Each ws In Application.ActiveWorkbook.Worksheets
    If ws.Name <> "Sheet1" Then
       Sheets.Add.Name = "Sheet1"
   End If
Next

Dim fileExplorer As FileDialog
Set fileExplorer = Application.FileDialog(msoFileDialogFilePicker)
Dim MyString As String

fileExplorer.AllowMultiSelect = False

  With fileExplorer
     If .Show = -1 Then 'Any file is selected
     MyString = .SelectedItems.Item(1)

     Else ' else dialog is cancelled
        MsgBox "You have cancelled the dialogue"
        [filePath] = "" ' when cancelled set blank as file path.
        End If
    End With

    LString = Range("A1").Value
    dashpos = InStr(1, LString, "") + 1
    LArray = Split(LString, "")
    'MsgBox LArray(dashpos - 1)
    FileName = LArray(dashpos)

strFileName = CreateObject("WScript.Shell").specialfolders("Desktop") & "" & FileName

Set closedBook = Workbooks.Open(strFileName)
closedBook.Application.ScreenUpdating = False
numSheets = closedBook.Sheets.Count

        For x = 1 To numSheets
            closedBook.Sheets(x).Copy After:=ThisWorkbook.Sheets(1)
        x = x + 1
                 If x = numSheets Then
                    GoTo 1000
                 End If
Next

1000

closedBook.Application.ScreenUpdating = True
closedBook.Close
Application.ScreenUpdating = True

End Sub

answered Apr 5, 2020 at 22:26

RWB's user avatar

try this one

Sub Get_Data_From_File()

     'Note: In the Regional Project that's coming up we learn how to import data from multiple Excel workbooks
    ' Also see BONUS sub procedure below (Bonus_Get_Data_From_File_InputBox()) that expands on this by inlcuding an input box
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*xls*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
         'copy data from A1 to E20 from first sheet
        OpenBook.Sheets(1).Range("A1:E20").Copy
        ThisWorkbook.Worksheets("SelectFile").Range("A10").PasteSpecial xlPasteValues
        OpenBook.Close False
        
    End If
    Application.ScreenUpdating = True
End Sub

or this one:

Get_Data_From_File_InputBox()

Dim FileToOpen As Variant
Dim OpenBook As Workbook
Dim ShName As String
Dim Sh As Worksheet
On Error GoTo Handle:

FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.xls*),*.xls*")
Application.ScreenUpdating = False
Application.DisplayAlerts = False

If FileToOpen <> False Then
    Set OpenBook = Application.Workbooks.Open(FileToOpen)
    ShName = Application.InputBox("Enter the sheet name to copy", "Enter the sheet name to copy")
    For Each Sh In OpenBook.Worksheets
        If UCase(Sh.Name) Like "*" & UCase(ShName) & "*" Then
            ShName = Sh.Name
        End If
    Next Sh

    'copy data from the specified sheet to this workbook - updae range as you see fit
    OpenBook.Sheets(ShName).Range("A1:CF1100").Copy
    ThisWorkbook.ActiveSheet.Range("A10").PasteSpecial xlPasteValues
    OpenBook.Close False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub

Handle:
If Err.Number = 9 Then
MsgBox «The sheet name does not exist. Please check spelling»
Else
MsgBox «An error has occurred.»
End If
OpenBook.Close False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

both work as

answered Jul 6, 2020 at 4:26

Silvio Rivas's user avatar

You can copy and move a sheet in Excel using a VBA code, and in this tutorial, we will learn different ways to do that.

Copy a Sheet within the Same Workbook

If you want to copy a sheet within the same workbook, you can use the following code where you have used the copy method.

Sheets("Sheet5").Copy Before:=Sheets(1)

In this code, sheet1 is the first sheet in the workbook, and when you run this code, it copies the sheet with the name “Sheet5” before the first sheet in the workbook.

And if you want to copy it after the first sheet then the code would be like the following.

Sheets("Sheet5").Copy After:=Sheets(1)

And if you want to copy it after the first sheet, then the code would be like the following.

Sheets("Sheet5").Copy Before:=Sheets("Sheet3")
Sheets("Sheet5").Copy After:=Sheets("Sheet3")

When you run this VBA code, it copies the “Sheet5” before and after the “Sheet3”.

With the following line of code, you can copy a sheet after the last sheet in the workbook. It uses the sheet.count to get the count of the sheets and then uses the number to copy the sheet to the last.

Sheets("myNewSheet").Move After:=Sheets(Sheets.Count)

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Copy a Sheet in the Same Workbook with New Name

And if you want to copy a sheet and then want to rename it instantly, you need to use the name property, just like the following code.

Sheets("Sheet5").Move Before:=Sheets(1)
ActiveSheet.Name = "myNewSheet"

Move a Sheet within the Same Workbook

To move a sheet in the same workbook you need to use the move method as you have in the following code.

Sheets("Sheet5").Move After:=Sheets(1)

This code will move the “Sheet5” before the “Sheet2” as you can see in the above snapshot.

Copy a Sheet to the New Workbook

When you use the copy method without defining any sheet in the current workbook, VBA opens a new workbook and copy that sheet to that workbook.

Sheets("Sheet5").Copy

And to move a sheet to a new workbook.

Sheets("Sheet5").Move

Copy Multiple Sheets to the New Workbook

If you want to add multiple sheets to the new workbook in one go then use code like the following.

Sheets(Array("Sheet2", "Sheet3", "Sheet4", "Sheet5")).Copy

The above code creates an array of the sheets and then copy all of them to a new workbook.

Copy a Sheet to the Another Workbook

If you want to copy a sheet to another workbook that is already open then you can mention the workbook name after or before the argument.

Sheets("Sheet1").Copy Before:=Workbooks("Book1.xlsx").Sheets(1)

The above code copies the Sheet1 from the active workbook and adds to the before the first sheet of the Book1.xlsx that is already open.

 And if you want to move it.

Sheets("Sheet1").Move Before:=Workbooks("Book1.xlsx").Sheets(1)

Copy a Sheet to a Closed Workbook

There’s a way that you can copy a sheet to a workbook that is closed and you don’t need to open it. Look at the below code.

Sub vba_copy_sheet()
Dim mybook As Workbook

Application.ScreenUpdating = False

Set mybook = _
Workbooks.Open _
("C:UsersDellDesktopsamplefile.xlsx")

Workbooks("Book1.xlsx").Sheets("Sheet2").Copy Before:=mybook.Sheets(1)
mybook.Close SaveChanges:=True

Application.ScreenUpdating = True

End Sub

In this code, you have the myBook variable and then a workbook assigned to it. We have turned off the screen updating so that code can perform the task at the backend.

Copy Sheet from Another Workbook without Opening it

In the same way, you can copy and move a sheet from a closed workbook. Look at the below code.

Sub vba_copy_sheet()
Dim mybook As Workbook

Application.ScreenUpdating = False

Set mybook = _
Workbooks.Open _
("C:UsersDellDesktopsamplefile.xlsx")

mybook.Sheets("mySheet").Copy Before:=Workbooks("Book1.xlsx").Sheets(1)
mybook.Close SaveChanges:=True

Application.ScreenUpdating = True
End Sub

More Tutorials on VBA Worksheets

  • Back to VBA Worksheet / VBA Tutorial

This tutorial explains how to copy worksheets using Worksheets.Copy Method in Excel VBA, and demonstrate how to copy worksheet to another workbook.

You may also want to read:

Excel VBA Worksheets.Add Method to add new worksheet

Excel Workbooks Open Method and check if workbook open

Excel VBA Consolidate worksheets into one worksheet

Excel VBA Worksheets.Copy Method is to copy worksheet in a workbook. You can copy worksheets from one workbook to another workbook, and specify to insert after or before specific worksheet.

Syntax of Excel VBA Worksheets.Copy Method

expression .Copy(Before, After)
Name Description
Before Optional. The sheet before which the copied sheet will be placed. You cannot specify Before if you specify After.
After Optional. The sheet after which the copied sheet will be placed. You cannot specify After if you specify Before.

If you don’t specify either Before or After, Microsoft Excel creates a new workbook that contains the copied sheet.

Example 1 – Copy worksheet in the same workbook

The below example copies “Sheet2” to the end of the worksheets, and rename it as “new worksheet”.

Public Sub cpy1()
    Sheets("Sheet2").Copy After:=Sheets(ThisWorkbook.Sheets.Count)
    ActiveSheet.Name = "new worksheet"
End Sub

The below example copies “Sheet2” and move to the first worksheet

Public Sub cpy2()
    Sheets("Sheet2").Copy Before:=Worksheets(1)
    ActiveSheet.Name = "new worksheet"
End Sub

Example 2 – Copy worksheet to another workbook

The below example copies worksheet “wbA ws1” to another workbook “workbook b” after worksheet “wbB ws1”

Public Sub cpywb()
    Workbooks("workbook a.xlsx").Worksheets("wbA ws1").Copy after:=Workbooks("workbook b.xlsx").Worksheets("wbB ws1")
End Sub

Example 3 – Copy worksheets to a new workbook

Sub cpyWS()
   Set Newbook = Workbooks.Add
   ThisWorkbook.Sheets("SheetA").Copy After:=Newbook.Sheets(Newbook.Sheets.Count)
   ThisWorkbook.Sheets("SheetB").Copy After:=Newbook.Sheets(Newbook.Sheets.Count)
End Sub

You may also read my another example to copy each worksheet to new workbook.

Example 4 – Copy worksheet from another closed workbook

This example was originally asked in Microsoft Community.

Question

Hi,

Need help with VBA Code.

I’ve searched and tried a few codes but have been having trouble finding something that works.

What I want to do:

1) I’m in an open and active workbook

2) I want to insert and new sheet at the end of all the sheets in the open workbook

3) The sheet I want to insert is from a closed workbook with several worksheets.

Info, Please use in example code, appreciated.

1) location:   “C:UsersXxxxDocumentsXxxxTarget File.xlsx”

Answer

Public Sub cpy()
     Application.ScreenUpdating = False
     Set fileB = Workbooks.Open("C:UsersXxxxDocumentsXxxxTarget File.xlsx")
     fileB.Sheets("Sheet2").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
     fileB.Close
     Application.ScreenUpdating = True
 End Sub

Outbound References

https://msdn.microsoft.com/en-us/library/office/ff837784.aspx

Skip to content

VBA Copy Worksheet Explained with Examples

  • VBA Copy Worksheet

Copy worksheet in VBA is used to Copy the worksheet from one location to another location in the same workbook or another new workbook or existing workbook. Where Copy is a method of Worksheet object. Please find the more information about Copy Worksheet(s) in the following chapter. Sometimes we may want to Copy worksheet in the active workbook at the beginning of the worksheet or in between worksheets or at the end of worksheet. According to our requirement we can Copy the worksheets using Copy method of Worksheet object in VBA.

In this Topic:

  • VBA Copy Worksheet: Syntax
  • VBA Copy Worksheet: Using Before
  • VBA Copy Worksheet: Using After
  • VBA Copy Worksheet: Before Specified Worksheet
  • VBA Copy Worksheet: To New Workbook
  • VBA Copy Worksheet: To Specific Workbook
  • VBA Copy Worksheet: Instructions

VBA Copy Worksheet

VBA Copy Worksheet: Syntax

Please find the below syntax to Copy Worksheet using VBA.

Sheets(“Worksheet Number”).Copy([Before], [After])

Where
Before: It’s an Optional parameter. The worksheet will be Copied to before the specified worksheet. Then we can’t specify after parameter.
After: It’s an Optional parameter. The worksheet will be Copied to after the specified worksheet. Then we can’t specify after parameter.
Note: If you don’t specify either before or after, Excel will create new workbook that contains the Copied worksheet

VBA Copy Worksheet: Using Before

Please find the below example, It will show you how to Copy the Worksheet to the beginning.

Sub CopySheet_Beginning()
    Worksheets("Sheet3").Copy Before:=Worksheets(1)
End Sub

In the above example we are Copying the Worksheet named ‘Sheet3’ to the beginning of the worksheet. Where ‘1’ represents the Worksheet index number (Nothing but first available sheet in the workbook).

Sub CopySheet_Beginning1()
    ActiveSheet.Copy Before:=Worksheets(1)
End Sub

In the above example we are Copying the active worksheet to the beginning of the worksheet.

VBA Copy Worksheet: Using After

Please find the below example, It will show you how to Copy the Worksheet at the end of the available worksheets.

Sub CopySheet_End()
    Worksheets("Sheet3").Copy After:=Worksheets(Worksheets.Count)
End Sub

In the above example we are copying the Worksheet named ‘Sheet3’ to the end of the worksheet. Where ‘Worksheets.Count’ represents the number of available worksheets in the workbook

Sub CopySheet_End()
    ActiveSheet.Copy After:=Worksheets(Worksheets.Count)
End Sub

In the above example we are Copying the active worksheet to the end of the worksheet.

VBA Copy Worksheet: Before Specified Worksheet

Please find the below example, It will show you how to Copy the Worksheet either before or after the specified worksheet.

Sub CopySheet_Before()
    Worksheets("Sheet2").Copy Before:=Sheets("Sheet5")
End Sub

Please find the above example, we are Copying ‘Sheet2’ to the before ‘Sheet5’.

Sub CopySheet_Before()
    ActiveSheet.Copy Before:=Sheets("Sheet5")
End Sub

In the above example, we are Copying active sheet to the before ‘Sheet5’.

Sub CopySheet_After()
    Worksheets("Sheet2").Copy After:=Sheets("Sheet5")
End Sub

Please find the above example, we are Copying ‘Sheet2’ to the after ‘Sheet5’.

Sub CopySheet_After()
    ActiveSheet.Copy After:=Sheets("Sheet5")
End Sub

In the above example, we are Copying active sheet to the after ‘Sheet5’.

VBA Copy Worksheet: To New Workbook

Please find the below example, It will show you how to Copy the Worksheet named ‘Sheet1’ to new workbook.

Sub CopySheet_NewWorkbook()
    Sheets("Sheet1").Copy
End Sub

Please find the below example, It will Copy the active worksheet to new workbook.

Sub CopySheet_NewWorkbook()
    ActiveSheet.Copy
End Sub

VBA Copy Worksheet: To Specific Workbook

Please find the below example, It will show you how to Copy the Worksheet named ‘Sheet1’ to Specific workbook before ‘Sheet3’.

Sub CopySheet_SpecificWorkbook ()
    Sheets("Sheet1").Copy Before:=Workbooks("YourWorkbookName.xls").Sheets(“Sheet3”)
End Sub

Please find the below example, It will Copy the active worksheet to Specific workbook after ‘Sheet3’.

Sub CopySheet_SpecificWorkbook ()
    ActiveSheet.Copy After:=Workbooks("YourWorkbookName.xls"). Sheets(“Sheet3”)
End Sub

VBA Copy Worksheet Method- Instructions

Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

Step 1: Open an Excel Worksheet
Step 2: Press Alt+F11 to Open VBA Editor
Step 3: Insert a Module from Insert Menu
Step 4: Copy the above code for activating a range and Paste in the code window (VBA Editor)
Step 5: Save the file as macro enabled Worksheet
Step 6: Press ‘F5′ to run it or Keep Pressing ‘F8′ to debug the code line by line and have a look how the Worksheet(s) Copying in the workbook.

Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

  • In this Topic:
  • VBA Copy Worksheet: Syntax
  • VBA Copy Worksheet: Using Before
  • VBA Copy Worksheet: Using After
  • VBA Copy Worksheet: Before Specified Worksheet
  • VBA Copy Worksheet: To New Workbook
  • VBA Copy Worksheet: To Specific Workbook
  • VBA Copy Worksheet Method- Instructions

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

5 Comments

  1. Venkat
    August 29, 2015 at 5:07 PM — Reply

    Dear Mr.P N Rao ! What is the Basic difference b/w a macro and procedure..??

  2. PNRao
    August 30, 2015 at 3:15 AM — Reply

    Hi Venkat,
    A Marco is a set of statements which generally created for completing repetitive simple tasks ( without programming concepts like data types, logical expressions, conditional statements etc.)

    Where as Procedures are written using programming concepts.

    Example: In MS Excel, We can use the Macro recorder to automate simple tasks. Application generates simple statements, where you can’t see any logical statements, etc. But, a programmer writes the procedures using programming concepts, which is more reliable and generalized.

    Hope this clarifies.
    Thanks-PNRao!

  3. shahnas
    November 6, 2015 at 10:27 AM — Reply

    hi,

    how to copy one excel sheet(matser file) in to another excel work book( which contain 31 sheets) by date basis

  4. Saranya
    November 10, 2015 at 7:50 PM — Reply

    I have several sheets in a source workbook and I need to copy each sheets’s data to another workbook which has got the same name as the sheet name in the source workbook. I have workbooks as many as the number of sheets in the source workbook. How to copy the data from sheets to workbooks in sheet2

  5. Chait
    July 1, 2016 at 3:13 PM — Reply

    i have 2 workbooks in a location C:newfolder. I want sheet 1 from wb1, sheet3 from wb2 and place it one after the other in another existing workbook wb3 in the same location when i click a button in wb3. can you help me with a code?

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

Go to Top

Bottom Line: Learn how to use VBA macros to copy & paste data from one Excel workbook to another, including adding data to the bottom of an existing range or replacing data.

Skill Level: Intermediate

Video Tutorial

Watch on YouTube & Subscribe to our Channel

Download the Excel Files

Follow along with the video above using the same Excel files that I use. You can download them by clicking below. Here’s the workbook that I copy data from in my example:

And here’s the workbook that I copy data to.  This is the one that has all the macro code in it:

There are a few ways to copy & paste data with VBA. We are first going to use the Range.Copy method. This allows us to perform the entire action in one line of code.

  Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Copy _
    Workbooks("Reports.xlsm").Worksheets("Data").Range("A2")

The Range.Copy method has an optional Destination parameter that allows us to specify the range we want to paste to.

We reference the source workbook, worksheet, and range that we want to copy from. For the Destination parameter we reference the destination workbook, worksheet, and the beginning cell of the range to paste to.

Copy Data to Another Workbook Using Macros

The Range.Copy method does a regular copy and paste that includes formatting and formulas. If you just want to paste values, there is an example below.

Important Points to Remember

When using this macro to copy data from one workbook to another, keep these points in mind.

  • You must reference the correct file extension in the Workbooks property (see video above for details).
  • Workbooks do not have to be macro enabled for this to work.
  • This code can be stored in a separate workbook, such as your Personal Macro Workbook, if you choose. (Learn how to create a Personal Macro Workbook here.)
  • You do not need to select or activate the workbooks, worksheets, or even ranges first. This is because the code already specifies those details.
  • Both workbooks must be open when using this code. But the process of opening and closing workbooks can be automated with more code:
Sub OpenWorkbook()
'Open a workbook

  'Open method requires full file path to be referenced.
  Workbooks.Open "C:UsersusernameDocumentsNew Data.xlsx"

    'Open method has additional parameters
  'Workbooks.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
  'Help page: https://docs.microsoft.com/en-us/office/vba/api/excel.workbooks.open

End Sub

Sub CloseWorkbook()
'Close a workbook

  Workbooks("New Data.xlsx").Close SaveChanges:=True

    'Close method has additional parameters
  'Workbooks.Close(SaveChanges, Filename, RouteWorkbook)
  'Help page: https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.close

  End Sub

PasteSpecial Method to Paste Values, Formats, etc.

When pasting data into the destination workbook using VBA, you can also use any of the normal Paste Special features.

There is an example macro below. You’ll notice that my example uses the PasteValues type, but you could also use PasteFormulas, PasteFormats, or any of the other PasteSpecial options available. Here is a list of the PasteTypes.

  'Copy range to clipboard
  Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Copy

    'PasteSpecial to paste values, formulas, formats, etc.
  Workbooks("Reports.xlsm").Worksheets("Data").Range("A2").PasteSpecial Paste:=xlPasteValues

To learn more about PasteSpecial options, check out my video series on Copy and Paste with VBA.

Pasting Below the Last Cell

Sometimes the size of your data ranges in the source and destination files will change every time you run the macro. For example, you may have a daily task of adding new entries from an exported sheet to a master list in another workbook.

Copy Data to Another Workbook below existing entries

In that case, you’ll want to add the new entries directly below the last entry on your destination sheet. To do that, you can use the following macro.

Sub Copy_Paste_Below_Last_Cell()
'Find the last used row in both sheets and copy and paste data below existing data.

Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long

  'Set variables for copy and destination sheets
  Set wsCopy = Workbooks("New Data.xlsx").Worksheets("Export 2")
  Set wsDest = Workbooks("Reports.xlsm").Worksheets("All Data")

      '1. Find last used row in the copy range based on data in column A
  lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row

      '2. Find first blank row in the destination range based on data in column A
  'Offset property moves down 1 row
  lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row

  '3. Copy & Paste Data
  wsCopy.Range("A2:D" & lCopyLastRow).Copy _
    wsDest.Range("A" & lDestLastRow)

This code pastes your source data just below the existing destination sheet data.

In addition to finding the last row in a range or sheet, you can find the last column or cell as well. Checkout my post and video on 3 ways to find the last used row or column to learn more.

Clearing the Destination Range Before Pasting

Instead of adding to a list in your destination range, you may prefer to clear the existing range before pasting the new data. You can do that with this macro.

Sub Clear_Existing_Data_Before_Paste()

Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim lCopyLastRow As Long
Dim lDestLastRow As Long

  Set wsCopy = Workbooks("New Data.xlsx").Worksheets("Export 2")
  Set wsDest = Workbooks("Reports.xlsm").Worksheets("All Data")

        '1. Find last used row in the copy range based on data in column A
    lCopyLastRow = wsCopy.Cells(wsCopy.Rows.Count, "A").End(xlUp).Row

          '2. Find first blank row in the destination range based on data in column A
    'Offset property moves down 1 row
    lDestLastRow = wsDest.Cells(wsDest.Rows.Count, "A").End(xlUp).Offset(1).Row

        '3. Clear contents of existing data range
    wsDest.Range("A2:D" & lDestLastRow).ClearContents

    '4. Copy & Paste Data
    wsCopy.Range("A2:D" & lCopyLastRow).Copy _
      wsDest.Range("A2")

End Sub

Running that macro will remove any existing data in the destination range before inserting the data from the source worksheet.

Alternative Code for Copying Data to Your Current Workbook

I wanted to also present to you a slightly different option for your macro. Instead of identifying the destination workbook by name, you can use the ThisWorkbook property. This can be done as long as the macro is stored in the destination (or source) workbook.

By doing this, you avoid having to change the code in the event you change the file name for your destination workbook. Here is the VBA code that uses ThisWorkbook.

  Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Copy _
    ThisWorkbook.Worksheets("Data").Range("A2")

This reminds me that VBA will always assume that the macro you want to run applies to the active workbook if you don’t specify a workbook in each line of code. I talk about that critical assumption and other important points about running VBA code in this video on VBA Assumptions.

Copy Paste Between Sheets in Same Workbook

You can modify any of the examples above to copy & paste between sheets in the same workbook. Just use the same workbook reference for the copy and destination ranges. Here is an example.

  'Copy range to clipboard
  Workbooks("New Data.xlsx").Worksheets("Export").Range("A2:D9").Copy

    'PasteSpecial to paste values, formulas, formats, etc.
  Workbooks("New Data.xlsm").Worksheets("Data").Range("A2").PasteSpecial Paste:=xlPasteValues

You won’t always need to specify the workbook, but it is a good habit to get into. Otherwise, VBA makes assumptions that can get you in trouble.

Conclusion

I hope these tips and macros help save you time when copying data between workbooks. Automating this boring task will help prevent errors and make it easy for others to update your reports.

Please leave a comment below with any questions or suggestions. Thank you! 🙂

Содержание

  1. Метод Sheets.Copy (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Метод Worksheet.Copy (Excel)
  8. Синтаксис
  9. Параметры
  10. Замечания
  11. Пример
  12. Поддержка и обратная связь
  13. Sheets.Copy method (Excel)
  14. Syntax
  15. Parameters
  16. Remarks
  17. Example
  18. Support and feedback
  19. Макрос для копирования листа в Excel c любым количеством копий
  20. Как макросом скопировать листы в Excel
  21. Описание кода макроса для копирования листов Excel
  22. How to duplicate sheet in Excel with VBA
  23. Excel VBA to copy sheet to new workbook
  24. Copy multiple sheets in Excel with VBA
  25. Excel VBA to copy sheet to another workbook
  26. Copy sheet to the beginning of another workbook
  27. Copy sheet to the end of another workbook
  28. Copy sheet to a selected workbook
  29. Excel macro to copy sheet and rename
  30. Excel macro to copy sheet and rename based on cell value
  31. Macro to copy worksheet to a closed workbook
  32. Excel VBA to copy sheet from another workbook without opening
  33. Excel VBA to duplicate sheet multiple times
  34. How to duplicate sheets in Excel with VBA
  35. How to add a macro to your workbook
  36. How to run a macro from our sample workbook
  37. You may also be interested in

Метод Sheets.Copy (Excel)

Копирует лист в другое место в книге.

Синтаксис

expression. Копирование (до, после)

выражение: переменная, представляющая объект Sheets.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Лист, перед которым будет размещен скопированный лист. Невозможно указать параметр Before , если указать After.
After Необязательный Variant Лист, после которого будет размещен скопированный лист. Вы не можете указать After , если укажем значение До.

Замечания

Если не указать значение «До» или «После», Microsoft Excel создает новую книгу, содержащую скопированный лист.

Пример

В этом примере выполняется копирование Sheet1, помещая его после Sheet3.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Метод Worksheet.Copy (Excel)

Копирует лист в другое место в текущей или новой книге.

Синтаксис

expression. Копирование (до, после)

Выражение Переменная, представляющая объект Worksheet .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Before Необязательный Variant Лист, перед которым будет размещен скопированный лист. Невозможно указать параметр Before , если указать After.
After Необязательный Variant Лист, после которого будет размещен скопированный лист. Вы не можете указать After , если укажем значение До.

Замечания

Если не указать значение «До» или «После», Microsoft Excel создает новую книгу, содержащую скопированный объект Worksheet . Только что созданная книга содержит свойство Application.ActiveWorkbook и содержит один лист. На одном листе сохраняются свойства Name и CodeName исходного листа. Если скопированный лист содержал лист кода листа в проекте VBA, он также переносится в новую книгу.

Выбор массива из нескольких листов можно скопировать в новый пустой объект Workbook аналогичным образом.

Источник и назначение должны находиться в одном экземпляре Excel.Application. В противном случае возникает ошибка среды выполнения 1004: не поддерживается такой интерфейс, если использовался что-то подобное Sheet1.Copy objWb.Sheets(1) , или ошибка среды выполнения 1004: сбой метода копирования класса Worksheet, если использовалось что-то подобное ThisWorkbook.Worksheets(«Sheet1»).Copy objWb.Sheets(1) .

Пример

В этом примере выполняется копирование Sheet1, помещая его после Sheet3.

В этом примере сначала файл Sheet1 копируется в новую пустую книгу, а затем сохраняет и закрывает новую книгу.

В этом примере листы Sheet1, Sheet2 и Sheet4 копируются в новую пустую книгу, а затем сохраняются и закрываются.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Sheets.Copy method (Excel)

Copies the sheet to another location in the workbook.

Syntax

expression.Copy (Before, After)

expression A variable that represents a Sheets object.

Parameters

Name Required/Optional Data type Description
Before Optional Variant The sheet before which the copied sheet will be placed. You cannot specify Before if you specify After.
After Optional Variant The sheet after which the copied sheet will be placed. You cannot specify After if you specify Before.

If you don’t specify either Before or After, Microsoft Excel creates a new workbook that contains the copied sheet.

Example

This example copies Sheet1, placing the copy after Sheet3.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Макрос для копирования листа в Excel c любым количеством копий

Возможности макросов в Excel практически неограниченные. В данном примере покажем в пару кликов можно создать любое количество копий листов используя VBA-макрос.

Как макросом скопировать листы в Excel

Допустим необходимо приготовить планы работ для сотрудников вашего отдела. Иметься шаблон таблицы для заполнения документа плана в виде одного рабочего листа Excel:

Но вам необходимо создать 12 планов и соответственно 12 листов. В программе Excel нет встроенного инструмента для многократного создания копий рабочих листов за одну операцию. А копировать и вставлять 12 (а в практике встречаются случаи что и 120) листов вручную, да еще их все нужно переименовать – это потребует много рабочего времени и пользовательских сил. Определенно лучше в таком случае воспользоваться собственным макросом. А чтобы его написать воспользуйтесь VBA-кодом, который будет представлен ниже в данной статье.

Сначала откройте редактор макросов Visual Basic:

Создайте в нем стандартный модуль с помощью опций меню: «Insert»-«Module» и введите в него этот код, который ниже представленный на листинге:

Sub CopyList()
Dim kolvo As Variant
Dim i As Long
Dim list As Worksheet
kolvo = InputBox( «Укажите необходимое количество копий для данного листа» )
If kolvo = «» Then Exit Sub
If IsNumeric(kolvo) Then
kolvo = Fix(kolvo)
Set list = ActiveSheet
For i = 1 To kolvo
list.Copy after:=ActiveSheet
ActiveSheet.Name = list.Name & i
Next
Else
MsgBox «Неправильно указано количество»
End If
End Sub

Теперь если нам нужно скопировать 12 (или любое другое количество) раз листов содержащие шаблон для заполнения плана работы сотрудника, кликните по исходному листу, чтобы сделать его активным и выберите инструмент: «РАЗРАБОТЧИК»-«Код»-«Макросы»-«CopyList»-«Выполнить». Сразу после запуска макроса появиться диалоговое окно, в котором следует указать количество копий листа:

Введите, например, число 12 и нажмите ОК:

Лист с шаблоном плана скопируется 12 раз, а все названия листов будут иметь такое же как название исходного листа только со своим порядковым номером от 1 до12.

Внимание! Если название исходного листа слишком длинное, тогда может возникнуть ошибка в процессе выполнения макроса. Ведь в Excel название листа не может содержать более чем 31 символ. То есть ориентируйтесь так чтобы название исходного листа было меньше чем 27 символов. Так же ошибка может возникнуть если текущая рабочая книга Excel уже содержит листы с таким названием как у копий. Ведь в Excel все листы должны иметь уникальные названия.

Примечание. В новых версиях Excel (начиная от 2010 версии) одна рабочая книга может содержать максимальное количество листов, которое ограничивается лишь размером свободной оперативной памяти системы.

Описание кода макроса для копирования листов Excel

В коде используются 3 переменные:

  1. kolvo – в этой переменной определено какое количество копий будет создано при копировании текущего рабочего листа Excel.
  2. i – счетчик циклов.
  3. list – в этой переменной будет создан экземпляр объекта листа Excel.

В начале макроса вызываем диалоговое окно, в котором пользователь должен указать в поле ввода какое количество копий листов необходимо создать с помощью данного макроса «CopyList». Введенное числовое значение в поле ввода из этого диалогового окна передается в переменную kolvo. Если поле ввода пустое или в диалоговом окне была нажата кнопка отмены «Cancel», тогда дальнейшие инструкции не выполняться и работа макроса прерывается.

В следующей строке кода проверяется: является ли введенное значение в поле ввода – числовым? Если да, тогда на всякий случай удаляются все числа после запятой с помощью функции Fix.

Далее в переменой list создается экземпляр объекта ActiveSheet. После в цикле копируются листы. Количество циклов выполняется ровно столько, сколько пользователь указал в диалоговом окне макроса. В процессе копирования каждый раз изменяется название для новой копии листа. Так как в одной книге не может быть 2 и более листов с одинаковым названием. Уникальные названия для каждой копии создаются за счет присвоения к названию исходного листа число с порядковым номером текущего цикла. При необходимости пользователь может задать свои параметры для присвоения названия копиям листов изменив данную строку кода. Главное придерживаться правила уникальности названий листов.

Примечание. Если нет необходимости настраивать названия для новых листов, тогда данную строку кода можно закомментировать.

‘ActiveSheet.Name = list.Name & i

В таком случае названия для копий Excel будет присваивать сам. Например, для исходного листа с названием «Лист1» копии будут получать названия: «Лист1 (2)», «Лист1 (3)», «Лист1 (4)» и т.д.

В конце кода выводиться сообщение на тот случай если пользователь неправильно указал числовое значение в поле ввода диалогового окна макроса.

Источник

How to duplicate sheet in Excel with VBA

by Svetlana Cheusheva, updated on March 16, 2023

The tutorial provides a collection of macros to duplicate sheets in Excel: copy and rename based on cell value, copy multiple sheets, copy an active worksheet to another file without opening it, and more.

Manually copying sheets in Excel is pretty quick and straightforward. if performed just once or twice. Duplicating multiple sheets multiple times is boring and time consuming. On this page, you will find a handful of useful macros to automate this task.

Excel VBA to copy sheet to new workbook

This simplest one-line macro does exactly what its name suggests — copies the active sheet to a new workbook.

Copy multiple sheets in Excel with VBA

If you’d like to copy several sheets from the active workbook to a new one, select all the worksheets of interest and run this macro:

Excel VBA to copy sheet to another workbook

Depending on where you want to insert the copied sheet, use one of the following macros.

Copy sheet to the beginning of another workbook

This macro copies the active sheet before all other worksheets in the destination file, Book1 in this example. To copy to another file, replace «Book1.xlsx» with the full name of your target workbook.

Copy sheet to the end of another workbook

This piece of code duplicates the active worksheet and places the copy to the end of Book1. Again, please remember to replace «Book1.xlsx» with the name of your destination workbook.

Note. For the macros to work, the target workbook must be saved on your hard drive or network.

Copy sheet to a selected workbook

To be able to copy the current sheet to any open workbook, you can create a UserForm (named UserForm1) with a ListBox control (named ListBox1) and two buttons:

Next, double-click the form and paste the below code in the Code window:

With the UserForm in place, you can use one of the following macros to copy the active sheet to the workbook of your choosing.

Copy sheet to the beginning of the selected workbook:

Copy sheet to the end of the selected workbook:

When run in Excel, the macro will show you a list of all currently opened workbooks. You select the needed one and click OK:

Excel macro to copy sheet and rename

When you copy a sheet in Excel, the replica is given a name in the default format like Sheet1 (2). The following macros can spare you the trouble of changing the default name manually.

This code duplicates the active worksheet, names the copy as «Test Sheet» (you are free to replace it with any other name you like), and places the copied sheet at the end of the current workbook.

To allow the user to specify the name for the copied sheet, use this code:

Upon running, the macro displays the following input box, in which you type the desired name and press OK:

Excel macro to copy sheet and rename based on cell value

In some situations, it may be more convenient to name a copy with a specific cell value, for example, a column header. For this, you simply take the above code and supply the value of the currently selected cell to the input box automatically. As with the previous example, the copy will be placed at the end of the active workbook.

The trickiest part would be to have your users always select the correct cell before running the macro 🙂

Alternatively, you can hardcode the address of the cell by which the copy should be named, cell A1 in the below code. To name the copied worksheet based on another cell, replace A1 with an appropriate cell reference.

Macro to copy worksheet to a closed workbook

This macro copies the active sheet to the end of a closed workbook. The name of another workbook is not specified in the code — the macro will open the standard Windows Explorer window and allow you to choose any destination file:

After you select the file and click Open, the macro will copy the active sheet and close the target workbook automatically.

Excel VBA to copy sheet from another workbook without opening

This macro enables you to copy a worksheet from another Excel file without opening it. The copied sheet will be inserted at the end of the current workbook.

Just remember to make a couple of replacements in the code:

  • C:UsersXXXDocumentsTarget_Book.xlsx should be changed to the actual path and name of the workbook from which you want to copy a sheet.
  • Sheet1 should be replaced with the name of the sheet you want to copy.

Excel VBA to duplicate sheet multiple times

Sometimes, you may need to duplicate the same sheet more than once, for instance to test different formulas on the same data set. This can be easily done with the following macro.

Open the original sheet, run the macro, specify how many copies of the active sheet you want to make, and click OK:

How to duplicate sheets in Excel with VBA

To copy a sheet in Excel with one of the above macros, you can either insert the VBA code into your own book or run a macro from our sample workbook.

How to add a macro to your workbook

To insert the code in your workbook, perform these steps:

  1. Open the worksheet you want to copy.
  2. Press Alt + F11 to open the Visual Basic Editor.
  3. On the left pane, right-click ThisWorkbook, and then click Insert >Module.
  4. Paste the code in the Code window.
  5. Press F5 to run the macro.

For the detailed step-by-step instructions, please see How to insert VBA code in Excel.

How to run a macro from our sample workbook

Alternatively, you can download our sample workbook to Duplicate Excel Sheets and run the code from there.

The sample workbook contains the following macros:

CopySheetToNewWorkbook — copies the current worksheet to a new workbook.

CopySelectedSheets — copies multiple sheets that you select to a new workbook.

CopySheetToBeginningAnotherWorkbook — copies the active sheet to the beginning of another workbook.

CopySheetToEndAnotherWorkbook — copies the active sheet to the end of another Excel file.

CopySheetAndRename — duplicates the current sheet, renames it as specified by the user, and puts the copy after all other sheets in the current workbook.

CopySheetAndRenamePredefined — duplicates the active sheet, gives a hardcoded name to the copy and places it at the end of the current workbook.

CopySheetAndRenameByCell — makes a copy of the active sheet and renames it based on the selected cell value.

CopySheetAndRenameByCell2 — copies the active sheet and renames it based on the hardcoded cell address.

CopySheetToClosedWorkbook — allows you to copy sheet to a closed workbook.

CopySheetFromClosedWorkbook — enables you to copy a sheet from another Excel file without opening it.

DuplicateSheetMultipleTimes — lets you duplicate a sheet in Excel multiple times.

To run the macro in your Excel, just do the following:

  1. Open the downloaded workbook and enable the content if prompted.
  2. Open your own workbook and navigate to the sheet you want to copy.
  3. In your worksheet, press Alt + F8 , select the macro of interest, and click Run.

That’s how you can duplicate a sheet in Excel with VBA. I thank you for reading and hope to see you on our blog next week!

You may also be interested in

Table of contents

I am running the «Excel macro to copy sheet and rename» where it allows the user to save a new name. However, when I create it, it renames the old version then creates a duplicate of the original and puts in for example test (2). I want to keep the original and have the new named sheet at the end of the workbook. Here is my coding:
Sub CopySheetAndRename()
Dim newName As String

On Error Resume Next
newName = InputBox(«Enter the name for the copied worksheet»)

If newName «» Then
Sheets(«Portfolio Plus»).Copy After:=Worksheets(Sheets.Count)
On Error Resume Next
Sheets(«Portfolio Plus»).Name = newName
End If
End Sub

I have a worksheet where I would like to copy two worksheets and rename them. The two worksheets are named by date. How could I amend the macro to name the two new worksheets with the date+1 of the previous worksheets?

I have a template with named ranges in tables that I use to export data from SAS (One range per sheet, 9 sheets). I keep ending up with corrupted files and I was told to copy everything to a new workbook and try again. However, I get an error «You cannot copy or move a group of sheets that contain tables.»
I am very new to VBA, so any advice is appreciated!

Hi!
Convert your tables to a normal Excel range. VBA macros do not work with tables.
The following tutorial should help: Convert Excel table to range and turn data range into table.

I have set up the COPY A WORKSHEET AND RENAME macro but it copies the new worksheet AFTER (to the right of) the source. I want it to copy before..I tried changing the «After» command to «Before» but this did not work. suggestions?

Quiero copiar la hoja T3 y reemplazar con ella las hojas T1 y T2 sin que se disparen errores de Ref! en la hoja Indice

HI
Is there a way to run a macro to copy all comment thread/notes from cells to a new worksheet?
I’ve tried and found VB code but it didnt seem to work, I’m using office 365.
Thanks

Hello.
I am trying to place a shape button on sheets in a workbook so when data is filled for a week. I like copy this sheet say name of workbook is » working on» and sheet name » weekly report» when this page is filed for the week. I want copy this sheet in to closed work book say name is «weekly reports Archive» and place it at end of all sheets and name the sheet i am copying to «weekly report wk 21» after weekly report 20 sheet. All work books and sheets are shared for updates and want to make it more easier for others to update. Would you be able to help. I am new to VBA coding.

I recived «path not found ‘.vbbad70.tmp’ while i used:
Sheets(SheetCount).Copy After:=Sheets(SheetCount)

Hi thank you very much for these codes, it really saves a lot of time.I have question in regards to the copying of a sheet to a closed workbook.When I tried to do that it gives me a runtime error’91’ «currentSheet.Copy After:=closedBook.Sheets(closedBook.Worksheets.Count)».I’m copying to a hard drive. Will be glad if you can assist. Regards, Jan.

Hi,
It is very useful.
Can you help me with the codes to copy multiple sheets (Only values & format) from workbook to new workbook.
Thanks!

Amazing thank you! Did exactly what I needed it to (with some easy modifications)

Hi,
re Power Pivot / Manage in Data Model
I get this message «PowerPivot is unable to load the Data Model.»
I have tried a lot of ways to sort this problem, but no luck.
Do you think it would work if I export all the modules and Sheets individually and then import them into a new clear Workbook (.xlsm)

Dear Sir,
I have a workbook in which a sheet with some formulas. I want a duplicate copy of this sheet and rename with a cell value. And I want this duplicate sheet with Cell values only (as paste special). I did it with the help of your formulas but it is copy and pasting on the source sheet not on duplicate sheet. Please help me.
Private Sub CommandButton1_Click()
Dim wks As Worksheet
Set wks = ActiveSheet
ActiveSheet.Copy After:=Worksheets(Sheets.Count)
If wks.Range(«b9»).Value «» Then
On Error Resume Next
ActiveSheet.Name = wks.Range(«b9»).Value
End If
CommandButton2_Click
‘wks.Activate
End Sub
Private Sub CommandButton2_Click()
Worksheets(Sheets.Count).Activate
Range(«a1:s36»).Copy
Range(«a1:s36»).PasteSpecial xlPasteValues
End Sub

Morning all,
The above macros are extremely useful, but is there a way to copy the sheet across as «values only», similar to the PasteSpecial method?

Could anyone please help me on how to copy sheets with shapes?
My code is referencing to a specific shape, therefore when I copy the sheet, names of the shapes change.
How can I prevent this?
Is there a way to write a code that doesn’t have to reference each shape?
Thank you for your help.

I am trying to duplicate a excel sheet multiple times, rename them based on an Excel List, and then populate the column next to the sheet name with a link to the sheet.
The list is found in the «Cover» sheet and I want to copy the «Template» sheet based on the list selection. The link shortcut will be in the cover sheet in the column next to the cell that was used to generate the sheet name. There will be a lot of tabs and this will make life a lot easier if there is a link from the cover page
Is this possible, and if so how can I do it?

Hi
Is it possible to overwrite a sheet of the same name in the worksheet where the sheet is to be copied? I need to be able to copy the same sheet from time to time. Please help?

Hi,
Your macros have been extremely helpful.
I really appreciate your work. Thank you.
Thank you so much.

Excel macro to copy sheet and rename

Is there anyway for the button to be on one sheet but instead of copying the active sheet it copies the sheet called New Hire?

Excel VBA to duplicate sheet multiple times:
This is the closest to what I am trying to do. But all the new sheets are named he same as the original but with (x). i.e. Original sheet is 10001 and I need them to number 10002, 10003, etc. But they are numbering 10001, 10001(1), 10001(2).
How can I get my sheet tabs to number the way I want? Any help would be greatly appreciated.
Thanks!

Thanks for this vba «Excel VBA to copy sheet from another workbook without opening» which works excellently in its current form. Can you please tweak it a little so that instead of giving a specific path, a window opens and I select the file from which data needs to be pulled. Rest it should remain the same. Thanks in advance.

Hi I have used your code titled «Excel VBA to duplicate sheet multiple times»

but how shall I rename the sheets? I want them to be in numbers.

Eg
Original Sheet is «master’
Copy need 5
result shall be in sheet name as
Point 1
Point 2
Point 3
Point 4
Point 5

—[Snip, Snip]—
Public Sub DuplicateSheetMultipleTimes()
Dim n As Integer
On Error Resume Next
n = InputBox(«How many copies of the active sheet do you want to make?»)

If n >= 1 Then
For numtimes = 1 To n
activeSheet.Copy After:=ActiveWorkbook.Sheets(Worksheets.Count)
ActiveSheet.name = «Point » + CStr(numtimes)
Next
End If
End Sub
—[Snip, Sni

This will cause the various copied sheets to be renamed as they are copied

Hi,
I have a workbook with many sheets. I need particular cells copied from sheet 1,sheet2 of Workbook1 and show it in another workbook. For example I have the dealer ID and name in Sheet1 and the rating in sheet5 of the same workbook1. I need to pull the rating using ID which is unique to another worksheet and then I need the ID field to be dynamic. How do I do it? please advise.

Is it possible to pick up a range of tabs? For example, the macro requires that I list the tab names individually ie.Sheets(Array («Tab1», «Tab2», «Tab3», “etc…”)).Copy)
What if I want to pick up all the tabs between «Tab1» and «Tab8» without listing them all individually? Is this possible?

Hello, your macros have been extremely helpful.
I was wondering if the following can be achieved
1) I select a range, say A2-A15, which contains the names of worksheets in a particular workbook.
2) I want to create a new workbook with the selected worksheet names from the active workbook using the following formula:
“
Sub Copy_Worksheets()
Worksheets(Array(«ACC_HF», «ACC_Aflac», “etc…”)).Copy
End Sub
”
Is there a way to convert the selected range and pass is to the array argument?

How can i copy data from a range of cells say B5:I39 from multiple worksheets and paste them to one new worksheet, i want to be able to have all selected worksheets with specific data range to be copied to one worksheet at the end of the workbook. All formatting from selected sheets to be coppied across too.

Thanks for the tip, is there a way to copy a row in one workbook and paste that row of data to a different workbook on a specific cell? There is a catch though, the data will need to sync to a different tab of the same workbook every other month.

That’s great
how can I copy sheets containing a specific text string somewhere on the sheet, to a new workbook?

Источник

Понравилась статья? Поделить с друзьями:
  • Coolest word in the dictionary
  • Cool words for word of the day
  • Cool word for friend
  • Copying text from pdf to word
  • Cool word about music