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
Related
I have this code that exports a worksheet to the desktop. I want to change the formulas to values but only in the exported file, but I don't know how to do it.
Thanks.
Sub ExportWorksheets()
Dim worksheet_list As Variant, worksheet_name As Variant
Dim new_workbook As Workbook
Dim saved_folder As String
Dim File_name As String
Dim New_File_Name As String
worksheet_list = Array("Sheet_02")
'// makes sure you close the path with a back slash \
saved_folder = Environ("userprofile") & "\Desktop\"
For Each worksheet_name In worksheet_list
On Error Resume Next
' Opens a new Excel wokrobook
Set new_workbook = Workbooks.Add
File_name = ThisWorkbook.Name
File_name_02 = Replace(File_name, ".xlsm", "")
New_File_Name = worksheet_name & "_" & File_name_02 & ".xlsx"
ThisWorkbook.Worksheets(worksheet_name).Copy new_workbook.Worksheets(1)
new_workbook.SaveAs saved_folder & New_File_Name, 51
new_workbook.Close False
Next worksheet_name
MsgBox "Export completed. " & New_File_Name, vbInformation
End Sub
Please, try the next updated code. You do not need to previously create a new workbook, and .Value = .Value does what you need:
Sub ExportWorksheets()
Dim worksheet_list As Variant, worksheet_name As Variant
Dim saved_folder As String, File_name As String, New_File_Name As String
worksheet_list = Array("Sheet_02")
'// makes sure you close the path with a back slash \
saved_folder = Environ("userprofile") & "\Desktop\"
For Each worksheet_name In worksheet_list
File_name = ThisWorkbook.name
File_name_02 = Replace(File_name, ".xlsm", "")
New_File_Name = worksheet_name & "_" & File_name_02 & ".xlsx"
ThisWorkbook.Worksheets(worksheet_name).Copy 'it automatically create a new workbook with the content of the respective sheet
With ActiveWorkbook.Sheets(1).UsedRange
.value2 = .value2 'value2 is faster and may be used since the range has the same format...
End With
ActiveWorkbook.saveas saved_folder & New_File_Name, 51
ActiveWorkbook.Close False
Next worksheet_name
MsgBox "Export completed. " & New_File_Name, vbInformation
End Sub
I would like to open a workbook using a wildcard or partial name match and save a copy with another name.
However, there is an error -
Always at the " Workbooks(myFolderPath & "" & MyFileName).SaveCopyAs Filename:="NEW NAME.xlsx" " line
Here is my code:
Sub GENERATE()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'If workbook name like "Report Due" then open, if not already opened
Dim MyFileName As Variant
Dim myFolderPath As String
myFolderPath = Application.DefaultFilePath
MyFileName = Dir(myFolderPath & "\" & "Report Due*.xlsx")
If MyFileName <> "" Then
Workbooks.Open (myFolderPath & "\" & MyFileName)
End If
Workbooks(myFolderPath & "\" & MyFileName).SaveCopyAs Filename:="NEW NAME.xlsx"
Workbooks(myFolderPath & "\" & MyFileName).Close SaveChanges:=False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I'd be happy to see what's wrong! Many thanks!
Set a reference to the workbook when you open it, then you shouldn't need to use it's name to reference when saving the copy.
Option Explicit
Sub GENERATE()
Dim wb As Workbook
Dim MyFileName As Variant
Dim myFolderPath As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'If workbook name like "Report Due" then open, if not already opened
myFolderPath = Application.DefaultFilePath
MyFileName = Dir(myFolderPath & "\" & "Report Due*.xlsx")
If MyFileName <> "" Then
Set wb = Workbooks.Open(myFolderPath & "\" & MyFileName)
wb.SaveCopyAs Filename:="NEW NAME.xlsx"
wb.Close SaveChanges:=False
End If
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I'm working on a macro in my Excel File.
I want to export six worksheets as new backup files.
There are several sheets that I also don't want to export.
When I run the code as it is now there is one/two sheets that are being exported while the remaining four aren't exported.
The two exported sheets are then also being closed after they are saved as a new file.
I hope someone is able to help me and give me advice and feedback.
Thanks in advance.
My code is:
'''
Sub SplitWorkbook2()
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim xWs As Worksheet
Dim xWb As Workbook
Dim xNWb As Workbook
Dim FolderName As String
Application.ScreenUpdating = False
Set xWb = Application.ThisWorkbook
DateString = Format(Now, "mm-dd hh-mm")
FolderName = "I:\Export\Backup\TEMPS\2021\Urenlijsten\" & " Werkbriefjes week " & Range("C4") & " " & DateString
MkDir FolderName
Application.DisplayAlerts = False
On Error GoTo NErro
DoNotInclude = "Actions" & "Adressbook" & "Import" & "Hours_Database"
FileExtStr = ".xls"
For Each xWs In xWb.Sheets
If InStr(DoNotInclude, xWs.Name) = 0 Then
xWs.Copy
Set xNWb = Application.Workbooks.Item(Application.Workbooks.Count)
With xNWb
ActiveSheet.UsedRange.Value = ActiveSheet.UsedRange.Value
xFile = FolderName & "\" & Range("C6") & FileExtStr
xNWb.SaveAs xFile, FileFormat:=xlOpenXMLWorkbook
End With
End If
Next xWs
NErro: xWb.Activate
xWb.Activate
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "You can find the files in " & FolderName
End Sub
Export Worksheets
Not tested.
Option Explicit
Sub SplitWorkbook2()
Dim wb As Workbook
Dim ws As Worksheet
Dim DoNotInclude As Variant
Dim FileFormatNum As Long
Dim FileExtStr As String
Dim FolderName As String
FolderName = "I:\Export\Backup\TEMPS\2021\Urenlijsten\" & " Werkbriefjes week " & Range("C4") & " " & DateString
FileExtStr = ".xlsx" ' ??? not '.xls'
DateString = Format(Now, "mm-dd hh-mm")
DoNotInclude = Array("Actions" & "Adressbook" & "Import" & "Hours_Database")
On Error Resume Next
MkDir FolderName
On Error GoTo 0
Set wb = ThisWorkbook
Application.ScreenUpdating = False
For Each ws In wb.Worksheets
If IsError(Application.Match(ws.Name, DoNotInclude, 0)) Then
ws.Copy
With ActiveWorkbook.Worksheets(1)
.UsedRange.Value = .UsedRange.Value
xFile = FolderName & "\" & .Range("C6") & FileExtStr
Application.DisplayAlerts = False
.Parent.SaveAs xFile, FileFormat:=xlOpenXMLWorkbook
.Parent.Close
Application.DisplayAlerts = True
End With
End If
Next ws
Application.ScreenUpdating = True
MsgBox "You can find the files in " & FolderName
'wb.FollowHyperlink FolderName ' open in Windows File Explorer
End Sub
I have following code, which Saves file automatically as per my desired output, I want to make 2 changes into it
ask for file name, currently it saves automatically with "Carrier Files"
copy sheets from 5th sheet to last sheet
Sub Splitbook()
Dim xWs As Worksheet
Dim xPath As String
xPath = Application.ActiveWorkbook.Path & "\Carrier Files"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ActiveWorkbook.Worksheets
xWs.UsedRange.Value = xWs.UsedRange.Value
Next xWs
Application.ActiveWorkbook.SaveAs Filename:=xPath & "" & AD & ".xlsx"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Sheets("NIFTY WEEK ALL").Select
MsgBox ("Done.")
End Sub
To ask for the filename you could use a simple InputBox like so:
xPath = Application.ActiveWorkbook.Path
AD = InputBox("Enter desired filename")
Application.ActiveWorkbook.SaveAs Filename:=xPath & "\" & AD & ".xlsm"
To copy sheet 5:
Sheets(5).Copy After:=Sheets(Sheets.Count)
Use a Inputbox() for file name to enter. Try below sub
Sub Splitbook()
Dim xWs As Worksheet
Dim xPath As String
Dim myFile As String
xPath = Application.ActiveWorkbook.Path & "\Carrier Files\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ActiveWorkbook.Worksheets
myFile = InputBox("Enter a file name to save", "File Name", xWs.Name) 'Input file name
xWs.UsedRange.Value = xWs.UsedRange.Value
Next xWs
Application.ActiveWorkbook.SaveAs Filename:=xPath & myFile & ".xlsm"
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Sheets("NIFTY WEEK ALL").Select
MsgBox ("Done.")
End Sub
I am writing a function to take all the worksheets labeled "STORE #01" and create separate files for reach store that contain two tabs:
1 - The same "Compare Depts" sheet which all files will have
2 - The unique sheet associated with that store
Files must be stored as Store_01_City.xls.
When I run the macro, I do not see any files created. Also, the workbook I am running the macro in is password protected but I have entered the password obviously.
Sub SplitBook()
Dim xPath As String
Dim FilePath As String
xPath = Application.ThisWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each xWs In ThisWorkbook.Worksheets
If InStr(xWs.Name, "Store") <> 0 Then
Dim WB As Workbook
Set WB = xWs.Application.Workbooks.Add
ThisWorkbook.Sheets("Compare Depts").Copy Before:=WB.Sheets(1)
Sheets(xWs.Name).Copy Before:=WB.Sheets(2)
FilePath = "\" & Left(xWs.Name, 5) & "_" & Right(xWs.Name, 2)
& "_" & Application.ThisWorkbook.VLookup(Right(xWs.Name, 2),
ThisWorkbook.Sheets("Table").Range(H3, K100), 4)
WB.SaveAs Filename:=xPath & FilePath & ".xls"
WB.Close SaveChanges:=False
Set WB = Nothing
End If
Next xWs
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
I found a way to by-pass the password for the old Macro and modified it. This also works, but is much slower than your function #Thomas Inzina
Sub ProcessStoreDistribution()
Application.DisplayAlerts = False
For Each c In ThisWorkbook.Sheets("Table").Range("StoreList")
Process c
Next c
Application.DisplayAlerts = True
MsgBox prompt:="Process Completed"
End Sub
Sub Process(ByVal c As Integer)
Dim wb As Workbook
ThisWorkbook.Activate
StoreNum = WorksheetFunction.VLookup(c, Sheets("Table").Range("StoreTable"), 2)
StoreName = WorksheetFunction.Proper(WorksheetFunction.VLookup(c, Sheets("Table").Range("StoreTable"), 5))
myST = "STORE #" & Right(StoreNum, 2)
mySTN = WorksheetFunction.Substitute(WorksheetFunction.Substitute(ActiveWorkbook.FullName, "PPE", "(PPE"), ".xlsm", ") Store Distribution Files")
Application.DisplayAlerts = False
Sheets(Array("COMPARE DEPTS", myST)).Select
Sheets(Array("COMPARE DEPTS", myST)).Copy
Set wb = ActiveWorkbook
Sheets(Array("COMPARE DEPTS", myST)).Select
Cells.Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues
Sheets("COMPARE DEPTS").Activate
Application.CutCopyMode = False
If Len(Dir(mySTN, vbDirectory)) = 0 Then
MkDir mySTN
End If
mySTN = mySTN & "\STORE_" & StoreNum & "_" & StoreName & ".xls"
wb.SaveAs Filename:=mySTN _
, FileFormat:=xlExcel8, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWindow.Close
ThisWorkbook.Activate
Application.DisplayAlerts = True
End Sub
Updated
File picker added to get the external workbook.
I had to add a parameter to the VLookup and cast Right(.Name, 2) to an int. Hopefully it's smooth sailing from here.
Option Explicit
Sub ProcessExternalWorkBook()
Dim ExternalFilePath As String, password As String
ExternalFilePath = GetExcelWorkBookPath
If Len(ExternalFilePath) Then
password = Application.InputBox(Prompt:="Enter Password applicable", Type:=2)
SplitBook ExternalFilePath, password
End If
End Sub
Function GetExcelWorkBookPath() As String
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select a Excel WorkBook"
.AllowMultiSelect = False
.InitialFileName = "Path"
.Filters.Clear
.Filters.Add "Excel WorkBooks", "*.xls, *.xlsx, *.xlsm, *.xlsb"
If .Show = -1 Then
GetExcelWorkBookPath = .SelectedItems(1)
End If
End With
End Function
Sub SplitBook(ExternalFilePath As String, Optional sPassword As String)
Dim FilePath As String
Dim wb As Workbook, wbSource As Workbook
Dim xWs As Worksheet
Dim Secured
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wbSource = Application.Workbooks.Open(Filename:=ExternalFilePath, ReadOnly:=True, password:=sPassword)
For Each xWs In wbSource.Worksheets
If InStr(xWs.Name, "Store") <> 0 Then
Debug.Print xWs.Name & ": was processed"
FilePath = getNewFilePath(xWs)
If Len(FilePath) Then
Sheets(Array("Compare Depts", xWs.Name)).Copy
Set wb = ActiveWorkbook
wb.SaveAs Filename:=FilePath, _
FileFormat:=xlExcel8, password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
wb.Close SaveChanges:=False
Else
MsgBox xWs.Name & " was not found by VLookup", vbInformation
End If
Else
Debug.Print xWs.Name & ": was skipped"
End If
Next xWs
Set wb = Nothing
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Function getNewFilePath(xWs As Worksheet) As String
Dim s As String, sLookup As String
On Error Resume Next
With xWs
sLookup = WorksheetFunction.VLookup(CInt(Right(.Name, 2)), .Parent.Sheets("Table").Range("H3", "K100"), 4, False)
s = ThisWorkbook.Path & "\"
s = s & Left(.Name, 5) & "_" & Right(.Name, 2) & "_" & sLookup
If Err.Number = 0 Then getNewFilePath = s & ".xls"
End With
On Error GoTo 0
End Function
Function getCellValue(cell)
Dim s
s = cell.innerHTML
s = Replace(s, "<br>", "")
s = Replace(s, "<br />", "")
getCellValue = s
End Function