Vba excel copy after

Создание, копирование, перемещение и удаление рабочих листов Excel с помощью кода VBA. Методы Sheets.Add, Worksheet.Copy, Worksheet.Move и Worksheet.Delete.

Создание новых листов

Создание новых рабочих листов осуществляется с помощью метода Sheets.Add.

Синтаксис метода Sheets.Add

expression.Add [Before, After, Count, Type]

где expression — переменная, представляющая собой объект Sheet.

Компоненты метода Sheets.Add

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлен новый.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлен новый.
  • Count — необязательный параметр типа данных Variant, указывающий, сколько листов будет добавлено (по умолчанию — 1).
  • Type — необязательный параметр типа данных Variant, указывающий тип листа: xlWorksheet** (рабочий лист) или xlChart (диаграмма), по умолчанию — xlWorksheet.

*Если Before и After не указаны, новый лист, по умолчанию, будет добавлен перед активным листом.

**Для создания рабочего листа (xlWorksheet) можно использовать метод Worksheets.Add, который для создания диаграмм уже не подойдет.

Примеры создания листов

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

‘Создание рабочего листа:

Sheets.Add

Worksheets.Add

ThisWorkbook.Sheets.Add After:=ActiveSheet, Count:=2

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Лист1

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(1)

Workbooks(«Книга1.xlsm»).Sheets.Add After:=Worksheets(«Лист1»)

‘Создание нового листа с заданным именем:

Workbooks(«Книга1.xlsm»).Sheets.Add.Name = «Мой новый лист»

‘Создание диаграммы:

Sheets.Add Type:=xlChart

‘Добавление нового листа перед

‘последним листом рабочей книги

Sheets.Add Before:=Sheets(Sheets.Count)

‘Добавление нового листа в конец

Sheets.Add After:=Sheets(Sheets.Count)

  • Лист1 в After:=Лист1 — это уникальное имя листа, указанное в проводнике редактора VBA без скобок.
  • Лист1 в After:=Worksheets(«Лист1») — это имя на ярлыке листа, указанное в проводнике редактора VBA в скобках.

Создаваемый лист можно присвоить объектной переменной:

Dim myList As Object

‘В активной книге

Set myList = Worksheets.Add

‘В книге «Книга1.xlsm»

Set myList = Workbooks(«Книга1.xlsm»).Worksheets.Add

‘Работаем с переменной

myList.Name = «Listok1»

myList.Cells(1, 1) = myList.Name

‘Очищаем переменную

Set myList = Nothing

Если создаваемый лист присваивается объектной переменной, он будет помещен перед активным листом. Указать дополнительные параметры невозможно.

Копирование листов

Копирование рабочих листов осуществляется с помощью метода Worksheet.Copy.

Синтаксис метода Worksheet.Copy

expression.Copy [Before, After]

где expression — переменная, представляющая собой объект Worksheet.

Компоненты метода Worksheet.Copy

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет добавлена копия.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет добавлена копия.

*Если Before и After не указаны, Excel создаст новую книгу и поместит копию листа в нее. Если скопированный лист содержит код в проекте VBA (в модуле листа), он тоже будет перенесен в новую книгу.

Примеры копирования листов

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

‘В пределах активной книги

‘(уникальные имена листов)

Лист1.Copy After:=Лист2

‘В пределах активной книги

‘(имена листов на ярлычках)

Worksheets(«Лист1»).Copy Before:=Worksheets(«Лист2»)

‘Вставить копию в конец

Лист1.Copy After:=Sheets(Sheets.Count)

‘Из одной книги в другую

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Copy _

After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1»)

‘Один лист активной книги в новую книгу

Лист1.Copy

‘Несколько листов активной книги в новую книгу*

Sheets(Array(«Лист1», «Лист2», «Лист3»)).Copy

‘Все листы книги с кодом в новую книгу

ThisWorkbook.Worksheets.Copy

* Если при копировании в новую книгу нескольких листов хотя бы один лист содержит умную таблицу — копирование невозможно. Один лист, содержащий умную таблицу, копируется в новую книгу без проблем.

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Перемещение листов

Перемещение рабочих листов осуществляется с помощью метода Worksheet.Move.

Синтаксис метода Worksheet.Move

expression.Move [Before, After]

где expression — переменная, представляющая собой объект Worksheet.

Компоненты метода Worksheet.Move

  • Before* — необязательный параметр типа данных Variant, указывающий на лист, перед которым будет размещен перемещаемый лист.
  • After* — необязательный параметр типа данных Variant, указывающий на лист, после которого будет размещен перемещаемый лист.

*Если Before и After не указаны, Excel создаст новую книгу и переместит лист в нее.

Примеры перемещения листов

Простые примеры перемещения листов:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

‘В пределах активной книги

‘(уникальные имена листов)

Лист1.Move After:=Лист2

‘В пределах активной книги

‘(имена листов на ярлычках)

Worksheets(«Лист1»).Move Before:=Worksheets(«Лист2»)

‘Размещение после последнего листа:

Лист1.Move After:=Sheets(Sheets.Count)

‘Из одной книги в другую

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Move _

After:=Workbooks(«Книга2.xlsm»).Worksheets(«Лист1»)

‘В новую книгу

Лист1.Move

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Перемещение листа «Лист4» в позицию перед листом, указанным как по порядковому номеру, так и по имени ярлыка:

Sub Peremeshcheniye()

Dim x

x = InputBox(«Введите имя или номер листа», «Перемещение листа «Лист4»»)

If IsNumeric(x) Then x = CLng(x)

Sheets(«Лист4»).Move Before:=Sheets(x)

End Sub

Удаление листов

Удаление рабочих листов осуществляется с помощью метода Worksheet.Delete

Синтаксис метода Worksheet.Delete

expression.Delete

где expression — переменная, представляющая собой объект Worksheet.

Примеры удаления листов

‘По уникальному имени

Лист1.Delete

‘По имени на ярлычке

Worksheets(«Лист1»).Delete

‘По индексу листа

Worksheets(1).Delete

‘В другой книге

Workbooks(«Книга1.xlsm»).Worksheets(«Лист1»).Delete

Если рабочие книги указаны как элементы коллекции Workbooks, в том числе ActiveWorkbook и ThisWorkbook, листы нужно указывать как элементы коллекции Worksheets, использование уникальных имен вызовет ошибку.

Как обратиться к рабочему листу, переименовать, скрыть или отобразить его с помощью кода VBA Excel, смотрите в этой статье.

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

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

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

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

Содержание

  1. Метод Sheets.Copy (Excel)
  2. Синтаксис
  3. Параметры
  4. Замечания
  5. Пример
  6. Поддержка и обратная связь
  7. Sheets.Copy method (Excel)
  8. Syntax
  9. Parameters
  10. Remarks
  11. Example
  12. Support and feedback
  13. Метод Worksheet.Copy (Excel)
  14. Синтаксис
  15. Параметры
  16. Замечания
  17. Пример
  18. Поддержка и обратная связь
  19. Worksheets.Copy method (Excel)
  20. Syntax
  21. Parameters
  22. Remarks
  23. Example
  24. Support and feedback
  25. Метод Worksheets.Copy (Excel)
  26. Синтаксис
  27. Параметры
  28. Замечания
  29. Пример
  30. Поддержка и обратная связь

Метод Sheets.Copy (Excel)

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

Синтаксис

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

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

Параметры

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

Замечания

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

Пример

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

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

Есть вопросы или отзывы, касающиеся 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.

Источник

Метод 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 и обратная связь.

Источник

Worksheets.Copy method (Excel)

Copies the sheet to another location in the workbook.

Syntax

expression.Copy (Before, After)

expression A variable that represents a Worksheets 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.

If the sheet specified by After is hidden and there are no visible sheets after it, the new sheets will be copied after the last visible sheet rather than after the specified one. Making the sheet specified by After visible before the copy allows to get the new sheets in the correct position.

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.

Источник

Метод Worksheets.Copy (Excel)

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

Синтаксис

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

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

Параметры

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

Замечания

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

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

Пример

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

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

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

Источник

Понравилась статья? Поделить с друзьями:
  • Vba excel convert to number one
  • Vba excel controls add
  • Vba excel commandbutton click
  • Vba excel collection of collections
  • Vba excel combobox формат даты