Copy worksheet into new workbook and save - excel

Copy Worksheet 1 in Workbook A
Create new Workbook (named as below)
Copy worksheet 1 into new workbook
Save new workbook as 'abc (daily) & Format(Date, "ddmmmyyy") & ".xlsm" - i.e. code will save in a way that depends on today's date
I'm not sure where I'm making a mistake
'Save Worksheet1 as Workbook
Worksheets("Worksheet 1").Activate
With Worksheets("Worksheet 1")
.copy
End With
saveLocation = "X:\abc\abc\abc (daily)" & Format(Date, "ddmmmyyy") & ".xlsm"
ActiveSheet.ExportAsFixedFormat Type:=xlTypexlsm, _
Filename:=saveLocation

Sub CopySheetAsNewWorkbook()
Dim theNewWorkbook As Workbook
Dim currentWorkbook As Workbook
'currentWorkbook is the source workbook, create a new workbook referencing to it with theNewWorkbook
Set currentWorkbook = ActiveWorkbook
Set theNewWorkbook = Workbooks.Add
'do the copy (it's better to check if there is already a 'Worksheet 1' in the new workbook. It it exists delete it or rename it
currentWorkbook.Worksheets("Worksheet 1").Copy before:=theNewWorkbook.Sheets(1)
'Remove default sheets in order to have only the copied sheet inside the new workbook
Application.DisplayAlerts = False
Dim i As Integer
For i = theNewWorkbook.Sheets.Count To 2 Step -1
theNewWorkbook.Sheets(i).Delete
Next i
Application.DisplayAlerts = True
'Save File as XLSM
saveLocation = "X:\abc\abc\abc (daily)" & Format(Date, "ddmmmyyy") & ".xlsm"
theNewWorkbook.SaveAs Filename:=saveLocation, FileFormat:=XlFileFormat.xlOpenXMLWorkbookMacroEnabled
theNewWorkbook.Close
End Sub

Maybe try something like this:
Sub test()
Path = "D:\"
Filename = "test "
Sheets("Worksheet 1").Copy
' for multiple sheets : Sheets(Array("TABEL", "DATA", "BACKUP")).Copy
' to save with time : ActiveWorkbook.SaveAs Filename:=Path & Filename & Format(Now(), "yymmdd hh mm ss") & ".xlsm", FileFormat:=52
ActiveWorkbook.SaveAs Filename:=Path & Filename & Format(Date, "ddmmyy") & ".xlsm", FileFormat:=52
ActiveWorkbook.Close
End Sub

A Worksheet Export
Before running the code, adjust the values of variables NewFilePath
and SourceSheet in Sub exportFirst. NewFilePath must not end with a backslash \.
The code is written to refer to a worksheet in ThisWorkbook i.e. the workbook
containing this code.
Sub exportFirst is calling Sub exportWorksheet.
You can write several subs like Sub exportFirst for other
worksheets in the workbook.
I would prefer using e.g. Worksheets("Sheets1") over
Worksheets(1).
After you are done testing the code, you should probably un-comment the
line .Close.
Option Explicit
Sub exportFirst()
Const NewFilePath As String _
= "C:\Test"
Dim SourceSheet As Worksheet
Set SourceSheet = ThisWorkbook.Worksheets(1)
exportWorksheet SourceSheet, NewFilePath
End Sub
Sub exportWorksheet(SourceSheet As Worksheet, NewFilePath As String)
Dim NewFileName As String
Dim SaveLocation As String
' Either:
' ' If you want to name the new workbook using 'SourceSheet.Name':
NewFileName = SourceSheet.Name
' ' Or:
' ' If you want to name the new workbook using 'ThisWorkbook.Name':
' NewFileName _
' = Left$(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".") - 1)
' I would prefer "yyyymmdd" or at least "ddmmmyyyy"
SaveLocation = NewFilePath & "\" & NewFileName & " (daily)" _
& Format(Date, "ddmmmyyy")
SourceSheet.Copy
With ActiveWorkbook
' Either:
' .xlsm
SaveLocation = SaveLocation & ".xlsm"
.SaveAs FileFormat:=xlOpenXMLWorkbookMacroEnabled, _
Filename:=SaveLocation
' or:
' .xlsx
' SaveLocation = SaveLocation & ".xlsx"
' .SaveAs FileFormat:=xlOpenXMLWorkbook, _
' Filename:=SaveLocation
' or:
' .csv
' SaveLocation = SaveLocation & ".csv"
' .SaveAs FileFormat:=xlCSVUTF8, Filename:=SaveLocation
' or:
' .pdf
' SaveLocation = SaveLocation & ".pdf"
' .ExportAsFixedFormat Type:=xlTypePDF, Filename:=SaveLocation
' .Saved = True
'.Close ' You should use '.Close' always with '.pdf'.
End With
End Sub

Related

Select and save specific sheets as new workbook

I need to write a macro that allows me to select which workbook sheets I want to save as a new file separately.
I am currently doing it with the following code, but it saves all the sheets as a new file. I would like to be able to select or define which sheets I want to save.
Sub Save_sheets_xlsx()
Dim Path As String
Path = Application.ActiveWorkbook.Path
Dim FileName As String
FileName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 5)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Sheets
xWs.Copy
Application.ActiveWorkbook.SaveAs FileName:=Path & "\" & FileName & " " & xWs.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Export Sheets As New Workbooks
Option Explicit
Sub ExportSheets()
Const SheetNameList As String = "Sheet1,Sheet2,Sheet3" ' commas no spaces!
Dim SheetNames() As String: SheetNames = Split(SheetNameList, ",")
Dim FolderPath As String: FolderPath = ThisWorkbook.Path
Dim BaseName As String
BaseName = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5)
Application.ScreenUpdating = False
Dim sh As Object
Dim FilePath As String
For Each sh In ThisWorkbook.Sheets(SheetNames)
sh.Copy
FilePath = FolderPath & "\" & BaseName & " " & sh.Name & ".xlsx"
Application.DisplayAlerts = False ' overwrite without confirmation
Workbooks(Workbooks.Count).SaveAs FileName:=FilePath
Application.DisplayAlerts = True
Application.ActiveWorkbook.Close SaveChanges:=False
Next
Application.ScreenUpdating = True
MsgBox "Sheets exported.", vbInformation
End Sub

Copy data from a workbook to an existing workbook

I'm working on Excel for Mac, v16.53, with OS Catalina v10.15.7
I have an Excel workbook called SCRIPT with two sheets.
Sheet 1 has data entry areas and sheet 2 compiles those entries into a pseudo-table. The data in sheet 1 changes with every new person that is interviewed.
The data in sheet 2 is in columns A, B, H, I and J. It is non-contiguous and doesn't always have row 1 populated.
I can copy those five columns to a new csv file called Telesales-Leads-TODAY'S DATE.
The issue is when there already is a Telesales-Leads-TODAY'S DATE file.
The script is supposed to:
If Telesales-Leads-TODAY'S DATE file does not exist:
Start a new one.
Copy/paste the new SCRIPT data and save the Telesales-Leads-TODAY'S DATE file.
If a Telesales-Leads-TODAY'S DATE file does exist:
Copy the new data from the SCRIPT workbook to the first 100% empty column of the Telesales-Leads-TODAY'S DATE file.
Save the file with the same name (Telesales-Leads-TODAY'S DATE) in csv format.
It throws an error AFTER it copies the data from the SCRIPT workbook but BEFORE it has a chance to completely open the Telesales-Leads-TODAY'S DATE file.
I am using the MsgBox to debug.
Sub BackUpScriptData()
Dim strFileName As String
Dim strFileExists As String
Dim finalcolumn As Integer
Dim firstemptycolumn As Integer
Dim csvOpened As Workbook
Dim oneCell As Range
Dim myCSVFileName As String
Dim myWB As Workbook
Dim tempWB As Workbook
Dim rngToSave As Range
Dim col As String
Dim ColumnNumber As Integer
Dim ColumnLetter As String
Dim colstart As String
Dim CellAddress As String
Dim TestChar As String
Dim NumberToLetter As String
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
On Error GoTo err
strFileName = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/User Content.localized/Startup.localized/Excel/" & "Telesales-Leads-" & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
strFileExists = Dir(strFileName)
If strFileExists = "" Then
MsgBox strFileName & " ~~~~~~~~doesn't exist"
Set myWB = ThisWorkbook
myCSVFileName = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/User Content.localized/Startup.localized/Excel/" & "Telesales-Leads-" & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
Set rngToSave = Range("A1:B69,H1:J69")
rngToSave.Copy
Set tempWB = Application.Workbooks.Add(1)
With tempWB
.Sheets(1).Range("A1").PasteSpecial xlPasteValues
.SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
Else
Set myWB = ThisWorkbook
Set rngToSave = Range("A1:B69,H1:J69")
rngToSave.Copy
Set csvOpened = Workbooks.Open(FileName:=strFileName)
MsgBox "csvOpened is " & csvOpened
With csvOpened
Set oneCell = Range("A1")
Do While WorksheetFunction.CountA(oneCell.EntireColumn)
Set oneCell = oneCell.Offset(0, 1)
Loop
MsgBox "oneCell.Column is " & oneCell.Column
End With
CellAddress = Cells(1, ColNum).Address
For i = 2 To Len(CellAddress)
TestChar = Mid(CellAddress, i, 1)
If TestChar = "$" Then Exit For
NumberToLetter = NumberToLetter & Mid(CellAddress, i, 1)
Next i
MsgBox "colstart is " & colstart
With csvOpened
.Sheets(1).Range(colstart & "1").PasteSpecial xlPasteValues
.SaveAs FileName:=myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close
End With
End If
err: MsgBox "failed to copy."
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
The code is essentially the same for creating a new workbook or updating an existing, the only difference being the column where the data is to be pasted. As this is a csv file then UsedRange is a simple way to determine the last clear column.
Sub BackUpScriptData2()
Const FOLDER = "/Users/XXXXXXXX/Library/Group Containers/XXXXXXXX.Office/" & _
"User Content.localized/Startup.localized/Excel/"
Const PREFIX = "Telesales-Leads-"
Dim wb As Workbook, wbCSV As Workbook
Dim ws As Worksheet, rngToSave As Range
Dim colNum As Long, myCSVFileName As String
myCSVFileName = PREFIX & VBA.Format(VBA.Now, "mm-dd-yyyy") & ".csv"
' check if file exists
If Len(Dir(FOLDER & myCSVFileName)) = 0 Then
' not exists
MsgBox "'" & myCSVFileName & "'" & vbCrLf & _
"does not exist, it will be created", vbInformation, FOLDER
Set wbCSV = Workbooks.Add()
colNum = 1
Else
' exists
Set wbCSV = Workbooks.Open(FOLDER & myCSVFileName)
With wbCSV.Sheets(1).UsedRange
colNum = .Column + .Columns.Count
End With
MsgBox "'" & myCSVFileName & "'" & vbCrLf & _
"exists, it will extended from column " & colNum, vbInformation, FOLDER
End If
' copy and save
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet2")
Set rngToSave = ws.Range("A1:B69,H1:J69")
rngToSave.Copy
With wbCSV
.Sheets(1).Cells(1, colNum).PasteSpecial xlPasteValues
.SaveAs Filename:=FOLDER & myCSVFileName, FileFormat:=xlCSV, CreateBackup:=False
.Close False
End With
MsgBox "File saved to " & myCSVFileName, vbInformation, FOLDER
End Sub

How to assingn my code properly to a button?

This code works perfectly it saves an excel file to CSV-UTF8 and adds a timestamp in front of the file named "Test".
However, when I assign this code to a button, I'm always getting an error 400 for some reason.
So what I did is put the same code inside a module and debug it, and it didn't give me any errors it executed the code without any problems.
Can someone help me get this to work while using a button?
Sub SaveWorkSheetAsCSV()
Dim wbNew As Excel.Workbook
Dim wsSource As Excel.Worksheet, wsTemp As Excel.Worksheet
Dim name As String, myPath As String
comp = Environ("username")
myPath = "C:\" & comp & "\Testing\" 'use here the path you need
Set wsSource = ThisWorkbook.Worksheets(1)
name = Format(Now, "yyyymmdd-hh.mm") & " Testing"
Application.DisplayAlerts = False 'will overwrite existing files without asking
Set wbNew = ActiveWorkbook
wbNew.SaveAs myPath & "\" & name & ".csv", xlCSVUTF8 'new way
wbNew.Close
Application.DisplayAlerts = True
End Sub
Error 1004
Recieving the following error on this part:
wbNew.SaveAs myPath & "\" & name & ".csv", xlCSVUTF8 'new way
Export to CSV
'Semicolon users' might want to add , Local:=True to the SaveAs line to get the result separated by the semicolon.
ThisWorkbook.FollowHyperlink FolderPath will open the folder in Windows File Explorer.
The Code
Option Explicit
Sub SaveWorkSheetAsCSV()
Dim FolderPath As String
FolderPath = Environ("USERPROFILE") & "\Testing"
' or:
'FolderPath = "C:\Users\" & Environ("USERNAME") & "\Testing"
' Print the path to the Immediate window (CTRL+G).
'Debug.Print FolderPath
Dim FileName As String: FileName = Format(Now, "yyyymmdd-hh.mm ") & " Test"
Dim sws As Worksheet: Set sws = ThisWorkbook.Worksheets(2)
Application.ScreenUpdating = False
sws.Copy
Dim dwb As Workbook: Set dwb = ActiveWorkbook
Application.DisplayAlerts = False
dwb.SaveAs FolderPath & "\" & FileName & ".csv", xlCSVUTF8 ', Local:=True
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
Application.ScreenUpdating = True
'ThisWorkbook.FollowHyperlink FolderPath
End Sub

How to save each sheet as a separate workbook except sheet 1?

I have an excel workbook with 5 sheets but I only want to save sheet 2 to sheet - 5 but I don't want to save sheet 1. I want to exclude it from saving. How can I do it?
I have tried some codes but I am having difficulties.
Sub SaveShtsAsBook()
Dim xcsvFile As String
Dim datestring As String
Dim Count As Integer
datestring = DateValue(Now) & Time
datestring = Replace(datestring, "/", "_")
datestring = Replace(datestring, ":", "_")
datestring = Replace(datestring, " ", "_")
' Application.WindowState = xlMinimized
' Application.Visible = False
Application.EnableEvents = True
' Application.Calculation = xlCalculationManual
' Application.Wait (Now + TimeValue("0:00:10"))
For Count = 1 To 3000
DoEvents
Next Count
'For Each Sheet In Worksheets
For Each Sheet In ThisWorkbook.Worksheets ' Safer way to qualify the worksheets with the workbook where this code lies
Select Case Sheet.Name
Case "Sheet1"
' do nothing
Case Else
xcsvFile = "E:\" & xWs.Name & "_" & datestring & ".csv"
' xcsvFile = "E:\" & "\" & xWs.Name & ".csv" 'compare mine to yours to see issues
xWs.Copy
Dim newSheet As Workbook 'setting copied sheet to workbook variable for easier coding
Set newSheet = ActiveSheet.Parent 'parent of worksheet is workbook
newSheet.SaveAs Filename:=xcsvFile, FileFormat:=xlCSV, CreateBackup:=False
newSheet.Close False
End Select
Next
End Sub
The problem is you were referring to xWs variable which doesn't exist on your code. If you change it with Sheet, it works perfectly as I tested on my Excel:
Sub SaveShtsAsBook()
Dim xcsvFile As String
Dim datestring As String
Dim Count As Integer
datestring = DateValue(Now) & Time
datestring = Replace(datestring, "/", "_")
datestring = Replace(datestring, ":", "_")
datestring = Replace(datestring, " ", "_")
' Application.WindowState = xlMinimized
' Application.Visible = False
Application.EnableEvents = True
' Application.Calculation = xlCalculationManual
' Application.Wait (Now + TimeValue("0:00:10"))
For Count = 1 To 3000
DoEvents
Next Count
'For Each Sheet In Worksheets
For Each Sheet In ThisWorkbook.Worksheets ' Safer way to qualify the worksheets with the workbook where this code lies
Select Case Sheet.Name
Case "Sheet1"
' do nothing
Case Else
xcsvFile = "E:\" & Sheet.Name & "_" & datestring & ".csv"
' xcsvFile = "E:\" & "\" & xWs.Name & ".csv" 'compare mine to yours to see issues
Sheet.Copy
Dim newSheet As Workbook 'setting copied sheet to workbook variable for easier coding
Set newSheet = ActiveSheet.Parent 'parent of worksheet is workbook
newSheet.SaveAs Filename:=xcsvFile, FileFormat:=xlCSV, CreateBackup:=False
newSheet.Close False
End Select
Next
End Sub
Hope this helps.

I want to save a selection as a new workbook but if the workbook already exists i want to save as a new worksheet within the existing workbook instead

I'm still fairly new to this. I want to be able to do the following:
select a copy range
paste selection in a new workbook
save workbook in a folder with year value found in range H5 (if folder does not exists, create one)
save file as "title_month_year" values found in ranges A5,F5,H5 (but if file already exists save as new worksheet/tab)
So far I believe I have 1-3 covered and part of 4.
Option Explicit
Const MYPATH As String = "C:\USERS\3658\Desktop\"
Sub IfNewFolder()
Dim AuditYear As String
AuditYear = Range("H5").Value
'if a particular directory doesnt exists already then create folder.
If Len(Dir(MYPATH & AuditYear, vbDirectory)) = 0 Then
MkDir MYPATH & AuditYear
End If
End Sub
Sub SaveCustomizedCourse()
'copy and past selected data in a new workbook
Range("B8").End(xlDown).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.End(xlUp)).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Range("A1").Select
Selection.PasteSpecial xlPasteColumnWidths
Selection.PasteSpecial xlPasteFormats
'save selected data in a new workbook
Dim AuditMonth As String
Dim AuditYear As String
Dim AuditTitle As String
AuditMonth = Range("F5").Value 'MONTH
AuditYear = Range("H5").Value 'YEAR
AuditTitle = Range("A5").Value 'TITLE
IfNewFolder 'creates a yearly subfolder
ActiveWorkbook.SaveAs Filename:= _
MYPATH & AuditYear & "\" & AuditTitle & "_" & AuditMonth & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
MsgBox ("Audit Saved.")
'ActiveWindow.Close
End Sub
You can add the below sub and call it after IfNewFolder and remove all the code after it.
Private Sub Carla(AuditMonth, AuditYear, AuditTitle)
Dim CurWb As Workbook 'This is whatever workbook you are working with
Dim SaveAsWb As Workbook 'This is spare for the workbook in case that has the same name
Dim SaveFileName As String
Set CurWb = ActiveWorkbook
SaveFileName = AuditYear & "\" & AuditTitle & "_" & AuditMonth & ".xlsm"
If Len(Dir(MYPATH & SaveFileName)) = 0 Then
CurWb.SaveAs FileName:=MYPATH & SaveFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
Set SaveAsWb = Workbooks.Open(MYPATH & SaveFileName)
CurWb.Worksheets("Sheet1").Copy After:=SaveAsWb.Worksheets(Sheets.Count)
SaveAsWb.Save
SaveAsWb.Close
End If
MsgBox ("Audit Saved.")
End Sub
I cleared your code a little bit - see below. I assumed that the values of AuditMonth, AuditYear and AuditTitle are placed in the "current" workbook.
Sub SaveCustomizedCourse()
'copy and paste selected data in a new workbook
Dim lngLastRow As Long
Dim wksThis As Excel.Worksheet
Dim wkbNew As Excel.Workbook
'save selected data in a new workbook
Dim AuditMonth As String
Dim AuditYear As String
Dim AuditTitle As String
Set wksThis = ActiveSheet
Set wkbNew = Workbooks.Add
With wksThis
lngLastRow = .Range("B8").End(xlDown).Row
AuditMonth = .Range("F5").Value 'MONTH
AuditYear = .Range("H5").Value 'YEAR
AuditTitle = .Range("A5").Value 'TITLE
.Range("B8:B" & lngLastRow).Copy
End With
With wkbNew.Sheets(1).Range("A1")
.PasteSpecial xlPasteValuesAndNumberFormats
.PasteSpecial xlPasteColumnWidths
End With
IfNewFolder 'creates a yearly subfolder
With wkbNew
.SaveAs Filename:= _
MYPATH & AuditYear & "\" & AuditTitle & "_" & AuditMonth & ".xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
.Close
End With
MsgBox ("Audit Saved.")
End Sub
I found that this variation of Peicong Chen's post helped a lot.
It works exactly like i want it to, thanks.
Public Sub IfSheetExists(AuditMonth, AuditYear, AuditTitle)
AuditMonth = Range("F5").Value 'MONTH
AuditYear = Range("H5").Value 'YEAR
AuditTitle = Range("A5").Value 'TITLE
Dim CurWb As Workbook 'This is whatever workbook you are working with
Dim SaveAsWb As Workbook 'This is spare for the workbook in case that has the same name
Dim SaveFileName As String
Set CurWb = ActiveWorkbook
SaveFileName = AuditYear & "\" & AuditTitle & "_" & AuditMonth & ".xlsm"
Application.DisplayAlerts = False
If Len(Dir(MYPATH & SaveFileName)) = 0 Then
Sheets("Sheet2").Delete
Sheets("Sheet3").Delete
CurWb.SaveAs Filename:=MYPATH & SaveFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
CurWb.Close
Else
Set SaveAsWb = Workbooks.Open(MYPATH & SaveFileName)
CurWb.Worksheets("Sheet1").Copy After:=SaveAsWb.Worksheets(Sheets.Count)
SaveAsWb.save
SaveAsWb.Close
CurWb.Close
End If
Application.DisplayAlerts = True
MsgBox ("Audit Saved.")
Range("A1").Select
End Sub

Resources