Excel vba copy sheet to new sheet

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

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
Skip to content

Copy Data from one Worksheet to Another in Excel VBA

Home » Excel VBA » Copy Data from one Worksheet to Another in Excel VBA

  • Copy Data from one Worksheet to Another in Excel VBA

Description

When we are dealing with many worksheet, it is a routine thing to copy data from one worksheet to another in Excel VBA. For example, we may automate a task which required to get the data from different worksheets (some times different workbooks). In this situation, we need to copy the some part the worksheet and paste it in a target worksheet.

Copy Data from one Worksheet to Another in Excel VBA – Solution(s)

Copy data from one Worksheet to anotherWe can use Copy method of a range to copy the data from one worksheet to another worksheet.

Copy Data from one Worksheet to Another in Excel VBA – An Example

The following example will show you copying the data from one sheet to another using Excel VBA.

Code:
'In this example I am Copying the Data from Sheet1 (Source) to Sheet2 (Destination)
Sub sbCopyRangeToAnotherSheet()

'Method 1
Sheets("Sheet1").Range("A1:B10").Copy Destination:=Sheets("Sheet2").Range("E1")

'Method 2
'Copy the data
Sheets("Sheet1").Range("A1:B10").Copy
'Activate the destination worksheet
Sheets("Sheet2").Activate
'Select the target range
Range("E1").Select
'Paste in the target destination
ActiveSheet.Paste

Application.CutCopyMode = False

End Sub
Instructions:
  1. Open an excel workbook
  2. Enter some data in Sheet1 at A1:B10
  3. Press Alt+F11 to open VBA Editor
  4. Insert a Module for Insert Menu
  5. Copy the above code and Paste in the code window
  6. Save the file as macro enabled workbook
  7. Press F5 to run it

Now you should see the required data (from sheet1) is copied to the target sheet (sheet2).

Explanation:

We can use two methods to copy the data:
Method 1: In this method, we do not required to activate worksheet. We have to mention the source and target range. This is the simple method to copy the data.
Method 2: In this method, we have to activate the worksheet and paste in a range of active worksheet.

The main difference between two methods is, we should know the destination worksheet name in the first method, in second method we can just activate any sheet and paste it.

Download the Example Macro Workbook:

Download the Example VBA Macro File and Explore the code example to copy the data from one sheet to another worksheet:

Copy Data Form One Sheet To Another Sheet

Copy from One Sheet And Paste in Another Worksheet

Here is the simple VBA Code to Copy and Paste the Data from one worksheet to another.

Sub VBAMacroToCopyDataFromOneSheetToAnother()

'You can use the below statement to Copy and Paste the Data
'Sheets(Your Source Sheet).Rows(Your Source Range).Copy Destination:=Sheets(Your Target Sheet).Range(Your Target Range)
'For Example:

Sheets("SourceSheet").Range("B4:B5").Copy Destination:=Sheets("TargetSheet").Range("C2")

End Sub

Copy Data into Another Sheet based on Criteria

Most of the times we need VBA code to copy data from one sheet to another based on criteria. The following VBA Code to helps you to Copy and Paste the Data based on certain condition.

Sub CopyDataBasedOnStatusCondtion()
'You can also copy entire row and paste into different sheets based on certain criteria.
'See the below example to copy the rows based on criteria


Dim lRow, cRow As Long
lRow = Sheets("YourMain").Range("A50000").End(xlUp).Row 'Last row in your main sheet
'change the sheet name as per your needs


'Let's find these items in the Main sheet and send to the respective sheet
For j = lRow To 1 Step -1
'Assuming you have the drop-down in the first Column (= Column A)
    
'looping throu your main sheet and copying the data into respective sheet
    If Sheets("YourMain").Range("A" & j) = "Pending" Then
        cRow = Sheets("Pending").Range("A50000").End(xlUp).Row
        Sheets("YourMain").Rows(j).Copy Destination:=Sheets("Pending").Range("A" & cRow + 1)
        
        'You can delete the copied rows in the source sheet using below statement
        'Sheets("YourMain").Rows(j).Delete
    ElseIf Sheets("YourMain").Range("A" & j) = "Follow up" Then
        cRow = Sheets("Follow up").Range("A50000").End(xlUp).Row
        Sheets("YourMain").Rows(j).Copy Destination:=Sheets("Follow up").Range("A" & cRow + 1)
        
        'Sheets("YourMain").Rows(j).Delete
    
    ElseIf Sheets("YourMain").Range("A" & j) = "Completed" Then
        cRow = Sheets("Completed").Range("A50000").End(xlUp).Row
        Sheets("YourMain").Rows(j).Copy Destination:=Sheets("Completed").Range("A" & cRow + 1)
        
        'Sheets("YourMain").Rows(j).Delete
    End If
Next


'*NOTE:if this solution is for your clients, -
'You may have to write some validation steps-
'to check if all required sheets are available in the workbook
'to avoid future issue.
End Sub

Macros for Copying Data Using VBA:

  • Copy Method Explained
  • Copy Data from one Worksheet to Another in Excel VBA
  • Copy Data from One Range to Another in Excel VBA
  • Copying Moving and Pasting Data in Excel
  • Data Entry Userform
  • VBA to Append Data from multiple Excel Worksheets into a Single Sheet – By Column
  • VBA to Consolidate data from multiple Excel Worksheets into a Single Sheet – By Row
  • CopyFromRecordset
  • VBA Sort Data with No headers Excel Example Macro Code
  • VBA Sort Data with headers Excel Example Macro Code
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

    • Description
    • Copy Data from one Worksheet to Another in Excel VBA – Solution(s)
      • Download the Example Macro Workbook:
    • Copy from One Sheet And Paste in Another Worksheet
    • Copy Data into Another Sheet based on Criteria
    • Macros for Copying Data Using VBA:

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:

102 Comments

  1. I am trying to copy specific ranges from 12 worksheets on from the “Source” workbook to the same specific ranges on 12 worksheets to the “Target” workbook. How can I set up a “loop” to accomplish this in a VBA code? Thanks!

    – Ron –

  2. PNRao
    December 4, 2013 at 11:05 PM — Reply

    ‘If your input files are always same then store them in an Array
    mySource=Array(“File1.xlsx”,”File1.xlsx”,…,”File12.xlsx”)

    ‘If they are not same always then read your workbook names and store it in an Array (mySource)


    'open each workbook

    For iCntr=1 to 12
    set sourceWB=Workbooks.Open(mySource(iCntr-1)) ' since array starts from 0
    sourceWB.Sheets("YourSheetName").Range("YourRange").copy ThisWorkbook.Sheets("YourTargetSheet").Range("TargetRange")
    'Example:sourceWB.Sheets("Sheet1").Range("A1:A10").copy Destination:=ThisWorkbook.Sheets("YourTargetSheet").Range("A" &iCntr*10+1)
    next

    Search with a keyword ‘downloads’ in our site, you will get the working file to see the code.

    Hope this helps-PNRao!

  3. Ping
    January 22, 2014 at 6:15 AM — Reply

    How can we select user choice range and paste it in user defined range? Can we give ability to transpose the data if user wants? Do u gave any vba script that can help me with that?

  4. PNRao
    January 22, 2014 at 11:13 PM — Reply

    Hi,

    We give the user to select a range to copy and range to paste in two different ways.

    1. You can use two input boxes: one is to accept the ranges from users and other one is to choose the range to paste.
    Please check this link to for advanced input box examples: http://analysistabs.com/excel-vba/inputbox-accept-values/

    2.The other method is, creating userform and place two RefEdit controls. one is for to select the range to copy and the other one is the for accepting the range to paste.

    So, now you know the range to copy and the range to paste the data. Then you can use, pastespecial method to transpose the data

    Example: Let’s say you accepted two ranges from user and stored as rngToCopy and rngToPaste

    Range("rngToCopy").Copy
    Range(rngToPaste).Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= False, Transpose:=True

    Hope this helps.
    Thanks-PNRao!

  5. Matt
    May 6, 2014 at 11:36 PM — Reply

    Hey! I work for a transportation company and have a workbook in which I keep track of trailers parked at a lot daily. Every day I copy the previous day’s sheet and rename to today’s date.

    So I have sheet “05-05” and I copy it and rename the new sheet to “05-06”. I have been Googling this for hours now to no avail: I am trying to create a button that runs a macro that creates a copy of the active sheet, and renames it to today’s date. If I have to include the year in my sheet names that is fine. Can anyone help?

  6. Aliya
    May 8, 2014 at 1:46 PM — Reply

    Hi there,

    Could you please help me with the following:

    I have two worksheets named Data and Levels. In Data worksheet I have thousands of rows and three columns ( region, ID, and sum). In Levels worksheet I have only hundreds of rows and two columns (ID and Level). What I need is to put for each row in the first sheet its corresponding level from the second sheet.

    I’m only a beginner, so detailed explanation would be much appreciated,

    Thank you

  7. Josh
    August 13, 2014 at 12:16 AM — Reply

    I am working on a macro to transfer data from one spreadsheet to another. I would like ot transfer the data to the next open row within the second spreadsheet. Basically I want to take electronic batch sheets, with data entered in them, and transfer that data to a central source for record keeping. Is this doable?

    Thanks for any help you can offer.

  8. PNRao
    August 17, 2014 at 11:34 AM — Reply

    Hi Josh,
    We can do this, every time you need to find the last row in the common file and update the data from that particular row. You can search for the examples provided to find the last row in the excel sheet. Or, you can send me the sample file.

    Thanks-PNRao!

  9. chander shekhar
    August 17, 2014 at 3:43 PM — Reply

    i have one folder named checking master and it contains 4macro enabled excel2010 files and each file has 8 worksheet and i want to copy data from these four macro enabled files specific sheet called”register sheet ” ranging a2to k2 without opening these files into a new file master file in the same folder.further if files becomes more tan 4 macro enabled files then also all files “register sheet’s range a2 to k2 automatically transferred in the master file.please help through vba code and intimate through email and oblige

  10. And, as always, if you have questions about this or any other
    financial topic, seek the services of a licensed,
    responsible financial advisor or other professional.
    You might be able to obtain your score at no cost after you have applied for a
    loan. For this purpose you will have to limit the credit account as well as the
    credit card, make timely repayments of the credit facility availed and enhance your credit transactions.

  11. SS
    September 16, 2014 at 1:10 PM — Reply

    Hi I am pretty rubbish when it comes to VBA, im trying to put together a stock book where everything in column A, B and C on sheet1 automatically copies on to column A, B and C in sheet2. I want them to appear in exactly the same cell for each column. I dont want to have to click run or a button. Can you help?

  12. Ahamed
    November 6, 2014 at 5:29 PM — Reply

    In the VB Macro Can you also apply filter conditions from the source workbook to copy (based on filter) and paste it in a destination workbook. please note its a different workbook and NOT sheets.

  13. ratna
    November 13, 2014 at 2:39 PM — Reply

    please give me copy and paste jobs

  14. ratna
    November 13, 2014 at 2:40 PM — Reply
  15. syam
    November 28, 2014 at 5:22 PM — Reply

    Hi
    for every month, i am using one spreadsheet for each day. so for example for 30 days in a month, 30 spread sheets. the spread sheets contains lot of matter.
    what i need is the data of total month details has to come in one spreadsheet with date wise.

    example: 01.12.2014 02.12.2014…………………………………………………………………..31.12.2014
    1 3 7
    2 4 7
    2 6 2

  16. PNRao
    November 29, 2014 at 7:39 PM — Reply

    Hi Syam,
    You can do this using formula or VBA, please send an example file, we are happy to help you.

    Thanks
    PNRao!

  17. Aaron
    December 17, 2014 at 10:13 PM — Reply

    Hello

    The code works great but is there away of molding it slightly so instead of “Activatesheet.paste” you can paste only the values?

    Thank you

  18. K.S. Gill
    January 19, 2015 at 3:54 PM — Reply

    Hello
    I want to import data form one workbook to another workbook using VBA form,
    the main problem is that import dxata cantain duplicate values I do not import them I want only append new values in column.
    Please help.
    Thank you

  19. PNRao
    January 19, 2015 at 6:50 PM — Reply

    Hi K.S.Gill,

    You can check the duplicated records while updating it. You can do this in different ways:

    1.if your input data having minimal rows and columns then you can use for loop to check the duplicates and update record by record.

    2. If you have lot of records in your input file, then import all the records to your target file and then delete the duplicate records in one sheet using Delete Duplicate function available in the Excel.

    3. If may not want to disturb your target sheet -then you can duplicate the sheet and import the latest data into this temporary sheet. And run the macro to delete duplicates and then merge the unique records to your actual worksheet.

    Hope this helps.
    Thanks-PNRao!

  20. aja
    January 21, 2015 at 4:30 AM — Reply

    Hello all,

    I am beginner and I am looking import multiple text files (2200) to excel and make a single excel sheet using VBA

    Please help.. I am trying this using this code…

    [CODE]

    Sub CombineTextFiles()
    Dim FilesToOpen
    Dim x As Integer
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim sDelimiter As String
    ‘===================================
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    ‘======================================
    sDelimiter = “:”

    FilesToOpen = Application.GetOpenFilename _
    (FileFilter:=”Text Files (*.txt), *.txt”, _
    MultiSelect:=True, Title:=”Text Files to Open”)

    If TypeName(FilesToOpen) = “Boolean” Then
    MsgBox “No Files were selected”
    GoTo ExitHandler
    End If

    x = 1
    Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
    wkbTemp.Sheets(1).Copy
    Set wkbAll = ActiveWorkbook
    wkbTemp.Close (False)
    wkbAll.Worksheets(x).Columns(“A:A”).TextToColumns _
    Destination:=Range(“A1″), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, _
    ConsecutiveDelimiter:=False, _
    Tab:=False, Semicolon:=False, _
    Comma:=False, Space:=False, _
    Other:=True, OtherChar:=”|”
    x = x + 1

    While x Date
    Date Sta1Load.Pass Sta1Load.
    Code

    Sta1Load.
    VisionProgram

    Sta2Armature.Pass

    Sta2Armature.Code

    Sta2Armature.
    VisionProgram
    Sta3Weld.Pass: False
    2015-1-19 9:19:55 True 411 0 False 0 0 Flase
    Text file2 data
    Text fiel 3 data

  21. tom
    February 6, 2015 at 2:22 AM — Reply

    Hi PNRao, please could you help me with a VBA formula about this matter? I want to copy the data from sheet1 to sheet2 automaticly. In sheet1 there are formulas in the cells, but I want only the text to be copied to sheet2, everytime something changes in sheet1. Is this possible? I hope for a answer, would be very appreciated! Thanks a lot in advance for any help!

  22. PNRao
    March 2, 2015 at 6:54 PM — Reply

    Hi Tom,

    You can write something like below in Worksheet change event:

    Range("rngToCopy").Copy
    Range(rngToPaste).Select
    Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= False, Transpose:=True
    

  23. JM
    March 4, 2015 at 9:43 AM — Reply

    Hi,
    I have some data in sheet 1 and want to summarize it in sheet 2. Column A has the country names and Column B&C has some data. In most of the cases column B&C are not blank and in some cases either of one is blank or both are blank. I want to copy only the countries which has data in either one of the columns in sheet 2, by avoiding the blank rows. Please assist

  24. PNRao
    March 7, 2015 at 7:44 PM — Reply

    Hi JM,

    Please refer the below macro:

    Sub sbCopyCounryDataIfAvialble_OR_NotBlank()
    Dim iCntr, jCntr, lRow As Integer
    
    'iCntr is to loop through the Sheet1
    'jCntr is for sheet2 last row
    'lRow is the last row with data in sheet1
    
    
    lRow = 226 'if it is dynamic, please refer our most useful macros to find the last row
    
    jCntr = 1 '
    For iCntr = 1 To lRow
        If Cells(i, 2) <> " Or Cells(i, 3) <> " Then 'Either of the cell should have data
            Sheet(jCntr, 1) = Cells(i, 1) ' country name
            Sheet(jCntr, 2) = Cells(i, 2) ' Column B
            Sheet(jCntr, 3) = Cells(i, 3) ' Column C
            j = j + 1
        End If
    Next
    
    End Sub
    

    Thanks-PNRao!

  25. Vamsi
    March 10, 2015 at 3:47 PM — Reply

    Hi Sir,

    I am in starting stage of using macros for good effect, here we have a workbook, in which we will have lots of data in sheet1(Data_Source), we have copy data from sheet 1 to sheet2(“Data_Extracted”) with specific headers matching in sheet1 to sheet2
    we have to copy only those data which have the specific headings.

    the data in the sheet1 is dynamic and keeps on changing at the End of each day, and we need only values into sheet2.
    in sheet1 we will have formulas in almost all columns,so we require only values to be pasted in sheet2

    in sheet1 we will be having like for ex 32 columns(headings), we need only 9or 10 columns out of those 32.

    please send me the code for this to my mail, your help is highly required.

    Many Thanks in advance.

    please help ASAP.

  26. Rich
    March 15, 2015 at 5:00 AM — Reply

    I putting together and inventory sheet to track my restaurant inventory. I have figured out how to get the data from my add sheet and my remove sheet to the calculation sheet. The only problem is every time I run the macros it overwrites the data already on they calculation sheet. I have been trying to figure out what code line I need to search for the next available row and then paste my data. Can anyone help me with this? Keep in mind I am a beginner when it comes to this stuff.

  27. Yvonne
    March 15, 2015 at 8:59 PM — Reply

    Hi,
    could you please help me with a VBA formula about this matter? I have approx 60 files (.xls or .xlsx) saved in a drive c:test. However the number of files varies each time. (maybe less or maybe more)… I want to open the files from the directory and paste to master.xls assigned tabs. (i.e. abc.xls must go to master.xls TAB ABC, efg.xls must go to master.xls TAB EFG tab, and so on). I see a lot of vba that loop through directory if filename xls THEN copy to just master sheet. But since my number of file varies each time, and each file must be paste to assigned TABS. Please assist and thanks in advance.

  28. Sandeep
    March 18, 2015 at 7:30 PM — Reply

    Hi,

    i have got a requirement to copy data from One Excel Workbook to another Workbook(Located locally on the same machine). This will help me consolidate the data am receiving from my peers to a master file. Ideally there should be a VBA button on the source workbook if i click on it, that should trigger copying to the Master Workbook.

    Appreciate if someone can help on this. Thanks

  29. PNRao
    March 21, 2015 at 2:48 PM — Reply
  30. Dima
    March 23, 2015 at 9:22 PM — Reply

    Hi
    I’m working on excel document and I have to find a solution for situation like this. In one of the cells I need to have one word permanently and when I’m putting one click on it to write next to it a name which I will use on other sheet.
    For example: cell -> |Patient: (next to him impute name)|
    Is exist an solution to do this using VBA or formulas?
    Thank you for any help!

  31. BamaChic
    March 23, 2015 at 10:50 PM — Reply

    Hi,
    I have been told in some forums that this isn’t possible, but have been working on figuring this out for weeks! The company I work for is a Gov’t Subcontractor. The owner has a master spreadsheet “Pipeline Data”. There are headers in row 1, data from columns A-S and currently 348 entries. Columns M & N contain years for the solicitation date and award date (these can be the same year or 5 years apart). Is it possible to have a code transfer the data in the rows that have 2015 as the year in either M or N to a worksheet “2015”? The owner wants to be able to click on the worksheet 2015, 2016, 2017 etc. and see all the solicitations and awards that will occur in that year.
    The other tricky part is he wants it to automatically update when I enter new data in a row….so for example, if the new data has solicitation year 2015, but awarded in 2018 then it will automatically copy to both sheets 2015 & 2018.
    I did find a code in a forum that worked checking column M for the dates, but having no experience with VBA, I have no idea how to rewrite it to check both columns M & N. As I stated, others have told me Excel was not capable of doing this, but I want someone else’s opinion. I know the owner is tired of hearing “I’m still working on it”, but I have yet to find a way for this to work and I am a determined lady. Thank you in advance for any help you can offer me!!

  32. PNRao
    March 24, 2015 at 7:34 PM — Reply

    Hi Dima,

    You can write VBA code for this in Selection_Change() event of the worksheet:

    The below example will write current date and time on the B1 when you click on the A1:

    Please paste the below code in the required worksheet code module:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        If Target.Address = "$A$1" Then
            
            Target.Offset(0, 1) = Now()
            Target.Offset(0, 1).Select
            'Or Range("B1")= Now()
        End If
    End Sub
    

    Thanks-PNRao!

  33. Georgios
    March 25, 2015 at 10:05 PM — Reply

    Hi there if its possible to help me with a very complicate issue in vba.

    Well the situation is this: i have a set of around 50 files (more less) and there are all in the same format (i have created them). There are answers from a research that i did (with names and values 0,1 or 2). Like the following:
    B5 = Question 1
    B6 = Question 2
    B7 = Question 3
    etc
    to Question 30

    from D4 to N4 horizontaly there are names like (Thomson, James, Howard…etc ) where are corresponded values like 0 or 1 or 2 per name and question. The only difference between these 50 files is that not always each cell is fullfiled from (d4 to N4 with names) . Sometimes are less than 11 names and left it blank the coressponded cell but the format is the same for all 50 files.
    What i want to do is little complicated. I want to take each response from FILE1,FILE2…to FILE50 and copy the values into another file or sheet. In the new file or sheet i want to organized the answers in lists per answer and per question.

    For example if someone responded
    D5=0 (Thomson responded 0),
    E5=0 (James responded 0)
    F5=2 (Howard responded 2) in File1,

    and in File2
    D5=0 (Brandley responded 0),
    E5=1 (Clarck responded 1)
    F5=2 (Nickolson responded 2)

    I would like to create a list like the following anywhere in a the new sheet or file:
    Question1
    (answered 0 )
    Thomson
    James
    Brandley

    Question1
    (Answered 1)
    Clarck

    Question1
    (Answered 2 )
    Howard
    Nickolson

    These lists should be created for every question from Question1 to Question30.
    I hope i explain well what i would like to do and i hope even more and i would appreciate any suggestion and advice from anyone for this complicated work.

  34. vasu
    April 1, 2015 at 11:07 AM — Reply

    DEAR Matt,
    pls explain ur need in detail. i will help you. I am also in Logistic service. Its a favour for me to help anotherf logistics man. Thank u. Vasu

  35. Zhao Lei
    April 1, 2015 at 1:45 PM — Reply

    Hi,

    Now I want to copy 1 column of data to another workbook, but the data need to be separate in different columns which is not continuous column.

  36. PNRao
    April 1, 2015 at 7:33 PM — Reply

    Hi Zhao,

    you can record a macro and use ‘Text to Columns’ command in the data tab. And change the auto generated code accordingly.

    Thanks-PNRao!

  37. Krishna Bajaj
    May 12, 2015 at 6:07 PM — Reply

    Hi,
    I want to know what i am trying to do is possible or not in excel and if how?
    I want to write data in one sheet (e.g.. sheet1 A1 to G1) and that data get copied to sheet two(e.g.. Sheet2 A1 to G1) then again when i write in the same row of sheet1 (A1 to G1) this time the data get copied to sheet2-A2 to G2 and this process goes on.
    Basicalyy i want to fix my user input cell in sheet1 and the resultant will be transferred to sheet 2.
    Is their any way to do this.
    Thanks in advance for your reply.

  38. PNRao
    May 13, 2015 at 8:23 PM — Reply

    Hi Krishna,
    Here is the code to copy the sheet1 data into sheet2. You can place a button in sheet1 and assign this macro. You can ask your users to fill the data in sheet1 and hit the button to update the sheet2.

    Sub CopyRangeFromSheet1toSheet2()
    Dim lastRow As Long
        lastRow = Sheets("Sheet2").Range("A100000").End(xlUp).Row + 1 ' then next free row in sheet2
        Sheets("Sheet1").Range("A1:G1").Copy Destination:=Sheets("Sheet2").Range("A" & lastRow)
    End Sub
    

    Thanks-PNRao!

  39. mathew
    May 19, 2015 at 7:15 PM — Reply

    Hello,

    we have 100 number of files in a folder which has name like C1.. C2.. C3 to file C100. we have defined name range in all files.

    we need output in a different worksheet named “WORKBOOK”, Sheet name “OUTPUT” Continuously starting from cell A1.

    we want to import a name range (values with same format) which we defined in file C1 to C100 sheet:Sheet1 Cell:A1 (want to loop till it finds a false named range in any file in sheet1 cell A1)

    (Name ranges are either 7 columns or 14 columns, 24 rows as defined.)

    we also have a “OUTPUT” sheet in all files where we get in range A1:N24
    we can also use that as target

    can anyone please help regarding this..

  40. Tom
    May 27, 2015 at 3:45 AM — Reply

    Hi,

    I have 4 columns of data in Sheet 2. I need to search a value in column A and a value in column B. Once both column match at row X, I want to copy column C, row X : row X+1 and column D, row X : row X+1 to show in Sheet 1.

    Please show me how to do this. Thank you!

  41. Woody Ely
    June 1, 2015 at 3:13 AM — Reply

    I have a simply request, I am constructing a call log for myself, I have a drop box that has started, Pending, Follow up and Completed,
    I would like to be able to copy the whole row of data to another worksheet in the same workbook Pending for Pending, Follow up for Follow up and Completed, and also have them removed from the main worksheet when drop box is used to go from started to the other choices, Is the a way to do this
    Any and all help is always appreciated
    Thanks in advanced

  42. PNRao
    June 1, 2015 at 12:51 PM — Reply

    Hi Woody Ely,

    Hope this example helps to solve your requirement:

    Example file to download: http://analysistabs.com/download/copy-data-one-sheet-another/

    Sub CopyDataBasedOnStatusCondtion()
    
    Dim lRow, cRow As Long
    lRow = Sheets("YourMain").Range("A50000").End(xlUp).Row 'Last row in your main sheet
    'change the sheet name as per your needs
    
    
    'Let's find these items in the Main sheet and send to the respective sheet
    For j = lRow To 1 Step -1
    'Assuming you have the drop-down in the first Column (= Column A)
        
    'looping throu your main sheet and copying the data into respective sheet
        If Sheets("YourMain").Range("A" & j) = "Pending" Then
            cRow = Sheets("Pending").Range("A50000").End(xlUp).Row
            Sheets("YourMain").Rows(j).Copy Destination:=Sheets("Pending").Range("A" & cRow + 1)
            Sheets("YourMain").Rows(j).Delete
        ElseIf Sheets("YourMain").Range("A" & j) = "Follow up" Then
            cRow = Sheets("Follow up").Range("A50000").End(xlUp).Row
            Sheets("YourMain").Rows(j).Copy Destination:=Sheets("Follow up").Range("A" & cRow + 1)
            Sheets("YourMain").Rows(j).Delete
        
        ElseIf Sheets("YourMain").Range("A" & j) = "Completed" Then
            cRow = Sheets("Completed").Range("A50000").End(xlUp).Row
            Sheets("YourMain").Rows(j).Copy Destination:=Sheets("Completed").Range("A" & cRow + 1)
            Sheets("YourMain").Rows(j).Delete
        End If
    Next
    
    
    '*NOTE:if this solution is for your clients-
    'You may have to write some validation
    'steps to check if all required sheets are available in the workbook
    'to avoid future isssue
    End Sub
    

    Thanks-PNRao!

  43. Woody Ely
    June 2, 2015 at 6:43 AM — Reply

    Sir,
    I appreciate all your hard work, I had my popup in column K but no worries I just started over and used column A and all is working out. I hope I can call on you again.
    Thanks
    Woody

  44. MR.GSchnitzler
    June 3, 2015 at 12:18 AM — Reply

    Hi there, I have a ~maybe~ simple request:

    I am constructing a sales history. Where I have all the sales of the day recorded on a sheet.
    After we close, I copy (using a Macro) all the info to another Sheet.
    This sheet have info on Column A to N. (beginning on row 7, rows 1 – 6 are for the header)
    Also, I’m trying to filter and copy some rows from that sheet to another.
    The “Search” I’ve made using a UserForm, but I’m having some trouble with the “copy & paste” part.
    Could you suggest a way to do it ?
    If you need, I can also paste the code..
    Thanks in advanced!

  45. PNRao
    June 3, 2015 at 12:19 PM — Reply

    Your most welcome Woody!
    Thanks-PNRao!

  46. NavneetR
    June 24, 2015 at 10:23 AM — Reply

    Hi,
    Kindly help me on the following problem I have a sheet with some names of the products with their company names in two columns respectively & in corresponding the quarter sales is updated in a workbook which need to be copied again to the other workbook which is having same product name in one column & company name in next column in next column & quarter sales (needed to be copied along with values+ cell comments) in other column. The column keeps on changing for each quarter i.e if its A column for this quarter then its B for next quarter.
    Kindly help me with a macro for the same ASAP.
    Thanks in advance.

  47. Maratonomak
    June 30, 2015 at 11:29 PM — Reply

    Hi,

    I’m looking for a VBA code to export tables from a workbook to another .
    Here’s what I have. Workbook1 (“Validation”) has tables exported from access queries. Tables are exported into sheets (F01,F02,F03……F10).
    This tables needs to be exported to another workbook (“Validation Update”) to next blank row. So, table from Workbook1/Sheet F01 to be exported to next blank row, Workbook2/Sheet F01.
    And repeat the process for sheet F02, F03 to F10. Some of the tables may be empty sometimes. Is there any way to use N/A in that case?

    Any help would be greatly appreciated !

  48. manny
    July 6, 2015 at 12:31 PM — Reply

    Hi,
    In my first excel sheet there are around 20 columns but want to copy around 5 of them to the second worksheet using a VBA macro.
    Please help

  49. Valli
    July 6, 2015 at 12:57 PM — Reply

    Hi Manny,

    Please find the below macro code.

    Sub Move_Data_From()
     Sheets("Sheet2").Columns("A:E").Copy Destination:=Sheets("Sheet3").Range("A1")
    End Sub
    

    Where
    Sheet2 – Source Sheet Name
    Sheet3 – Destination Sheet Name
    Columns (“A:E”) – Source Data (Column A to E)
    Range(“A1”) – Destnation Cell or range

    Thanks-Valli

  50. Hella
    July 15, 2015 at 1:06 PM — Reply

    Hi There, I want to copy a specific column from one workbook to another workbook using VBA macros, and both workbooks have merged cells in between the rows , please I need your urgent response

  51. PNRao
    July 15, 2015 at 8:02 PM — Reply

    Hi Hella,

    The below code will copy Column D of Sheet1 from Book1 to Book2:

    'Clear the target Column to avoid Merge Cells Warning
    Workbooks("Book2").Sheets("Sheet1").Range("D:D").Cells.Clear
    
    'Now copy the Column D to target Workbook
    Workbooks("Book1").Sheets("Sheet1").Range("D:D").Copy _
     Destination:=Workbooks("Book2").Sheets("Sheet1").Range("D1")
    

    Hope this helps!
    Thanks-PNRao!

  52. Yogesh Kumar
    July 20, 2015 at 11:22 PM — Reply

    Please request your assistance in Private sub, this is how i want macro to work
    if i enter Email id in sheet 1 any cells of the worksheet it should automatically get updated in “Sheet2 – coloumn 1” and also email id’s should be unique in sheet 2 (i.e no duplication should happen) Please assist me…

  53. Satbir
    July 25, 2015 at 1:58 PM — Reply

    Hi, Want to copy data from various sheets in one, is that possible using Macro?

  54. Stacey
    August 3, 2015 at 8:05 PM — Reply

    Hi,

    I am new to VBA code and don’t really know anything about coding. I am desperately trying to get my worksheets to:
    When yes is entered in a column the macro copies the row the yes is in and transfers it from the waiting list spreadsheet it is in, to the allocated spreadsheet in the next available row, of the same workbook. It would be great if once transfered the data could be deleted from the waiting list spreadsheet and the data below it be moved up.

    This is what i have put so far (like I said I am not a natural at this):

    Sub MoveText()

    ‘ MoveText Macro
    ‘ Move text from Waiting List tab to Allocated tab


    Range(“L8”).Select
    Do Until Selection.Value = “yes”
    If LCase(Selection.Value) = “yes” Then
    Selection.EntireRow.Copy
    Loop
    End If

    Sheets(“Allocated”).Select
    Range(“A6”).Select

    If IsEmpty(ActiveCell.Offset(1)) Then
    ActiveCell.Offset(1).Select
    Else
    ActiveCell.End(xlDown).Offset(1).Select
    End If

    Selection.Paste
    Sheets(“Waiting list”).Select
    Range(“L8”).Select
    Do Until Selection.Value = “xxx”
    If LCase(Selection.Value) = “yes” Then
    Selection.EntireRow
    Selection.Delete
    Else
    Selection.Offset(1, 0).Select
    End If

    I keep getting error messages and have no idea what I am doing wrong. Can anyone kindly help me?

    Stacey

  55. Darren
    August 5, 2015 at 8:34 PM — Reply

    Hi All

    Not sure whether this is acheiveable but here goes…

    I have a workbook with 3 work sheets – Order Form / Stock Level / Order History

    When completing the Order Form, a check is carried out agasint the inputted cell to see if it is in stock, if it is then the Stock Level work sheet is updated accordingly. If it is not availble (<=0) then you are prompted on the Order Form sheet that this isnt in stock and the Stock Level sheet is updated to show that stock is required for order. – If you can follow my poor description then grand, if not – not to worry as this is the part I dont need help with!

    What I do need help with/ words of advise/ shoulder to cry on etc is with the relationship between Order Form & Order History. Ideally, once you have completed the Order Form all the details will be passed through to the Order History, but I only have one instance of the Order Form and the Order History so when I need to put an order through for another member of staff it over – rides the details in the Order History as opposed to ‘adding’ it to the Order History sheet.

    Is there a way, where if you complete Order Form and ‘submit’ it will populate the Order History sheet wit the relevant data and then clear the data out of the Order Form ready for the next entry – whilst keeping this data stored within the Order History Sheet?

    Any help would be appreciated
    Thanks
    Darren

  56. Preet
    August 14, 2015 at 5:26 AM — Reply

    I am struggling with copying data from master file to rest of tabs based on filter. Assuming I have master sheet with column name application and my tabs are arranged with column names, I wanted to copy data from master sheet to corresponding tabs of each application, with keeping master data as well. Also if something is present in master tab but not in application tab, that row must be moved to separate tab I created. This tab is common to all application tab. Reason being, this master sheet is going to get updated every day and I want my tabs to have current data but keeping the old one in misc. tab. I will really appreciate the help. Thanks.

  57. surendar
    August 24, 2015 at 5:25 PM — Reply

    how to copy data from one workbook and paste to another workbook.

  58. PNRao
    August 25, 2015 at 12:13 AM — Reply

    Hi Surendar,
    You can use the Copy command as shown below:

    Workbooks("Book1").Sheets("Sheet1").Range("A1:B10").Copy _
    Destination:=Workbooks("Book2").Sheets("Sheet1").Range("E1")
    

    Thanks-PNRao!

  59. So…
    August 28, 2015 at 4:58 AM — Reply

    How do plan to initiate the script without a button or having to click run?

  60. PNRao
    August 28, 2015 at 10:10 PM — Reply

    We can assign to short-cut key, like Ctr+Q. Go to Macros list and select the macro, then provide the keyboard short-cut in the Options.
    Thanks-PNRao!

  61. Joseph G
    September 15, 2015 at 7:14 PM — Reply

    I have a source spreadsheet with number of rows, now I would like to do the following,

    # copy entire rows 1, 2.. create a new spreadsheet (new excel file) and transpose paste and save the file with value in cell “B2” of new spreadsheet.
    Again
    # copy entire rows 1, 3.. create a new spreadsheet (new excel file) and transpose paste and save the file with value in cell “B2” of new spreadsheet.
    # copy entire rows 1, 4.. create a new spreadsheet (new excel file) and transpose paste and save the file with value in cell “B2” of new spreadsheet.
    And the process go on for 400 rows ans ending up with 400 new Excel spreadsheets with names of values in their corresponding B2 cells.

    I am a public health researcher and with my knowledge in VB, I couldn’t manage write a code. Could someone please help me with this?

    Thanks in advance

  62. Karthikai Sankar
    September 26, 2015 at 4:19 PM — Reply

    Im having Six months data on sheet1.
    I Want to Copy one month data from sheet1 to sheet2.
    can u plz help me to use loop function in VBA codes???
    and how to plot the graphs using macro without gaps..
    i want to plot only for activecell which i copied from sheet1 to sheet2!
    whats the VBA code for this two ??

  63. Navneet Rajwar
    October 7, 2015 at 9:30 AM — Reply

    Hi,
    Kindly help me on the following problem I have a sheet with some names of the products with their company names in two columns respectively & in corresponding the quarter sales is updated in a workbook which need to be copied again to the other workbook which is having same product name in one column & company name in next column in next column & quarter sales (needed to be copied along with values+ cell comments) in other column. The column keeps on changing for each quarter i.e if its A column for this quarter then its B for next quarter.
    Kindly help me with a macro.
    Thanks in advance.

  64. melissa
    November 5, 2015 at 7:40 AM — Reply

    I am entering data in a sheet for stock counts which have the week of the count and the outcome of the count, i would like this data to copy to a master sheet and count how many times the row has been counted across 52 weeks

  65. shahnas
    November 6, 2015 at 2:38 AM — Reply

    HI,

    I have a master excel sheet for my data entry .I want a VB code for saving this sheet in to other work book,which contain 31 sheets.The master sheet shouild be copied every day in to target work book by date basis.For example if I have finished my data entry in master sheet today, by command button click it should be copied to 6th sheet of target sheet.

    pls healp

    shahnas

  66. Patrick
    November 6, 2015 at 6:18 AM — Reply

    Hi all,
    I am trying to develop a code that enables me to copy cells from a variable worksheet and file location and paste them to my “Data” sheet for further analysis, it appears the code i have is copying the cells however getting them to ouptut to the “Data” sheet in my workbook is not happening. my Code is as follows:
    Private Sub CommandButton3_Click()

    Dim fileDialog As fileDialog
    Dim strPathFile As String
    Dim strFileName As String
    Dim strPath As String
    Dim dialogTitle As String
    Dim wbSource As Workbook
    Dim rngToCopy As Range
    Dim rngRow As Range
    Dim rngDestin As Range
    Dim lngRowsCopied As Long

    dialogTitle = “Navigate to and select required file.”
    Set fileDialog = Application.fileDialog(msoFileDialogFilePicker)
    With fileDialog
    .InitialFileName = “C:UsersUserDocuments”
    ‘.InitialFileName = ThisWorkbook.Path & ” ‘Alternative to previous line
    .AllowMultiSelect = False
    .Filters.Clear
    .Title = dialogTitle

    If .Show = False Then
    MsgBox “File not selected to import. Process Terminated”
    Exit Sub
    End If
    strPathFile = .SelectedItems(1)
    End With

    Set wbSource = Workbooks.Open(Filename:=strPathFile)
    Dim myRange As Range

    Set myRange = Application.InputBox(prompt:=”Please select the cell you want to copy”, Type:=8)
    Dim targetSheet As Worksheet
    Set targetSheet = wbSource.ActiveSheet

    ‘get the row of user select
    Set myRange = targetSheet.Range(targetSheet.Cells(myRange.Row, 1), targetSheet.Cells(myRange.Row, targetSheet.Columns.Count).End(xlToLeft))

    ‘copy data when there is an not empty cell in the range
    If WorksheetFunction.CountA(myRange) 0 Then
    Set rngDestin = ThisWorkbook.Sheets(“Data”).Cells(1, “A”)

    myRange.SpecialCells(xlCellTypeVisible).Copy Destination:=rngDestin
    End If

    wbSource.Close SaveChanges:=False

    Set fileDialog = Nothing
    Set rngRow = Nothing
    Set rngToCopy = Nothing
    Set wbSource = Nothing
    Set rngDestin = Nothing

    ‘MsgBox “The data is copied”

    End Sub

  67. Sarah
    November 18, 2015 at 10:04 AM — Reply

    Hi,

    I currently have two separate workbooks that get sent to two different customers with the exact same information. One has heading in Column A and data in Column B, while the other has Headings in Row 1, Data in Row 2. They also have different spacing so I can not directly transpose.

    Happy to fill in line by line but NEVER done code before and would really appreciate some help!

    This is what I have just from some attempts myself but keep getting errors.

    Would love some help!!
    Sub sbCopyRangeToAnotherSheet()

    Sheets(“Practice Details”).Range(“B1”).Copy Destination:=Sheets(“AMAL”).Range(“A2”)
    Sheets(“New Practice Setup ACS”).Range(“B2”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“B2”)
    Sheets(“New Practice Setup ACS”).Range(“B5”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“E2”)
    Sheets(“New Practice Setup ACS”).Range(“B6”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“F2”)
    Sheets(“New Practice Setup ACS”).Range(“B14”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“I2”)
    Sheets(“New Practice Setup ACS”).Range(“B15”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“J2”)
    Sheets(“New Practice Setup ACS”).Range(“B16”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“K2”)
    Sheets(“New Practice Setup ACS”).Range(“B17”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“L2”)
    Sheets(“New Practice Setup ACS”).Range(“B18”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“M2”)
    Sheets(“New Practice Setup ACS”).Range(“B21”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“N2”)
    Sheets(“New Practice Setup ACS”).Range(“B22”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“O2”)
    Sheets(“New Practice Setup ACS”).Range(“B23”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“P2”)
    Sheets(“New Practice Setup ACS”).Range(“B24”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“Q2”)
    Sheets(“New Practice Setup ACS”).Range(“B25”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“R2”)
    Sheets(“New Practice Setup ACS”).Range(“B26”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“S2”)
    Sheets(“New Practice Setup ACS”).Range(“B28”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“T2”)
    Sheets(“New Practice Setup ACS”).Range(“B29”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“U2”)
    Sheets(“New Practice Setup ACS”).Range(“B30”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“V2”)
    Sheets(“New Practice Setup ACS”).Range(“B31”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“W2”)
    Sheets(“New Practice Setup ACS”).Range(“B32”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“X2”)
    Sheets(“New Practice Setup ACS”).Range(“B44”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“Y2”)
    Sheets(“New Practice Setup ACS”).Range(“B47”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“AB2”)
    Sheets(“New Practice Setup ACS”).Range(“B50”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“AC2”)
    Sheets(“New Practice Setup ACS”).Range(“B51”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“AD2”)
    Sheets(“New Practice Setup ACS”).Range(“B52”).Copy Destination:=Sheets(“AMAL Notification_Practice Set Up”).Range(“AE2”)

    End Sub

  68. vivek
    January 9, 2016 at 8:54 PM — Reply

    hi
    i am school teacher who want to generate students individual marks report from all students general report with column data to be pasted on different row on separate worksheet using vba . Please Help me

    thanks in advance

  69. kaviani
    January 10, 2016 at 3:04 PM — Reply

    Your website helped me a lot today
    Thanks so much

  70. Joey
    January 15, 2016 at 1:10 AM — Reply

    I have a workbook that I use for my servers that I input their tips on daily. Is there a way to add the total tips from each workbook?

  71. Edwin
    January 29, 2016 at 8:37 PM — Reply

    PNRao, your comments helped me a lot to figure out the mess i was in.
    Thanks a lot. Good job guys.

  72. PNRao
    January 30, 2016 at 11:25 PM — Reply

    Thanks and you are welcome!-PNRao!

  73. Jaiprasad
    April 20, 2016 at 8:21 PM — Reply

    Hi PNRao,

    This code helped me a lot on simplifying my excel work but have one issue where the updated data on the second sheet needs needs to be the most recent once ( Instead o. How can I do that? Please let me know if you have a code to that. Thank you

  74. etusch
    May 18, 2016 at 7:26 PM — Reply

    HI
    For example ı have an excel sheet containing many data. I need to choose all rows containing turkey word and make all these rows yellow.

  75. Ritam Biswas
    June 5, 2016 at 8:52 PM — Reply

    Hi,
    I would you thank you for shearing these useful codes…
    I have a query, if you could help me out I would be grateful..
    How can I use your copy method on a daily basis..Lets say If same cell value is equal to today’s date then copy within the predefined rang…
    Thanks in advance.
    Waiting for your expert advise..
    Ritam

  76. vinay
    July 13, 2016 at 12:29 AM — Reply

    Hi,
    I have two workbook. X and Y. I want to copy data from closed workbook containing text data X range A1: R53 into Y A1: R53 as number data. X file will keep changing as the data is exported from the web.

    Thank you.

  77. Spencer T
    July 26, 2016 at 8:00 PM — Reply

    Hi all,
    Long time since I played with VBA, now trying to write code to copy order requirements from multiple worksheets to a master if someone enters a value in the Order_Qty column.
    Have tried several different ways and it falls over!

    1st sheet in workbook is Order_Sheet. Currently blank from row 11 down.
    Only 4 columns in use at the moment, Item_Number, Descriptio, RRP and Order_Qty.

    2nd sheet (Group_A), same titles in A1:D1
    15 Items listed, with description and RRP.
    Customer to enter Qty’s required in Column D.

    3rd sheet (Group_B) as per Group_A.

    4th sheet (Group_C) as per Group_A, but only 10 items.

    Any Help Appreciated.

  78. Rakesh
    September 2, 2016 at 3:37 PM — Reply

    Hi I have n no. Of sheets in my workbook. In this I am using find function with unique value or name once I found I have copy the data of entire row and paste in the previously worked sheet where I started using find.
    Eg.i have 30 sheets in a work book…currently I was in sheet 2. I am using find function to find $10000 and I have found the amount in 25th sheet here I have copy the entire row of $10000 and paste it to sheet2. Kindly share macro code for this thanks rakesh

  79. Khushbu
    September 2, 2016 at 9:04 PM — Reply

    Hi,
    I am khushbu. I want to develop VBA code so that it automatically transfer the data from different excel to one master excel file. Master file and other excel has same format. I have to send master file to different centers so that they update their project details in it by filtering their centres. There is total of 20 centres so I always get 20 excel files from different centers. Please help me for it.

  80. M.Ramesh
    September 7, 2016 at 4:42 PM — Reply

    Hi all ,
    I am new to excel VBA. I have a one task. we have a average program running time for several subsystems for each month.each month’s data will be in seperate sheets in a same workbook. what I have to do is I want to copy each month’s data from the workbook and I have to paste it in the different workbook which contains only single worksheet. note that there are 5 columns for each month data. There should be one column left blank between each month’s data. This code should work when I add a next month data in the data worksheet. Can anyone help me in resolving this.

  81. Shuyun
    September 10, 2016 at 9:47 AM — Reply

    Hey. I am new in VBA code and I need help for the following situation.

    I have one Workbook with two worksheets, one is “Source” and another one is “Target”.

    I need to copy the data in “Source” and paste into “Target”. However, the problem is I have over 20 part codes with different shipment dates and shipment quantities in “Source” and I need to match the same part code in “Target” and paste the shipment quantity under specified shipment date.

    I need to loop this operation for 20 part codes.

    Any help would be appreciated. Thanks.

  82. Maggy Hoebrechts
    September 28, 2016 at 9:13 PM — Reply

    I got an excel sheet with data.
    Each 93th row I need to insert 4 rows (easy with a macro) an in those four rows I need to copy a set of formulas repeatedly.
    How do I do this?

    Thanks

    Maggy

  83. Carl Anthony
    October 22, 2016 at 1:07 PM — Reply

    Hi,

    I want to copy data from one worksheet to another continuously.

    The source data named “Book1” and the target named “Data List” where I want to paste it.

    Book1 has 2 worksheets. But only the data on “sheet1” What I want to paste in “Data List”.
    In “sheet1” the range I want to copy is from A2:D101 but I want to copy only the active cells in that given range.

    In “Data List” I have only one active worksheet named “Item List” where I want to paste the data.
    The range where I want to paste it is from column A2:D2 continuously.

    Thanks in advance.

    Best Regards,
    Carl Anthony Navarro

  84. Faris
    November 23, 2016 at 3:18 AM — Reply

    Thx for this tutorial … this is work for me … I use the second method

  85. gowtham
    December 6, 2016 at 3:28 PM — Reply

    Hi,

    Am trying to copy the data from sheet1 to sheet 2 using vb script but what were code i have written it is not capturing and also not getting error.

    My question is in the sheet1 i will update the data (ex-100records) the same data should copy to next sheet, also if i did some modification in sheet1 and clicked on copy button it should replace the previous records.

  86. mahesh
    December 6, 2016 at 9:11 PM — Reply

    Hi,
    I need the same VBA code but you have mentioned for different workbooks but in a single workbook itself i had 12 sheets in that specific columns(B,J,M,U,V) need to selected so pls say the changes to copy and paste in another seperate workbook.

    Thanks in advance

  87. varun
    January 6, 2017 at 8:09 AM — Reply

    i am varun and i want to extract phone number (10-digit number) from multiple text files(1000) to excel one sheet using macro vba

  88. George Thomas
    January 17, 2017 at 3:40 PM — Reply

    I’m new to VBA and when I try to copy from one sheet to another I get error 400 or Object required.
    This it he VBA I used
    Sub sbCopyRangeToAnotherSheet()

    Sheets(“Dec-Bills”).Range(“o1”).Copy Destination:=Sheets(“Jan-Bills”).Range(“C1”)
    End Sub

  89. Ramya
    February 20, 2017 at 10:10 PM — Reply

    Hi,

    I wanted to copy a name from sheet 2 and search the same in sheet 1 and if there is any match i want the macro to highlight the cell in sheet 2 with green colour, can you please help me with this.

    Regards
    Ramya

  90. Mar
    February 22, 2017 at 9:54 PM — Reply

    Hi, I have a workbook where I am building statistics between myself and a colleague.
    I would like to be able to pull the full data from our two individual worksheets to a “Full Report/Master Report” sheet that is complete data from both our worksheets. Now, since the labels are identical I would only need the raw data to transfer over, this so we can have a pivot table connected to the “Full report” that shows our full data. Everything is in the same workbook but on diffrent sheets, Is this possible?

  91. dhruv khabya
    March 5, 2017 at 7:50 PM — Reply

    in one excel workbook I have 5 sheets (office, factory,field, mines,Master_sheet)
    In each sheet i have data of visitors with ID, NAME, CONTACT_NO
    Every day I have to add data in first 4 sheets..
    how to update the data automatically to the master sheet simultaneously while entering data….
    please help me…
    I have used you code:
    Sheets(“Sheet1”).Range(“A1:B10”).Copy Destination:=Sheets(“Sheet2”).Range(“E1”)
    but in my case the data must be enter in the new line from all sheets…
    in above case the data is getting overlapped

  92. Nichole Drouin
    June 4, 2017 at 5:39 PM — Reply

    So I’m trying to transfer data from sheet 2 to sheet 1 but here is the kicker. I need the info from sheet 2 cell B1 to transfer to sheet 1 cell G2. But, cell A1, sheet 2 needs to match sheet 1 cell A2. I have no idea on how to do this and there is a full sheet of this. Can anyone help me? If you need to see the Excel Spreadsheet, let me know so I can send it. Thanks1

  93. Vishal Mathur
    July 24, 2017 at 1:57 PM — Reply

    Hi, i have a scenario which i would like to automate. Any help would be appreciated.
    So i receive a file daily with several tabs(10), in which i have different fields. Now i have to copy the data from all the tabs of the workbook mostly the A Column(there could be any number of lines in that ranging from 5 to 100) and so on in other tabs.now all the data from this workbook needs to be copied to to a new workbook with(current date will be the name of the file), and copy all the data in that workbook(Sheet1).

  94. R Krishnan
    January 30, 2018 at 10:46 AM — Reply

    Hai
    I am a employee of acompany, I would like to get your help as follows.,

    I have a work book on which there are sheet1 and sheet2 with our damage items lists.
    There is a sheet called ” Bill” which is having a format.
    We have to conduct a seconds mela, so that when a customer selects the products from the list, we have to make a bill with customer address and other details including items code and item diescription with price details as per format in Bill.
    What I needed is
    1. After taking first invoice, (Bill) Address and all items selected are to be stored in another work sheet in a row, as follows

    Customer name, address, sl no, items code, decsription, qty, value bill amount, GST etc. then again next item if any

    On running the macro button, I have done clear contents of invoice details for entering another customer details.

    So i want details of customer as a databse, in another sheet before another bill is taken

    I can forward the excel work book so that you can do necessary correction and help

    Regards
    Krishnan, Trivandrum Kerala

  95. ajit rikibe
    August 13, 2018 at 2:58 PM — Reply

    Hello,
    I want to copy specific cell from one workbook to another workbook.
    How to do this with using macro ??

  96. Shubh
    September 16, 2018 at 8:33 PM — Reply

    Hii

    I have 1 workbook, name of workbook is t.xlsm, data is in “Sheet1” from A1:D10

    I need to copy this in multiple workbook’s whenever i want. Plz help me with the code

  97. Nur Asleena Binti Alaudin
    June 14, 2019 at 11:29 AM — Reply

    Hi. My name is Leena.

    I have a question related this excel VBA Macro. For example i have 10 folders. Inside the 10 folders have many subfolders together with 3 pdf files. Everytime i have to copy one specific pdf file from each of the folder and paste all in one separate folder. The pdf file name will be different for each folder. This will take some time if i have more than 10 or 20 folders. I plan to automate it. Can you guide through the coding of how to create it.

  98. Pravin
    July 5, 2019 at 12:28 PM — Reply

    Dear sir, I need to export data from one workbook to another. Source file name should be written in particular cell and destination file name also be written in particular cell. data range is from E4:O (data range will be more or less but column range will be fixed. secondly if column F has value more than zero then data will be exported. please help me. Please ask me if you need more explanation what I need.

  99. David Holland
    October 28, 2019 at 6:33 PM — Reply

    I want change the value of a cell on one sheet depending on the value in a cell of a different sheet. I have the following code:

    Worksheets(“Sheet2”).Range(“C5”) = Worksheets(“Sheet2”).Range(“C5”) – Worksheets(“Sheet1”).Range(“A17”)

    This works fine but I need to do this for multiple rows ( C%:C32 and A17:A44 )

    Can I put this in a loop to avoid repeating the code for each row?

  100. Sunil Joshi
    November 10, 2020 at 5:11 PM — Reply

    I have 1 workbook name abc.xlsm on desktop and another workbook on some drive, placed under folder “Name”. Where folder name is Dynamic. We can change folder name with the help of textbox on abc workbook.
    So please tell me the code to copy data fron file placed on Name folder to abc file

  101. Steve
    March 17, 2023 at 10:46 AM — Reply

    Hi!

    Using the Code above, I am trying to change the Criteria, to be based on the value of a drop down box in another sheet (created using an Offset/PivotTable in Data Validation,

    I cannot seem to simply reference the cell.

    It always fails at the part shown below.

    In “Sheet9”, I want it to find the rows which contain the Value of the Dropdown box (E6) from “Sheet12”, then paste them into “Sheet2”

    If Sheets(“Sheet9”).Range(“C” & j) = (**Needed to reference, E6 in Sheet12, which is a Dropdown box made**) Then
    cRow = Sheets(“Sheet2”).Range(“A500”).End(xlUp).Row
    Sheets(“Sheet9”).Rows(j).Copy Destination:=Sheets(“Sheet2”).Range(“A” & cRow + 1)

    For the life of me I can’t get it to work

    Any help greatly appreciated!

    • PNRao
      March 18, 2023 at 11:59 AM — Reply
      If Sheets("Sheet9").Range("C" & j) = Sheets("Sheet12").Range("E6") Then
      cRow = Sheets("Sheet2").Range("A100000").End(xlUp).Row
      Sheets("Sheet9").Rows(j).Copy Destination:=Sheets("Sheet2").Range("A" & cRow + 1)
      End If
      

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

Создание, копирование, перемещение и удаление рабочих листов 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, смотрите в этой статье.

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

Like this post? Please share to your friends:
  • Excel vba copy paste special
  • Excel vba copy method failed
  • Excel vba copy hyperlink
  • Excel vba copy cell and paste
  • Excel vba copy all sheets to one sheet