Copy, Paste Value, Save Worksheet - Multiple Worksheets - excel

I have a workbook with many worksheets. I am attempting to use the below macro to cycle the worksheets, copy and paste value, then save off individually in a location.
I feel like I'm glossing over something very small and beginning to go bonkers. Currently this code copies and pastes value the first worksheet, and then saves the rest off without the copy/paste. So everything is working as desired with the exception of the copy/paste value not occurring with each worksheet.
Sub SaveFilesInFolder()
'
'This is for saving each worksheet as a workbook in a destination folder as an excel file
'
'
Dim sh As Worksheet
Dim wb As Workbook
For Each sh In Worksheets
With ActiveWorkbook
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
SheetName = sh.Name
sh.Copy
.SaveAs Filename:="C:\Location\" & SheetName
.Close SaveChanges:=True
End With
Next sh
End Sub
Any and all assistance is greatly appreciated.
Edit:
Below is the updated code from comments. Unfortunately, the sheet is still copying/pasting for the first worksheet and not the rest. Everything is saving in the specified location as intended.
Sub SaveFilesInFolder()
'
'This is for saving each worksheet as a workbook in a destination folder as an excel file
'
'
Dim sh As Worksheet
Dim wb As Workbook
Dim rng As Range
For Each sh In ThisWorkbook.Worksheets
Set rng = Cells
rng.Copy
rng.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
sh.Copy
ActiveWorkbook.SaveAs ("C:\Location\" & sh.Name)
ActiveWorkbook.Close
Next sh
End Sub

Try it without the clipboard. I've also turned off alerts (for saving over files) and done a small amount of clean up.
Sub SaveFilesInFolder()
'
'This is for saving each worksheet as a workbook in a destination folder as an excel file
'
'
On Error GoTo e
Application.DisplayAlerts = False
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
With sh.UsedRange
.Value2 = .Value2
End With
sh.Copy
ActiveWorkbook.Close True, "C:\Location\" & sh.Name
Next sh
e:
' Ensure alerts are turned back on before re-throwing.
Application.DisplayAlerts = True
If Err > 0 Then Err.Raise Err
End Sub

Export Worksheets
To leave the source workbook intact, convert formulas to values in the destination workbooks.
Sub ExportWorksheets()
Const dFolderPath As String = "C:\Location\"
Dim swb As Workbook: Set swb = ThisWorkbook
Dim dPath As String: dPath = dFolderPath
If Right(dPath, 1) <> Application.PathSeparator Then
dPath = dPath & Application.PathSeparator
End If
Application.ScreenUpdating = False
Dim sws As Worksheet
Dim dwb As Workbook
Dim dws As Worksheet
Dim drg As Range
For Each sws In swb.Worksheets
sws.Copy ' copied to a new single-worksheet workbook
Set dwb = Workbooks(Workbooks.Count) ' the last
Set dws = dwb.Worksheets(1) ' the one and only
Set drg = dws.UsedRange
drg.Value = drg.Value ' formulas to values
Application.DisplayAlerts = False ' to overwrite without confirmation
dwb.SaveAs dPath & dws.Name
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False ' it's already been saved
Next sws
Application.ScreenUpdating = True
MsgBox "Worksheets exported to single-worksheet workbooks.", vbInformation
End Sub

Related

How to save the selected worksheet without specifying sheet name or number

Is there a way to save the active/selected worksheet without having to specify sheets(1)?
The code below is execute via command button and will take the worksheet "Quote" copy to a new workbook, and then prompt to save under the downloads directory.
I'm also trying to get that button to save whichever sheet is selected, it could be Quote or Sheet1, but not both.
Private Sub CommandButton4_Click() ' save worksheet
'Gets the name of the currently visible worksheet
Filename = ActiveSheet.Name
'Puts the worksheet into its own workbook
ThisWorkbook.ActiveSheet.Copy
'Saves the workbook - uses the name of the worksheet as the name of the new workbook
'Filename = Range("A1")
'ActiveWorkbook.Save
Dim NameFile As Variant
With Worksheets("Quote")
'NameFile = .Range("A1") & "_" & .Range("B5") & "_" & ".xls"
End With
NameFile = Application.GetSaveAsFilename(InitialFileName:=Environ("USERPROFILE") & "\Downloads\" & NameFile, Filefilter:="Fichier Excel (*.xls), *.xls")
If NameFile = False Then
MsgBox "File not saved"
Else
ActiveWorkbook.SaveAs Filename:=NameFile
End If
'Closes the newly created workbook so you are still looking at the original workbook
ActiveWorkbook.Close
End Sub
This Sub creates a new Workbook from a sheet. But you must have a way to call this Sub of every sheet, or a better place is a button in the ribbon witch in it's handler: Call NewBookOfSheet(ActiveSheet).
Public Sub NewBookOfSheet(ws As Worksheet)
Dim nwb As Workbook, curwb As Workbook
If ws Is Nothing Then Exit Sub
Set curwb = ws.Parent
Set nwb = Workbooks.Add
curwb.Activate
ws.Select
ws.Copy Before:=nwb.Sheets(1)
nwb.Activate
Application.Dialogs(xlDialogSaveAs).Show ws.Name
End Sub
Copy the Active Worksheet to a New Workbook
Private Sub CommandButton4_Click() ' save worksheet
If ActiveSheet Is Nothing Then Exit Sub ' no visible workbooks open
If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
Dim sws As Worksheet: Set sws = ActiveSheet
sws.Copy
Dim dwb As Workbook: Set dwb = Workbooks(Workbooks.Count)
Dim dws As Worksheet: Set dws = dwb.Sheets(1) ' the one and only
Dim dwbName: dwbName = Application.GetSaveAsFilename( _
InitialFileName:=Environ("USERPROFILE") & "\Downloads\" & dws.Name, _
FileFilter:="Fichier Excel (*.xls), *.xls")
If dwbName = False Then
MsgBox "File not saved", vbCritical
Else
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs Filename:=dwbName, FileFormat:=xlWorkbookNormal
Application.DisplayAlerts = True
End If
dwb.Close SaveChanges:=False
' Now 'dws' and 'dwb' are invalid but still 'Not Nothing'.
' On the other hand, 'sws' still points to the (initial) source worksheet.
' If you need to reference the source workbook use:
'Dim swb As Workbook: Set swb = sws.Parent
End Sub

I'm trying to copy and paste a specific range for multiple worksheets, each with a different name, into a new workbook with defined worksheets names

I have this macro codes which allow me to copy and paste specific range of one worksheet into a new workbook (both excel and pdf). I need to do the same but for multiple worksheets all at once. How do I modify this code.
Sub SaveData()
' Declare objects
Dim sourceWorkbook As Workbook
Dim targetWorkbook As Workbook
Dim sourceRange As Range
Dim targetRange As Range
Dim cellRange As Range
' Declare other variables
Dim targetWorkbookName As String
Dim targetWorkbookTitle As String
Dim sourceSheetName As String
Dim sourceRangeAddress As String
Dim targetRangeAddress As String
Dim rowCounter As Long
' <<< Customize this >>>
sourceSheetName = "ATP620" ' Name of the source sheet
sourceRangeAddress = "D3:AU197" ' Address of the range you want to copy in the source workbook
targetRangeAddress = "A1" ' Cell address where you want to paste the copied range
targetWorkbookTitle = "ATP620 WP&B 2023" ' Base file name
' Reference source workbook
Set sourceWorkbook = ThisWorkbook
' Create a new workbook
Set targetWorkbook = Application.Workbooks.Add
' Set reference to source range
Set sourceRange = sourceWorkbook.Sheets(sourceSheetName).Range(sourceRangeAddress)
' Copy the range to clipboard
sourceRange.Copy
' This copies the range in the first available worksheet begining in the cell address specified
targetWorkbook.Sheets(1).Range(targetRangeAddress).PasteSpecial Paste:=xlPasteValues
targetWorkbook.Sheets(1).Range(targetRangeAddress).PasteSpecial Paste:=xlPasteFormats
targetWorkbook.Sheets(1).Range(targetRangeAddress).PasteSpecial Paste:=xlPasteColumnWidths
Set targetRange = targetWorkbook.Sheets(1).Range(targetRangeAddress).Resize(sourceRange.Rows.Count, sourceRange.Columns.Count)
' Adjust row heights
For Each cellRange In sourceRange.Columns(1).Cells
rowCounter = rowCounter + 1
targetRange.Rows(rowCounter).RowHeight = cellRange.RowHeight
Next cellRange
' Set the name of the new workbook
targetWorkbookName = Application.GetSaveAsFilename(InitialFileName:=targetWorkbookTitle, _
fileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
' Simultanously export the new workbook into pdf format and set filename the same as the new workbook
sourceRange.ExportAsFixedFormat Type:=xlTypePDF, Filename:=targetWorkbookName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
If targetWorkbookName = vbNullString Then
MsgBox "Saving operation canceled"
Exit Sub
End If
' Save the new workbook
targetWorkbook.SaveAs Filename:=targetWorkbookName ' Un comment this if you want it in OpenXML format: , FileFormat:=xlOpenXMLWorkbook
End Sub
Export a Range
Utilization
Sub ExportDataTEST()
Dim Exceptions() As Variant: Exceptions = Array("Sheet1", "Sheet2")
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet
For Each ws In wb.Worksheets
If IsError(Application.Match(ws.Name, Exceptions, 0)) Then
ExportData ws, "D3:AU197", " WP&B 2023"
End If
Next ws
End Sub
The Method
Sub ExportData( _
ByVal SourceWorksheet As Worksheet, _
ByVal SourceRangeAddress As String, _
ByVal TargetNameSuffix As String)
Const PROC_TITLE As String = "Export Data"
' Reference the Source range.
Dim srg As Range: Set srg = SourceWorksheet.Range(SourceRangeAddress)
' Create and reference a new single-worksheet workbook, the Target workbook.
Dim twb As Workbook: Set twb = Application.Workbooks.Add(xlWBATWorksheet)
' Reference the Target worksheet.
Dim tws As Worksheet: Set tws = twb.Sheets(1) ' the one and only
' Copy/paste.
srg.Copy
With tws.Range("A1")
.PasteSpecial Paste:=xlPasteValues
.PasteSpecial Paste:=xlPasteFormats
.PasteSpecial Paste:=xlPasteColumnWidths
End With
' Adjust the row heights.
Dim sCell As Range, r As Long
For Each sCell In srg.Columns(1).Cells
r = r + 1
tws.Rows(1).RowHeight = sCell.RowHeight
Next sCell
' Get the path of the new workbook.
Dim tBaseName As String: tBaseName = ws.Name & TargetNameSuffix
Dim tPath As Variant: tPath = Application.GetSaveAsFilename( _
InitialFileName:=tBaseName, _
FileFilter:="Excel Workbooks (*.xlsx),*.xlsx")
If VarType(tPath) = vbBoolean Then
MsgBox "Saving operation canceled", vbExclamation, PROC_TITLE
twb.Close SaveChanges:=False
Application.CutCopyMode = False
Exit Sub
End If
' Save the new workbook.
Dim ErrNum As Long
Dim ErrDescription As String
Application.DisplayAlerts = False ' overwrite without confirmation
On Error Resume Next ' e.g. workbook with same name is already open
twb.SaveAs Filename:=tPath
ErrNum = Err.Number
ErrDescription = Err.Description
On Error GoTo 0
Application.DisplayAlerts = True
If ErrNum <> 0 Then
MsgBox "Run-time error '" & ErrNum & vbLf & vbLf & ErrDescription, _
vbCritical, PROC_TITLE
Exit Sub
End If
twb.Close SaveChanges:=False ' just got saved
' Export to PDF.
srg.ExportAsFixedFormat Type:=xlTypePDF, Filename:=tBaseName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End Sub

Excel VBA copying specified set of worksheets to new workbook/excluding sheet from copy

I am trying to copy only data from one workbook into a new one, but with only four of the existing worksheets. The code below allows me to successfully copy all worksheets to a new workbook. This worked fine before, but now I only want to copy sheet 2-7, thus excluding sheet 1.
This is done by a user copying data into sheet 1 and the data will be populated to sheets 2-5. Sheet 6 & 7 contains metadata which will be the same for all new workbooks. To be able to import the copied data, I need a new workbook with sheets 2-7.
Sub Button1_Click()
Dim Output As Workbook
Dim Current As String
Dim FileName As String
Set Output = ThisWorkbook
Current = ThisWorkbook.FullName
Application.DisplayAlerts = False
Dim SH As Worksheet
For Each SH In Output.Worksheets
SH.UsedRange.Copy
SH.UsedRange.PasteSpecial xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Next
FileName = ThisWorkbook.Path & "\" & "Generic name.xlsx" 'Change name as needed
Output.SaveAs FileName, XlFileFormat.xlOpenXMLWorkbook
Workbooks.Open Current
Output.Close
Application.DisplayAlerts = True
End Sub
Any suggestions on how improve the code to only copy specified sheets, or to exclude sheet 1?
Copy a Set of Worksheets to Another Workbook
Option Explicit
Sub Button1_Click()
' Constants
Const dFileName As String = "Generic name.xlsx"
Dim DoNotCopy As Variant: DoNotCopy = Array(1) ' add more: Array(1, 7, 8)
Const ConversionWorksheetsCount As Long = 4
' Write the names of the desired worksheets to an array.
Dim swb As Workbook: Set swb = ThisWorkbook
Dim swsCount As Long: swsCount = swb.Worksheets.Count
Dim dwsNames() As String: ReDim dwsNames(1 To swsCount)
Dim sws As Worksheet
Dim sCount As Long
Dim dCount As Long
For Each sws In swb.Worksheets
sCount = sCount + 1
If IsError(Application.Match(sCount, DoNotCopy, 0)) Then
dCount = dCount + 1
dwsNames(dCount) = sws.Name
' Else ' worksheet index found in the 'DoNotCopy' array.
End If
Next sws
If dCount = 0 Then
MsgBox "No worksheets found.", vbCritical
Exit Sub
End If
If dCount < swsCount Then
ReDim Preserve dwsNames(1 To dCount)
End If
Application.ScreenUpdating = False
' Copy the desired worksheets to a new (destination) workbook.
swb.Worksheets(dwsNames).Copy
Dim dwb As Workbook: Set dwb = ActiveWorkbook
' Do the conversions.
Dim dws As Worksheet
Dim n As Long
For n = 1 To ConversionWorksheetsCount
On Error Resume Next
Set dws = dwb.Worksheets(n)
On Error GoTo 0
If Not dws Is Nothing Then ' destination worksheet exists
dws.Activate ' needed for '.Cells(1).Select'
With dws.UsedRange
.Copy
.PasteSpecial xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
.Cells(1).Select ' cosmetics
End With
Set dws = Nothing
'Else ' destination worksheet doesn't exist
End If
Next n
'dwb.Worksheets(1).Activate ' cosmetics
' Save the new (destination) workbook.
Dim dFilePath As String: dFilePath = swb.Path & "\" & dFileName
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs dFilePath, xlOpenXMLWorkbook
Application.DisplayAlerts = True
dwb.Close
' Note that you never modified the source. It's in the same state as before.
Application.ScreenUpdating = True
MsgBox "Workbook created.", vbInformation
End Sub
Add an If statement after the For Each loop to exclude Sheet1:
For Each SH In Output.Worksheets
If SH.Name <> "Sheet1" Then
SH.UsedRange.Copy
SH.UsedRange.PasteSpecial xlPasteValuesAndNumberFormats, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
End If
Next

VBA Import data from external worksheet - variable worksheet name

I'm looking to do the following:
CommandButton in a destination Worksheet opens a source file (dialog box to choose which one)
Finds a worksheet (always the same name - "Performance") within the source file
Copies a range of cells (actually a couple of separate ranges - to be added)
Makes sure destination sheet (which has the same name as cell I2 in source sheet) exists
Pastes values to same ranges in destination Worksheet
Closes source file
I have this so far:
Private Sub CommandButton1_Click()
Dim SourceFile As String
Dim SourceBook As Workbook
Dim DestinationBook As Workbook
Dim desiredName As String
Set DestinationBook = ThisWorkbook
SourceFile = Application.GetOpenFilename(fileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
Set SourceBook = Workbooks.Open(SourceFile)
SourceBook.Sheets("Performance").Activate
desiredName = ActiveSheet.Range("I2")
Application.CutCopyMode = True
SourceBook.ActiveSheet.Range("E25:I64").Copy
DestinationBook.Activate
If WorksheetExists = False Then
MsgBox "Couldn't find " & desiredName & " sheet within destination workbook"
Call SourceBook.Close(False)
Exit Sub
Else
Range("E25:I64").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Call SourceBook.Close(False)
End If
End Sub
Function WorksheetExists() As Boolean
Dim sh As Object
For Each sh In DestinationBook.Worksheets
If sh.Name = desiredName Then WorksheetExists = True: sh.Activate
Exit For
Next
End Function
I'm getting Run-time error '424': Object Required
Any suggestions...?
Thanks in advance!
Here is a modification of your latest code. Notice these additions: 1) "Option Explicit" ensures you've properly declared all variables, 2) variables have been assigned to the important workbooks, worksheets, and ranges, 3) needed variables are passed to the WorkSheetExists function. For this to work there should be sheets named "Performance" and "testSheet" in the DestinationBook, and "testSheet" in I2 of the SourceBook. Remember, that this is just an attempt to "get you going" so I expect you'll need to modify.
Option Explicit
Sub test()
Dim SourceFile As String
Dim SourceBook As Workbook, performanceSh As Worksheet
Dim DestinationBook As Workbook
Dim desiredName As String
Set DestinationBook = ThisWorkbook
SourceFile = Application.GetOpenFilename(fileFilter:="Excel Macro-Enabled Workbook (*.xlsm), *.xlsm")
Set SourceBook = Workbooks.Open(SourceFile)
Set performanceSh = SourceBook.Sheets("Performance")
desiredName = performanceSh.Range("I2")
Application.CutCopyMode = True
performanceSh.Range("E25:I64").Copy
If WorksheetExists(DestinationBook, desiredName) = False Then
MsgBox "Couldn't find " & desiredName & " sheet within destination workbook"
SourceBook.Close(False)
Exit Sub
Else
Range("E25:I64").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
SourceBook.Close(False)
End If
End Sub
Function WorksheetExists(destWk As Workbook, theName As String) As Boolean
Dim sh As Object
For Each sh In destWk.Worksheets
If sh.Name = theName Then WorksheetExists = True: sh.Activate
Exit For
Next
End Function

Copy values only to new workbook from multiple worksheets

Suppose I have a workbook1.xlsm with multiple worksheets and full of various formulas. I want to create a new workbook2.xlsx which would look exactly the same as workbook1 but in all the cells would be values instead of formulas.
I have this macro to copy one sheet from workbook1:
Sub nowe()
Dim Output As Workbook
Dim FileName As String
Set Output = Workbooks.Add
Application.DisplayAlerts = False
ThisWorkbook.Worksheets("Przestoje").Cells.Copy
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormats
FileName = ThisWorkbook.Path & "\" & "worksheet2.xlsx"
Output.SaveAs FileName
End Sub
but the problem is it copies only one worksheet and does not name it like it was in worksheet1. I cannot figure it out.
Yet another problem is that worksheet2 is being opened afterwards. I do not want to do this.
How can I solve these problems?
I would do that as simply as possibly, without creating new workbook and copying sheets to it.
Few simple steps: taking into consideration thisworkbook >> for each worksheet within thisworkbook >> copy+paste values of used range within worksheet >> save as new workbook as xlsx type >> open back base workbook >> and finally close one we created.
The code will be simple and looks as follows:
Sub nowe_poprawione()
Dim Output As Workbook
Dim Current As String
Dim FileName As String
Set Output = ThisWorkbook
Current = ThisWorkbook.FullName
Application.DisplayAlerts = False
Dim SH As Worksheet
For Each SH In Output.Worksheets
SH.UsedRange.Copy
SH.UsedRange.PasteSpecial xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Next
FileName = ThisWorkbook.Path & "\" & "worksheet2.xlsx"
Output.SaveAs FileName, XlFileFormat.xlOpenXMLWorkbook
Workbooks.Open Current
Output.Close
Application.DisplayAlerts = True
End Sub
This should allow you to keep all the formatting, column widths, and only the values.
Option Explicit
Sub copyAll()
Dim Output As Workbook, Source As Workbook
Dim sh As Worksheet
Dim FileName As String
Dim firstCell
Application.ScreenUpdating = False
Set Source = ActiveWorkbook
Set Output = Workbooks.Add
Application.DisplayAlerts = False
Dim i As Integer
For Each sh In Source.Worksheets
Dim newSheet As Worksheet
' select all used cells in the source sheet:
sh.Activate
sh.UsedRange.Select
Application.CutCopyMode = False
Selection.Copy
' create new destination sheet:
Set newSheet = Output.Worksheets.Add(after:=Output.Worksheets(Output.Worksheets.Count))
newSheet.Name = sh.Name
' make sure the destination sheet is selected with the right cell:
newSheet.Activate
firstCell = sh.UsedRange.Cells(1, 1).Address
newSheet.Range(firstCell).Select
' paste the values:
Range(firstCell).PasteSpecial Paste:=xlPasteColumnWidths
Range(firstCell).PasteSpecial Paste:=xlPasteFormats
Range(firstCell).PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Next
' delete the sheets that were originally there
While Output.Sheets.Count > Source.Worksheets.Count
Output.Sheets(1).Delete
Wend
FileName = ThisWorkbook.Path & "\" & "worksheet2.xlsx"
Output.SaveAs FileName
Output.Close
Application.ScreenUpdating = True
End Sub
Something like this would work to cycle through and copy all sheets after adding the workbook:
dim i as integer
For i = 1 To ThisWorkbook.Worksheets.Count
ThisWorkbook.Worksheets(i).Activate
ThisWorkbook.Worksheets(i).Select
Cells.Copy
Output.Activate
Dim newSheet As Worksheet
Set newSheet = Output.Worksheets.Add()
newSheet.Name = ThisWorkbook.Worksheets(i).Name
newSheet.Select
Cells.Select
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Next
Note that this doesn't handle removing default sheets that automatically get created when the workbook gets created.
Also, worksheet2 is actually being opened (though not named til SaveAs) as soon as you call this:
Set Output = Workbooks.Add
Just close it after saving:
Output.Close
Something like this would work to cycle through and copy all sheets after adding the workbook - it builds on mr.Reband's answer, but with a few bells and whistles. Among other things it will work if this is in a third workbook (or an add-in etc), it deletes the default sheet or sheets that were created, it ensures the order of the sheets is the same as the original, etc:
Option Explicit
Sub copyAll()
Dim Output As Workbook, Source As Workbook
Dim sh As Worksheet
Dim FileName As String
Dim firstCell
Application.ScreenUpdating = False
Set Source = ActiveWorkbook
Set Output = Workbooks.Add
Application.DisplayAlerts = False
Dim i As Integer
For Each sh In Source.Worksheets
Dim newSheet As Worksheet
' select all used cells in the source sheet:
sh.Activate
sh.UsedRange.Select
Application.CutCopyMode = False
Selection.Copy
' create new destination sheet:
Set newSheet = Output.Worksheets.Add(after:=Output.Worksheets(Output.Worksheets.Count))
newSheet.Name = sh.Name
' make sure the destination sheet is selected with the right cell:
newSheet.Activate
firstCell = sh.UsedRange.Cells(1, 1).Address
newSheet.Range(firstCell).Select
' paste the values:
Range(firstCell).PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, SkipBlanks:=True, Transpose:=False
Next
' delete the sheets that were originally there
While Output.Sheets.Count > Source.Worksheets.Count
Output.Sheets(1).Delete
Wend
FileName = ThisWorkbook.Path & "\" & "worksheet2.xlsx"
Output.SaveAs FileName
Output.Close
Application.ScreenUpdating = True
End Sub

Resources