I am using this code which works fine but it also copies:
Formulas
Shapes
Macros embedded on Sheet
I am looking for a way to only copy the values of the sheet, whilst retaining their original formatting and then close the newly created workbook as my macro does.
Sub export_sheet()
Dim sourceWB As Workbook
Dim destWB As Workbook
Dim strSourceSheet As Worksheet
Dim strname As String
Dim path As String
Application.DisplayAlerts = False
path = ThisWorkbook.path & "\"
strname = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"
Set strSourceSheet = ActiveSheet
ThisWorkbook.Sheets(strSourceSheet).Copy
ActiveWorkbook.SaveAs Filename:=path & strname, FileFormat:=51, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Something like this should work for you:
Sub tgr()
Dim wb As Workbook
Dim wsCopy As Worksheet
Dim wsDest As Worksheet
Dim rFirst As Range
Dim rLast As Range
Dim rDest As Range
Dim sFolderPath As String
Dim sFileName As String
Set wb = ThisWorkbook
Set wsCopy = wb.ActiveSheet
Set rFirst = wsCopy.Cells.Find("*", wsCopy.Cells(wsCopy.Rows.Count, wsCopy.Columns.Count), xlValues, xlPart, , xlNext)
Set rLast = wsCopy.Cells.Find("*", wsCopy.Range("A1"), xlValues, xlPart, , xlPrevious)
sFolderPath = ThisWorkbook.Path & Application.PathSeparator
sFileName = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"
wb.Worksheets.Add.Move 'create new workbook with a blank worksheet
Set wsDest = ActiveWorkbook.ActiveSheet 'the newly created workbook and sheet will be active because they were just created
With wsDest
Set rDest = .Cells(rFirst.Row, rFirst.Column)
wsCopy.Range(rFirst, rLast).Copy
rDest.PasteSpecial xlPasteValues
rDest.PasteSpecial xlPasteFormats
rDest.PasteSpecial xlPasteColumnWidths
.Parent.SaveAs sFolderPath & sFileName, xlOpenXMLWorkbook
.Parent.Close True
End With
End Sub
Try this:
Sub export_sheet()
Dim sourceWB As String
Dim destWB As String
Dim strSourceSheet As String
Dim strname As String
Dim path As String
Application.DisplayAlerts = False
path = ThisWorkbook.path & "\"
strname = "test_" & Format(Now, "dd_mmm_yy_hh_mm_ss") & ".xlsx"
strSourceSheet = ActiveSheet.Name
sourceWB = Activeworkbook.Name
Sheets(strSourceSheet).Copy
‘If want to copy yo new wb
Workbooks.Add
DestWB = Activeworkbook.Name
‘Or if DestWb already exists then
‘DestWB = yourdestinationwb.xlsx
‘Windows(DestWB).Activate
‘Sheets(1).Select
Activesheet.Range(“A1”).SeLect
Selection.PasteSpecial Paste:=XlPasteValues
Selection.PasteSpecial Paste:=XlPasteFormats
ActiveWorkbook.SaveAs Filename:=path & strname, FileFormat:=51, CreateBackup:=True
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
Related
I am using this code which exports activesheet to CSV. However, I am looking to modify this so I can pass as arguments the names of multiple sheets to export.
Sometimes it could be 2 sheets, sometimes it could be 10 sheets and I want to somehow define the names of the sheets as parameters for the export.
Sub saveSheetToCSV()
Dim myCSVFileName As String
Dim tempWB As Workbook
Application.DisplayAlerts = False
On Error GoTo err
myCSVFileName = ThisWorkbook.Path & "\" & "CSV-Exported-File-" & VBA.Format(VBA.Now, "dd-MMM-yyyy hh-mm") & ".csv"
ThisWorkbook.Sheets("YourSheetToCopy").Activate
ActiveSheet.Copy
Set tempWB = ActiveWorkbook
With tempWB
.SaveAs Filename:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
err:
Application.DisplayAlerts = True
End Sub
Export Worksheet to New Workbook
!!! denotes places to be checked carefully and possibly modified.
Option Explicit
Sub ExportWorksheetsTEST()
Dim wb As Workbook: Set wb = Workbooks.Open("C:\Test\Test.xlsx")
ExportWorksheets "Sheet1", "Sheet5", "Sheet8"
End Sub
Sub ExportWorksheets(ParamArray WorkSheetNames() As Variant)
Dim dFolderPath As String: dFolderPath = ThisWorkbook.Path & "\"
Const dFileExtension As String = ".csv"
Const dDateFormat As String = "dd-MMM-yyyy hh-mm"
Const dFileNameDelimiter As String = "-"
' This is the requirement.
' The recommendation is to put it as the first parameter of the procedure:
' Sub ExportWorksheets(ByVal wb As Workbook, ParamArray...)!!!
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim dDateString As String: dDateString = VBA.Format(VBA.Now, dDateFormat)
Dim ws As Worksheet
Dim n As Long
Dim dFilePath As String
For n = LBound(WorkSheetNames) To UBound(WorkSheetNames)
On Error Resume Next ' prevent error if worksheet doesn't exist
Set ws = wb.Worksheets(WorkSheetNames(n))
On Error GoTo 0
If Not ws Is Nothing Then
' Build the file path!!!
dFilePath = dFolderPath & ws.Name & dFileNameDelimiter _
& dDateString & dFileExtension
ws.Copy ' copy to a new workbook
With Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite w/o confirmation
.SaveAs Filename:=dFilePath, FileFormat:=xlCSV
Application.DisplayAlerts = True
.Close SaveChanges:=False
End With
Set ws = Nothing
End If
Next n
MsgBox "Worksheets exported.", vbInformation
End Sub
Hi I have main excel file with 10 sheets (sheet1...sheet10), and i need help with extracting (create new folder with sheet name) sheet5 and sheet6 in folder which link is in sheet1 n6 cell, and sheet7 and sheet8 in folder which link is in sheet1 n7 cell.sheets must be extracted without macros and formulas, only paste as values. For now i only have this which is creating workbooks in main file folder, i dont know how to setup extracting in diferent folders.
Private Sub CommandButton2_Click()
Dim xWs As Worksheet
Dim xPath As String
xPath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox ("Done.")
End Sub
Export Single Worksheets to Workbooks
Option Explicit
Private Sub CommandButton2_Click()
Const lName As String = "Sheet1"
' The following two lines are dependent on each other.
Dim dExtension As String: dExtension = ".xlsx"
Dim dFileFormat As XlFileFormat: dFileFormat = xlOpenXMLWorkbook
Dim lCellAddresses As Variant: lCellAddresses = Array("N6", "N7")
Dim dNames As Variant: dNames = Array( _
Array("Sheet5", "Sheet6"), _
Array("Sheet7", "Sheet8"))
Dim swb As Workbook: Set swb = ThisWorkbook
Dim lws As Worksheet: Set lws = swb.Worksheets(lName)
Application.ScreenUpdating = False
Dim dwb As Workbook
Dim sws As Worksheet
Dim dFilePath As String
Dim n As Long
For Each sws In swb.Worksheets
For n = LBound(dNames) To UBound(dNames)
If IsNumeric(Application.Match(sws.Name, dNames(n), 0)) Then
sws.Copy
Set dwb = ActiveWorkbook
With dwb.Worksheets(1).UsedRange
.Value = .Value
End With
dFilePath = CStr(lws.Range(lCellAddresses(n)).Value)
If Right(dFilePath, 1) <> "\" Then dFilePath = dFilePath & "\"
If Left(dExtension, 1) <> "." Then dExtension = "." & dExtension
dFilePath = dFilePath & sws.Name & dExtension
Application.DisplayAlerts = False ' overwrite: no confirmation
dwb.SaveAs Filename:=dFilePath, FileFormat:=dFileFormat
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
Exit For
End If
Next n
Next sws
Application.ScreenUpdating = True
MsgBox "Worksheets exported.", vbInformation
End Sub
Hi I have the following code which loops through dropdown selections and saves each result as a new workbook based on the named range in cell G3. I am trying to edit the code so that it saves all the worksheets to the new file instead of just the active one, if anyone could help? thank you
Sub myFiles()
Dim wb As Workbook
Dim ws As Worksheet
Dim nwb As Workbook
Dim nws As Worksheet
Dim rng As Range
Dim Path As String
Dim myDate As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Summary")
Set rng = ws.Range("G3")
Path = "C:\Users\bradley\Desktop\Sales by Month\"
myDate = Format(Now(), "MM-DD-YYYY")
For i = 1 To 4
rng = ws.Range("J" & i)
ws.Copy
Set nwb = ActiveWorkbook
Set nws = nwb.Worksheets("Summary")
With nws
Cells.Copy
Cells.PasteSpecial (xlPasteValues)
End With
Application.DisplayAlerts = False
nwb.SaveAs FileName:=Path & rng & " " & myDate & ".xlsx",
FileFormat:=xlWorkbookDefault
nwb.Close
Application.DisplayAlerts = True
Next i
End Sub
Loop through the sheets but only create a workbook on the first one.
Option Explicit
Sub myFiles()
Const FOLDER = "C:\Users\bradley\Desktop\Sales by Month\"
Dim wb As Workbook, nwb As Workbook
Dim ws As Worksheet, rng As Range
Dim myDate As String, i As Long, j As Long
Dim filename As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Summary")
Set rng = ws.Range("G3")
myDate = Format(Now(), "MM-DD-YYYY")
Application.ScreenUpdating = False
For i = 1 To 4
rng.Value2 = ws.Range("J" & i).Value2
' copy all sheets
For j = 1 To wb.Sheets.Count
If j = 1 Then
wb.Sheets(j).Copy
Set nwb = ActiveWorkbook
Else
wb.Sheets(j).Copy after:=nwb.Sheets(j - 1)
End If
With nwb.Sheets(j)
.UsedRange.Value2 = .UsedRange.Value2
End With
Next
' save workbook
filename = FOLDER & rng.Value2 & " " & myDate & ".xlsx"
Application.DisplayAlerts = False
nwb.SaveAs filename:=filename, FileFormat:=xlWorkbookDefault
nwb.Close
Application.DisplayAlerts = True
Next i
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
Been working on a macro to copy sheets from the main workbook and to paste them into a temporary workbook in another location to save as a workbook and add to email for sending before deleting it.
I finally cracked it last night and it works great on my machine (Excel 2013) but when I took it to work and put on my machine there and changed the folder destinations to their respective locations on our shared drive (Excel 2010) the macro freezes at the copy/paste part of the macro and I cant figure out why?
As said the below works fine on my PC.
{Sub LatestUpdates()
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
Dim Ws As Worksheet
Application.DisplayAlerts = False
FPath = "C:\Temp"
FName = "Latest Spreadsheet for Details" & " " & Format(Date, "dd-mm-yyyy")
Set NewBook = Workbooks.Add
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6", "Sheet7", _
"Sheet8", "Sheet9", "Sheet10")).Copy Before:=NewBook.Sheets(1)
Worksheets("Sheet1").Delete
Set Ws = Worksheets("Sheet1 (2)")
Ws.Name = "Sheet1"
Worksheets("Sheet1").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet2").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet3").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet4").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet5").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet6").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet7").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet8").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet9").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet10").Select
ActiveSheet.Buttons.Delete
Sheets("Sheet1").Activate
NewBook.SaveAs Filename:=FPath & "\" & FName, FileFormat:=xlOpenXMLWorkbook
Call MAILDan
Application.DisplayAlerts = True
ActiveWorkbook.Close
Kill "C:\Temp\*.xl*"
End Sub}
But this one on the server doesn't and stops at the copy/paste phase?
{Sub LatestUpdates()
Dim FName As String
Dim FPath As String
Dim NewBook As Workbook
Dim Ws As Worksheet
Application.DisplayAlerts = False
FPath = "S:\Shared Drive\That Folder\LatestUpdates"
FName = "Latest Spreadsheet for Details" & " " & Format(Date, "dd-mm-yyyy")
Set NewBook = Workbooks.Add
**ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6", "Sheet7", _
"Sheet8", "Sheet9", "Sheet10")).Copy Before:=NewBook.Sheets(1)**
Worksheets("Sheet1").Delete
Set Ws = Worksheets("Sheet1 (2)")
Ws.Name = "Sheet1"
Worksheets("Sheet1").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet2").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet3").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet4").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet5").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet6").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet7").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet8").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet9").Select
ActiveSheet.Buttons.Delete
Worksheets("Sheet10").Select
ActiveSheet.Buttons.Delete
Sheets("Sheet1").Activate
NewBook.SaveAs Filename:=FPath & "\" & FName, FileFormat:=xlOpenXMLWorkbook
Call MAILDan
Application.DisplayAlerts = True
ActiveWorkbook.Close
Kill "S:\Shared Drive\That Folder\LatestUpdates\*.xl*"
End Sub}
Any help as to why it wont work will be much appreciated.
Many thanks
Instead of saving the workbook to a folder on the shared drive you could save it locally to the Temp folder.
The following code will do that, but you might need to adjust the code in MAILDan to refer to the correct path when attaching the new workbook to the email.
Sub LatestUpdates()
Dim NewBook As Workbook
Dim Ws As Worksheet
Dim FName As String
Dim FPath As String
Application.DisplayAlerts = False
FPath = GetTempFolder
FName = "Latest Spreadsheet for Details" & " " & Format(Date, "dd-mm-yyyy")
Set NewBook = Workbooks.Add
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4", "Sheet5", "Sheet6", "Sheet7", _
"Sheet8", "Sheet9", "Sheet10")).Copy
Set NewBook = ActiveWorkbook
For Each Ws In NewBook.Sheets
Ws.Buttons.Delete
Next Ws
Sheets("Sheet1").Activate
NewBook.SaveAs Filename:=FPath & "\" & FName, FileFormat:=xlOpenXMLWorkbook
Call MAILDan
Application.DisplayAlerts = True
FPath = NewBook.FullName#
NewBook.Close
Kill FPath
End Sub
Function GetTempFolder()
Dim FSO As Object, TmpFolder As Object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set TmpFolder = FSO.GetSpecialFolder(2)
GetTempFolder = TmpFolder
End Function
Is there a way to generate the ws In Worksheets(Array("DiscardedDataFile", "GephiNodeFile", "GephiEdgeFile")) for the 2nd Sub dynamically?
Edit: Updated with simoco code and my revision
Sub SaveSheetsAsNewBooks3()
Dim SheetName As String
Dim MyFilePath As String
Dim fileName As String
Dim ws As Worksheet, wsN As Worksheet
Dim wb As Workbook
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
For Each ws In Worksheets
If ws.Index <> 1 Then
SheetName = ws.Name
ws.Copy
MyFilePath = ThisWorkbook.Path & "\" & SheetName
If Len(Dir(MyFilePath, vbDirectory)) = 0 Then
MkDir MyFilePath
End If
With ActiveWorkbook
'~save book in this folder
ActiveWorkbook.SaveAs fileName:=MyFilePath & "\" & SheetName & "_" & Format(Now(), "DD-MM-YY hh.mm") & ".csv", FileFormat:=6
ActiveWorkbook.Close SaveChanges:=True
End With
End If
Next ws
Sheets("Source").Select
End Sub
If I understood you correctly, you need something like this:
Sub SaveSheetsAsNewBooks2()
Dim SheetName As String
Dim MyFilePath As String
Dim fileName As String
Dim ws As Worksheet, wsN As Worksheet
Dim wb As Workbook
With Application
.ScreenUpdating = False
.DisplayAlerts = False
End With
With ThisWorkbook
For Each ws In .Worksheets
If ws.Index <> 1 Then
SheetName = ws.Name
MyFilePath = ThisWorkbook.Path & "\" & SheetName
If Len(Dir(MyFilePath, vbDirectory)) = 0 Then
MkDir MyFilePath
End If
'create new workbook
ws.Copy
With ActiveWorkbook
'save new workbook in this folder
.SaveAs fileName:=MyFilePath & "\" & SheetName & "_" & Format(Now(), "DD-MM-YY hh.mm") & ".csv", FileFormat:=6
.Close SaveChanges:=True
End With
End If
Next ws
.Worksheets(1).Select
End With
With Application
.ScreenUpdating = True
.DisplayAlerts = True
End With
End Sub