Finance

Charts

Statistics

Macros

Search

Copying a Worksheet in Excel VBA

Copying a Worksheet

The following VBA procedure creates a copy of an existing worksheet in the same workbook:

Sub CopySheet()
    ThisWorkbook.Activate
    Worksheets("Sheet2").Copy After:=Worksheets("Sheet2")
    ActiveSheet.Name = "Sheet2copy"
End Sub

Explanation:

  • Ensure the correct workbook is active
  • Activate

This makes sure that the code targets the workbook containing the macro, especially important when multiple workbooks are open.

Copy a specific worksheet

Worksheets(« Sheet2 »).Copy After:=Worksheets(« Sheet2 »)

    • The Copy method is used to duplicate the worksheet named « Sheet2 ».
    • The After:= parameter specifies that the copy should be placed immediately after the original sheet within the same workbook.
    • The copied sheet becomes the active sheet once created.

Rename the copied worksheet

Name = « Sheet2copy« 

    • After the copy is made and activated, it’s renamed to « Sheet2copy ».

 

About the Copy Method Parameters:

  • After:=Worksheets(« Sheet2 »)
    This is an example of a named parameter, where the parameter name (After) is explicitly stated, followed by := (colon-equals) and the value.
  • Alternatively, you can use Before:=… to insert the copied sheet before a specific sheet.
  • If neither After nor Before is specified, Excel creates the copied sheet in a new workbook instead of the current one.

Why Use Named Parameters?

  • They make your code clearer by explicitly stating which argument you are assigning.
  • You don’t have to specify all parameters—just the ones relevant to your case.
  • They reduce confusion, especially when multiple optional parameters are involved.

Important Note:

If you try to run the macro again without deleting or renaming the copied sheet, you’ll get a runtime error because worksheet names must be unique within the same workbook.

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx