简体   繁体   中英

Copy multiple tabs into a new workbook, paste as values

I have code to paste several tabs in. However, I'm not sure how to paste them as values without altering the source code as little as possible.

I think it's currently using the default of .Copy copying into a new workbook, so I think I may have to declare the new workbook explicitly, but not sure.

Sub ExportTabs(Boro As String)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'ExportTabs
'This subroutine exports separate tabs into new workbooks. It will take in a borough and export it into a workbook,
'saved in the same directory as the master workbook. The export will be a copy paste
'of values and formatting.
'
'Parameters: Boro (String)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

'Step 1:    Declare your variables
    Dim MasterFile As Workbook
    Dim FileName As String
    Dim LeadingText As String
    Dim DateT As String


'Step 2:    Set file name strings, including hard-coding the header text
    LeadingText = "Completion Report - "
    DateT = Format(DateTime.Date, "MM-dd-yy")


'Step 3:    Find active workbook and relevant sheet, and copy and save with new file name
    Set MasterFile = ActiveWorkbook
    FileName = MasterFile.Path & "\" & LeadingText & DateT & " " & Boro & ".xlsx"
    MasterFile.Sheets(Array(Boro & " Completion Report", Boro & " Summary", "About")).Copy
    ActiveWorkbook.SaveAs FileName, FileFormat:=51

'Step 4:    Close new workbook
    ActiveWorkbook.Close

End Sub

I ended up altering the code under Step 3 to this:

    Set MasterFile = ActiveWorkbook
    FileName = MasterFile.Path & "\" & LeadingText & DateT & " " & Boro & ".xlsx"
    MasterFile.Sheets(Array(Boro & " Completion Report", Boro & " Summary", "About")).Copy
    For Each sht In ActiveWorkbook.Sheets
        'Only copy and paste as values in Summary tab
        If sht.Name = Boro & " Summary" Then
            sht.UsedRange.Copy
            sht.UsedRange.PasteSpecial xlValues
            sht.UsedRange.PasteSpecial xlFormats
        End If
    Next sht
    ActiveWorkbook.SaveAs FileName, FileFormat:=51

I found out that .Copy copies to a new workbook Excel recognizes as ActiveWorkbook , so you can change the workbook from there. The only way to paste as values seems to be the .PasteSpecial xlValues method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM