Separate worksheets into separate files
Hi I am using code
Sub Split_Sheet_into_ExcelFiles()
Dim FilePath As String
FilePath = Application.ActiveWorkbook.Path
Application.ScreenUpdating = False
Application.DisplayAlerts = False
For Each Sheet In ThisWorkbook.Sheets
Sheet.Copy
Application.ActiveWorkbook.SaveAs Filename:=FilePath & "\" & Sheet.Name & ".xlsx"
Application.ActiveWorkbook.Close False
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
It creates the same file but I was trying to split multiple worksheets into individual files. ANy idea what I'm typing wrong? Thanks
Export Each Sheet to an Individual File
Option Explicit
Sub ExportSheets()
Const PROC_TITLE As String = "Export Sheets"
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim dFilePath As String: dFilePath = swb.Path
If Len(dFilePath) = 0 Then
MsgBox "The path cannot be determined." & vbLf & "Please save the " _
& "workbook before using this procedure.", vbCritical, PROC_TITLE
Exit Sub
End If
Application.ScreenUpdating = False
Dim dwb As Workbook, ssh As Object, sshCount As Long
For Each ssh In swb.Sheets
If ssh.Visible = xlSheetVisible Then ' sheet is visible
ssh.Copy
Set dwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs Filename:=dFilePath & "\" & ssh.Name
Application.DisplayAlerts = False
dwb.Close SaveChanges:=False
sshCount = sshCount + 1
'Else ' sheet is not visible; do nothing!?
End If
Next ssh
Application.ScreenUpdating = True
MsgBox sshCount & " sheet" & IIf(sshCount = 1, "", "s") _
& " exported.", vbInformation, PROC_TITLE
End Sub
Related
I need help in making some changes to the existing VBA.
Based on the "Sheet" name and Sheet No., the existing code was used to copy a selected checkbox sheet to a new workbook.
I'd like to make it flexible so that the code still works when I rename or create a new sheet.
Private Sub ExportSheet_Click()
Dim wbNew As Workbook
Dim ws As Worksheet
Dim cnt As Control
Dim fileName As String
Const chBx As String = "CheckBox"
Application.ScreenUpdating = False
fileName = ThisWorkbook.Path & "\" & Me.Cmbteam.Value & ".xlsx"
Set wbNew = Workbooks.Add
Application.DisplayAlerts = False
Do Until wbNew.Worksheets.Count = 1
wbNew.Worksheets(2).Delete
Loop
Application.DisplayAlerts = True
Set ws = wbNew.Worksheets(1)
ws.Name = "DELETE_ME_LATER"
For Each cnt In Me.Controls
If Left(cnt.Name, Len(chBx)) = chBx Then
If cnt.Value = True Then
ThisWorkbook.Worksheets("Sheet" & Mid(cnt.Name, Len(chBx) + 1)).Copy after:=wbNew.Worksheets(wbNew.Worksheets.Count)
End If
End If
Next cnt
If wbNew.Worksheets.Count = 1 Then
MsgBox "No boxes were checked." & vbNewLine & "No file created", vbExclamation + vbOKOnly, "No selection made"
wbNew.Close savechanges:=False
Else
Application.DisplayAlerts = False
'Delete dummy sheet
ws.Delete
wbNew.Close savechanges:=True, Filename:=fileName
Application.DisplayAlerts = True
MsgBox "File saved at:" & vbNewLine & fileName
Unload Me
End If
Application.ScreenUpdating = True
End Sub
I have a workbook with a VBA macro that I run every day where I paste a large set of data and it formats, fills in extra fields using a vlookup against hidden sheets, splits the data into individual sheets, and saves each as a CSV file.
This process runs perfectly 6 out 7 days of the week & only has issues when I run Sunday data.
All VBA macros within the workbook work fine until I get to the step where it saves the CSVs, then it force closes the excel workbook.
I've noticed it saves 1 worksheet (named RCM), but even that it does incorrectly as it only pulls the first row into the file, and the row is from the incorrect sheet.
I thought the issue was with the sheet name (as I have a hidden sheet named RCM1 and the hidden sheets do not get saved). But I've attempted renaming the sheets & am still having the same issue.
I'm now uncertain of what is causing Excel to crash only with this particular data.
Here is the save portion of the macro
Sub SaveSheets()
'
' SaveSheets Macro
' Saves sheets as individual CSV files
'
'
Dim csvPath As String
Dim DateName As String
csvPath = "C:\Daily Batch Files"
r = Worksheets("Data").Range("B2")
DateName = "batchredeem.001." & WorksheetFunction.Text(r, "mmmmdd") & "_"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error Resume Next
Sheets("Work").ShowAllData
For Each xWs In ThisWorkbook.Sheets
If xWs.Visible = xlSheetVisible And xWs.Name <> "Magic Buttons" And xWs.Name <> "Data" And xWs.Name <> "Work" Then
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=csvPath & "\" & DateName & xWs.Name & ".csv", FileFormat:=xlCSV
Application.ActiveWorkbook.Close False
ElseIf xWs.Name = "Work" Then
xWs.Copy
Application.ActiveWorkbook.SaveAs Filename:=csvPath & "\" & xWs.Name & ".csv", FileFormat:=xlCSV
Application.ActiveWorkbook.Close False
End If
Next
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
**EDIT to add additional info:
If I change the name of the sheet before running the macro, it won't save the renamed "RCM" sheet at all- it works for the previous sheet, however, and if I delete the "RCM" sheet, the entire macro runs normally.
***EDIT 2 - I also cannot manually "copy" the "RCM" sheet, but I can manually copy any of the others. Also, if I save the entire workbook, then run the macro, it works normally! I'm stumped & not sure why it isn't working just for this one worksheet.
Export Worksheets As One-Worksheet Files
Option Explicit
Sub ExportVisibleWorksheets()
' Saves worksheets as individual CSV files
' Source
Const sExceptionsList As String = "Magic Buttons,Work,Data"
Const sSpecialName As String = "Work" ' exported differently
' Source Lookup
Const slName As String = "Data" ' included in the exceptions list
Const slCellAddress As String = "B2"
' Destination
Const dDateLeft As String = "batchredeem.001."
Const dDateMidFormat As String = "mmmmdd"
Const dDateRight As String = "_"
Dim dFolderPath As String: dFolderPath = "C:\Daily Batch Files\"
' The following two depend on each other!
Dim dFileExtension As String: dFileExtension = ".csv"
Dim dFileFormat As XlFileFormat: dFileFormat = xlCSV
If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
If Len(Dir(dFolderPath, vbDirectory)) = 0 Then Exit Sub ' doesn't exist
If Left(dFileExtension, 1) <> "." Then dFileExtension = "." & dFileExtension
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Worksheets(slName)
Dim sCell As Range: Set sCell = sws.Range(slCellAddress)
Dim sExceptions() As String: sExceptions = Split(sExceptionsList, ",")
Dim dDateMid As String
dDateMid = WorksheetFunction.Text(sCell.Value, dDateMidFormat) ' English
'dDateMid = Format(sCell.Value, dDateMidFormat) ' International
Dim dDateName As String: dDateName = dDateLeft & dDateMid & dDateRight
Application.ScreenUpdating = False
Dim dwb As Workbook
Dim dFilePath As String
Dim dwsCount As Long
Dim ErrNum As Long
Dim DoNotCopy As Boolean
For Each sws In swb.Worksheets
If sws.Visible = xlSheetVisible Then
If IsError(Application.Match(sws.Name, sExceptions, 0)) Then
dFilePath = dFolderPath & dDateName & sws.Name & dFileExtension
ElseIf StrComp(sws.Name, sSpecialName, vbTextCompare) = 0 Then
dFilePath = dFolderPath & sws.Name & dFileExtension
If sws.AutoFilterMode Then
sws.ShowAllData
End If
Else
DoNotCopy = True
End If
If DoNotCopy Then
DoNotCopy = False
Else
sws.Copy
Set dwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite: no confirmation
On Error Resume Next ' prevent error if file is open
dwb.SaveAs Filename:=dFilePath, FileFormat:=dFileFormat
ErrNum = Err.Number
On Error GoTo 0
Application.DisplayAlerts = True
dwb.Close SaveChanges:=False
If ErrNum = 0 Then
dwsCount = dwsCount + 1
Else
ErrNum = 0
End If
End If
End If
Next
Application.ScreenUpdating = True
Select Case dwsCount
Case 0: MsgBox "No worksheets exported.", vbExclamation
Case 1: MsgBox "One visible worksheet exported.", vbInformation
Case Else
MsgBox dwsCount & " visible worksheets exported.", vbInformation
End Select
End Sub
I have a function that basically makes a copy of the current file, and save it to users' "Downloads" folder.
However, while the SaveAs works, the output does not contain any modules. Instead, they are all linked to the exporting file.
Sub PushToProduction()
Application.ScreenUpdating = False
' save a copy of current file to the Downloads folder
outputPath = Environ$("USERPROFILE") & "\Downloads\"
d = Format(Date, "yyyymmdd")
fileName = outputPath & "REDACTED " & d & " v1.00.xlsm"
' prepare to save a copy of the file without the last tab
sheetCount = Application.Sheets.Count - 1
Dim tabs() As String
ReDim tabs(1 To sheetCount)
For i = 1 To sheetCount
tabs(i) = Worksheets(i).Name
Next
Worksheets(tabs).Copy
ActiveWorkbook.SaveAs fileName, XlFileFormat.xlOpenXMLWorkbookMacroEnabled
ActiveWorkbook.Close False
Application.CutCopyMode = False
Application.ScreenUpdating = True
MsgBox ("Success!")
End Sub
The output does not even have the "Modules" folder.
Is there anyway to solve this?
Create a Workbook Copy and Modify It
Option Explicit
Sub PushToProduction()
Dim dFolderPath As String
dFolderPath = Environ$("USERPROFILE") & "\Downloads\"
Dim d As String: d = Format(Date, "yyyymmdd")
Dim dFilePath As String
dFilePath = dFolderPath & "REDACTED " & d & " v1.00.xlsm"
Application.ScreenUpdating = False
' Create a reference to the Source Workbook ('swb').
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
' Save a copy of the Source Workbook.
If StrComp(dFilePath, swb.FullName, vbTextCompare) = 0 Then
MsgBox "You are trying save a copy of the file to the same location.", _
vbCritical, "Push to Production"
Exit Sub
End If
swb.SaveCopyAs dFilePath
' Open the copy, the Destination Workbook ('dwb'), remove its last sheet
' and close saving the changes.
Dim dwb As Workbook: Set dwb = Workbooks.Open(dFilePath)
Application.DisplayAlerts = False
dwb.Sheets(dwb.Sheets.Count).Delete
Application.DisplayAlerts = True
dwb.Close SaveChanges:=True
Application.ScreenUpdating = True
' Inform.
MsgBox "Success!", vbInformation, "Push to Production"
' Explore Destination Folder.
'swb.FollowHyperlink dFolderPath
End Sub
I have a template file and 4 source documents that I use to fill the template. For each row in sheet2, I create a new blank template and fill it out, resulting in somewhere between 10-100 files. I want to save these in a loop, but having issues with Excel force closing on me. This is my code so far, recycled from a different project.
Dim w As Long, wb As Workbook
Dim fp As String, fn As String
Dim folderName As String
Dim fsoFSO
On Error GoTo bm_Safe_Exit
'Application.ScreenUpdating = False 'stop screen flashing
Application.DisplayAlerts = False 'stop confirmation alerts
'start with a reference to ThisWorkbook
With ThisWorkbook
folderName = Format(Date, "ddmmyyyy")
'set path to save
'fp = "<PATH HERE>" & folderName
fp = "C:\Users\Username\OneDrive - CompanyName\Documents\Projects\ThisProject\csvOutput\" & folderName
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists(fp) Then
MsgBox "FOLDER - " & fp & " ALREADY EXISTS, DELETE CONTENTS TO PROCEED"
Exit Sub
Else
fsoFSO.CreateFolder (fp)
End If
'cycle through each of the worksheets
For w = 6 To Worksheets.Count
With Worksheets(w)
.Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
fn = .Worksheets(1).Name
Cells.Select
Selection.SpecialCells(xlCellTypeVisible).Copy
Worksheets.Add after:=Sheets(Sheets.Count)
Range("A1").Select
ActiveSheet.Paste
Worksheets(1).Delete
Worksheets(1).Name = fn
.SaveAs Filename:=fp & Chr(92) & fn, FileFormat:=51
.Close savechanges:=False '<~~ already saved in line above
End With
End With
Next w
End With
bm_Safe_Exit:
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub ```
The code below worked for me: not sure exactly where the problem might vbe with your posted code, but within your With blocks not everything is scope to the block using a leading .
Sub Test()
Dim w As Long, wb As Workbook, wbNew As Workbook
Dim fp As String, fn As String
Dim fsoFSO
On Error GoTo bm_Safe_Exit
Set wb = ThisWorkbook
fp = "C:\Users\Username\OneDrive - CompanyName\Documents\Projects\" & _
"ThisProject\csvOutput\" & Format(Date, "ddmmyyyy") & "\"
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
If fsoFSO.FolderExists(fp) Then
MsgBox "FOLDER - " & fp & " ALREADY EXISTS, DELETE CONTENTS TO PROCEED"
Exit Sub
Else
fsoFSO.CreateFolder fp
End If
'cycle through each of the worksheets
For w = 6 To wb.Worksheets.Count
'explicitly create a new single-sheet workbook as the destination
Set wbNew = Workbooks.Add(Template:=xlWBATWorksheet)
wb.Worksheets(w).Copy before:=wbNew.Sheets(1)
DeleteSheet wbNew.Sheets(2)
With wbNew
fn = .Worksheets(1).Name
.Worksheets.Add after:=.Worksheets(.Worksheets.Count)
.Worksheets(1).Cells.SpecialCells(xlCellTypeVisible).Copy _
Destination:=.Worksheets(2).Range("A1")
DeleteSheet .Worksheets(1)
.Worksheets(1).Name = fn
.SaveAs Filename:=fp & fn, FileFormat:=51
.Close savechanges:=False '<~~ already saved in line above
End With
Next w
Exit Sub
bm_Safe_Exit:
MsgBox Err.Description
End Sub
'utility sub
Sub DeleteSheet(ws As Worksheet)
Application.DisplayAlerts = False
ws.Delete
Application.DisplayAlerts = True
End Sub
Thanks in advance for helping!
I am currently using the below code to populate multiple .csv files into one sheet and then hide the sheet. The help I need is to remove duplicate rows from that sheet. Can it be incorporated into this code? Thank you!
Sub ImportCSVsWithReference()
'UpdatedforSPSS
Dim xSht As Worksheet
Dim xWb As Workbook
Dim xStrPath As String
Dim xFileDialog As FileDialog
Dim xFile As String
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select the folder with the csv files [File Picker]"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
Set xSht = Sheets.Add
ActiveSheet.Name = "ImportedData"
Worksheets("ImportedData").Visible = False
Application.ScreenUpdating = False
xFile = Dir(xStrPath & "\" & "*.csv")
Do While xFile <> ""
Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
xWb.Close False
xFile = Dir
Loop
Application.ScreenUpdating = True
Exit Sub
ErrHandler:
MsgBox "Encountered an error. Try again", , "Error"
End Sub
There is actually a built-in function to remove duplicates from a range. It is called RemoveDuplicates...
Let's look at an example. I assume here that -
The table has 3 columns
The table has 100 rows
The table does not have a header line
Then the code to remove duplicates will look something like:
ActiveSheet.Range("A1:C100").RemoveDuplicates Columns:=Array(1, 2, 3), Header:=xlNo
See the docs at https://learn.microsoft.com/en-us/office/vba/api/excel.range.removeduplicates
Do Not Import Headers After the First Imported Worksheet
s - Source (read from)
d - Destination (written to)
The Code
Option Explicit
Sub ImportCSVsWithReference()
Const ProcName As String = "ImportCSVsWithReference"
'On Error GoTo clearError
Const WorksheetName As String = "ImportedData"
Const HeaderRows As Long = 1
' Get Folder Path.
Dim FolderPath As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.AllowMultiSelect = False
'.InitialFileName = "C:\Test" ' consider using this
.Title = "Select the folder with the csv files [File Picker]"
If .Show = -1 Then
FolderPath = .SelectedItems(1)
Else
GoTo ProcExit ' Exit Sub
End If
End With
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Application.ScreenUpdating = False
' Define Destination Worksheet (delete existing, add new).
On Error Resume Next
Dim dws As Worksheet: Set dws = dwb.Worksheets(WorksheetName)
On Error GoTo 0
If Not dws Is Nothing Then ' it already exists
Application.DisplayAlerts = False
dws.Delete ' delete without confirmation
Application.DisplayAlerts = True
End If
Set dws = dwb.Worksheets.Add(After:=dwb.Sheets(dwb.Sheets.Count)) ' Sheets!
dws.Name = WorksheetName
dws.Visible = xlSheetHidden ' xlSheetVeryHidden (a 'tougher' option)
' Define Destination Cell.
Dim dCell As Range: Set dCell = dws.Range("A1")
' Copy data from Source Worksheets to Destination Worksheet.
Dim FileName As String: FileName = Dir(FolderPath & "\" & "*.csv")
Dim sws As Worksheet
Dim srg As Range
Dim swsCount As Long
Do While FileName <> ""
' There is only one worksheet in a csv file (the first):
Set sws = Workbooks.Open(FolderPath & "\" & FileName).Worksheets(1)
Set srg = sws.UsedRange
If srg.Rows.Count > HeaderRows Then
swsCount = swsCount + 1
If swsCount > 1 Then ' headers for the first worksheet only
Set srg = srg.Resize(srg.Rows.Count - HeaderRows) _
.Offset(HeaderRows)
End If
dCell.Resize(srg.Rows.Count, srg.Columns.Count).Value _
= srg.Value
Set dCell = dCell.Offset(srg.Rows.Count)
End If
sws.Parent.Close False ' the workbook is the 'parent' of the worksheet
FileName = Dir
Loop
'dwb.save
ProcExit:
If Application.ScreenUpdating = False Then
Application.ScreenUpdating = True
End If
' Inform.
Select Case swsCount
Case 0
MsgBox "No worksheet imported.", vbExclamation, "Fail?"
Case 1
MsgBox "1 worksheet imported.", vbInformation, "Success"
Case Else
MsgBox swsCount & " worksheets imported.", vbInformation, "Success"
End Select
Exit Sub
clearError:
MsgBox "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub