I have been working on my code to get the system to export specific sheet based only on what is visible in the system yet, for some reason I continue to struggle when it is trying to run the export with getting only the specified sheets to export. I know this has to be something simple that I am missing but I am unable to locate what that might be. Any assistance would be greatly appreciated.
Private Sub ExportSheets() 'saves all visible sheets as new xlsx files
Dim ws As Worksheet, wbNew As Workbook
Dim myWorksheets() As String 'Array to hold worksheet names to copy
Dim sFolderPath As String
Dim fs As Object
Dim FileName1 As String
Dim i As Integer
Set wbNew = Application.ThisWorkbook
FileName1 = Range("PMC_Name").Value
sFolderPath = wbNew.Path & "\" & FileName1 & " - Import Templates"
myWorksheets = Split("Chart of Accounts, Custom Mapping File, Custom Chart of Accounts,Conventional Default COA,Conventional Mapping File,CONV Chart of Accounts,HUD Chart of Accounts,Affordable Default COA,Affordable Mapping File,Entities,Properties,Floors,Units,Area Measurement,Tenants,Account Labels,Leases,Scheduled Charges,Tenant Beginning Balances,Vendors,Vendor Beginning Balances,Customers,Customer Beginning Balances,GL Beginning Balances,GL Detail,Bank Accounts,Budgets,Budgeting COA,Budgeting Conventional COA,Budgeting Affordable COA,Budgeting Job Positions,Budgeting Employee List,Budgeting Workers Comp,Expense Pools,Lease Recoveries,Index Code,Lease Sales,Option Types,Clause Types,Lease Clauses,Lease Options,Budgeting Current Budget Import,Job Cost,Draw Model Detail,Job Cost History,Job Cost Budgets,Fixed Assets,Condo Properties,Owners,Ownership Information,Ownership Billing,Owner Charges", ",") 'this contains an array of the sheets. You need to put the real sheet names here.
If Dir(sFolderPath, vbDirectory) <> "" Then
'If the folder does exist error
MsgBox "The folder currently exists, please rename or delete the folder.", vbCritical, "Error"
Exit Sub
'If the folder does not exist create folder and export
End If
MkDir sFolderPath
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Sheets 'for each worksheet
'if it's visible:
If Sheets(myWorksheets(i)).visible Then
Debug.Print "Exporting: " & ws.Name
ws.Copy '(if no params specified, COPY creates + activates a new wb)
Set wbNew = Application.ActiveWorkbook 'get new wb object
wbNew.SaveAs sFolderPath & "\" & ws.Name & ".csv", 23 'save new wb
wbNew.Close 'close new wb
Set wbNew = Nothing 'cleanup
End If
Next ws
Set ws = Nothing 'clean up
Application.ScreenUpdating = False
MsgBox "Sheet Export is now Complete. You can find the files at the following path." & vbNewLine & vbNewLine & sFolderPath, vbExclamation, "Export Sheets Complete"
End Sub
Export Sheets
Sub ExportSheets() 'saves all visible sheets as new xlsx files
Const PROC_TITLE As String = "Export Sheets"
Const SHEET_LIST As String _
= "Chart of Accounts,Custom Mapping File,Custom Chart of Accounts," _
& "Conventional Default COA,Conventional Mapping File," _
& "CONV Chart of Accounts,HUD Chart of Accounts," _
& "Affordable Default COA,Affordable Mapping File,Entities," _
& "Properties,Floors,Units,Area Measurement,Tenants,Account Labels," _
& "Leases,Scheduled Charges,Tenant Beginning Balances,Vendors," _
& "Vendor Beginning Balances,Customers,Customer Beginning Balances," _
& "GL Beginning Balances,GL Detail,Bank Accounts,Budgets," _
& "Budgeting COA,Budgeting Conventional COA,Budgeting Affordable COA," _
& "Budgeting Job Positions,Budgeting Employee List," _
& "Budgeting Workers Comp,Expense Pools,Lease Recoveries,Index Code," _
& "Lease Sales,Option Types,Clause Types,Lease Clauses,Lease Options," _
& "Budgeting Current Budget Import,Job Cost,Draw Model Detail," _
& "Job Cost History,Job Cost Budgets,Fixed Assets,Condo Properties," _
& "Owners,Ownership Information,Ownership Billing,Owner Charges"
Dim swb As Workbook: Set swb = ThisWorkbook
Dim sws As Worksheet: Set sws = swb.Sheets("Sheet1") ' adjust!
Dim PMC As String: PMC = CStr(sws.Range("PMC_Name").Value)
Dim dFolderPath As String
dFolderPath = swb.Path & "\" & PMC & " - Import Templates\"
If Len(Dir(dFolderPath, vbDirectory)) > 0 Then
MsgBox "The folder already exists. " _
& "Please rename or delete the folder.", vbCritical, PROC_TITLE
Exit Sub
End If
MkDir dFolderPath
Dim SheetNames() As String: SheetNames = Split(SHEET_LIST, ",")
Application.ScreenUpdating = False
Dim dwb As Workbook, ssh As Object, SheetName
For Each SheetName In SheetNames
On Error Resume Next
Set ssh = swb.Sheets(SheetName)
On Error GoTo 0
If Not ssh Is Nothing Then ' sheet exists
If ssh.Visible Then ' sheet is visible
Debug.Print "Exporting: " & ssh.Name
ssh.Copy ' creates a single-sheet workbook
Set dwb = Workbooks(Workbooks.Count)
dwb.SaveAs dFolderPath & ssh.Name & ".csv", xlCSVWindows ' 23
dwb.Close SaveChanges:=False
'Else ' sheet is not visible; do nothing
End If
Set ssh = Nothing ' reset for the next iteration
'Else ' sheet doesn't exist; do nothing
End If
Next SheetName
Application.ScreenUpdating = True
MsgBox "Sheet Export is now complete. " _
& "You can find the files in the following path:" & vbLf & vbLf _
& dFolderPath, vbInformation, PROC_TITLE
End Sub
I have some code that I make using Excel 2013. It works perfectly and when I try to run it on Excel 2010, the excel always does not respond, restarting the program and closing. I try to reopen it and the file sometimes goes with read-only or recovery mode so I can't even run my macro even I enable it.
Is there any way to fix this without updating the excel? any ideas?
NB: the laptop with Excel 2010 is not mine, it's my user laptop so if possible, I prefer to not change anything inside the laptop
here's the code
Public Const paramFolderPath = "C:\Users\Documents\Data"
Sub Sheet1()
Application.ScreenUpdating = False
OpenWorkbooks paramFolderPath 'Path collected from the folder parameter
Application.ScreenUpdating = True
End Sub
Sub OpenWorkbooks(sourceFolder As Variant)
Dim sourceFile As String 'Filename obtained by DIR function
Dim masterWb, Sourcewb As Workbook 'Used to loop through each workbook
Dim ext As String
On Error Resume Next
Application.ScreenUpdating = False
Set masterWb = ThisWorkbook
sourceFile = Dir(sourceFolder & "\") 'DIR gets the first file of the folder
Do While sourceFile <> ""
ext = Right(sourceFile, Len(sourceFile) - InStrRev(sourceFile, "."))
If sourceFile <> ThisWorkbook.Name And (ext = "xlsm" Or ext = "xlsx") Then
Workbooks.Open Filename:=sourceFolder & "\" & sourceFile, ReadOnly:=True
Set Sourcewb = ActiveWorkbook
'Copy only the first sheet of a workbook
Sourcewb.Worksheets(1).Copy after:=masterWb.Sheets(masterWb.Worksheets.Count)
'Close the source workbook
Sourcewb.Close SaveChanges:=False
Set Sourcewb = Nothing
End If
sourceFile = Dir 'DIR gets the next file in the folder
Loop
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
Loop Through Files in a Folder
Option Explicit
Public Const paramFolderPath = "C:\Users\Documents\Data"
Sub GetFirstWorkSheets()
ImportFirstWorksheets paramFolderPath
End Sub
Sub ImportFirstWorksheets(ByVal sFolderPath As String)
Const ProcName As String = "ImportFirstWorksheets"
Dim fCount As Long
Dim wbCount As Long
Dim wsCount As Long
On Error GoTo ClearError
Const ExtensionsList As String = "xlsm,xlsx"
' Check if files in folder.
If Right(sFolderPath, 1) <> "\" Then sFolderPath = sFolderPath & "\"
Dim sFileName As String: sFileName = Dir(sFolderPath)
If Len(sFileName) = 0 Then
MsgBox "No files found in '" & sFolderPath & "'.", _
vbExclamation, ProcName
Exit Sub
End If
Dim Extensions() As String: Extensions = Split(ExtensionsList, ",")
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim dwbPath As String: dwbPath = dwb.FullName
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim swb As Workbook
Dim Ext As String
Dim sFilePath As String
Do While Len(sFileName) > 0
fCount = fCount + 1
Ext = Right(sFileName, Len(sFileName) - InStrRev(sFileName, "."))
If IsNumeric(Application.Match(Ext, Extensions, 0)) Then
wbCount = wbCount + 1
sFilePath = sFolderPath & sFileName
If StrComp(sFilePath, dwbPath, vbTextCompare) <> 0 Then
Application.DisplayAlerts = False
On Error GoTo WbError
Set swb = Workbooks.Open(sFilePath, , True)
On Error GoTo ClearError
Application.DisplayAlerts = True
End If
If Not swb Is Nothing Then
If swb.Worksheets.Count > 0 Then ' only first worksheet
wsCount = wsCount + 1
swb.Worksheets(1).Copy After:=dwb.Sheets(dwb.Sheets.Count)
End If
swb.Close SaveChanges:=False
Set swb = Nothing
End If
End If
sFileName = Dir ' next file in folder
Loop
SafeExit:
On Error Resume Next
If Not Application.EnableEvents Then
Application.EnableEvents = True
Application.ScreenUpdating = True
End If
MsgBox "Files Found: " & fCount & vbLf _
& "Workbooks Found: " & wbCount & vbLf _
& "Worksheets Copied: " & wsCount, vbInformation, ProcName
On Error GoTo 0
Exit Sub
WbError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume Next
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume SafeExit
End Sub
I need help to handle runtime error 9.
My goals is to create a new workbook that compile specific sheet (Master User) from all excel workbook in a folder.
I'm stuck while using "on error goto" because i don't get it how to set the program while error (sheet doesn't exist) goto next workbook.
My code now cause me stuck in an never ending loop on a workbook that didn't have "master user" sheet
Sub Master()
Dim MyFiles As String
Dim Path As String
Dim myExtension As String
Dim Filename As String
Workbooks.Add.SaveAs Filename:="Master", FileFormat:=51
Path = "D:\My Document\"
myExtension = "*.xls*"
MyFiles = Dir(Path & myExtension)
On Error GoTo test
DoAgain:
Do While MyFiles <> ""
Workbooks.Open (Path & MyFiles)
Sheets("master user").Select
ActiveSheet.Rows(1).Copy
Workbooks("Master.xlsx").Activate
Sheets.Add After:=Sheets(Sheets.Count)
Range("A1").PasteSpecial xlPasteAll
If InStr(MyFiles, ".") > 0 Then
Filename = Left(MyFiles, InStr(MyFiles, ".") - 1)
End If
ActiveSheet.Name = Filename
Workbooks(Filename).Activate
Application.CutCopyMode = False
ActiveWorkbook.Close SaveChanges:=False
MyFiles = Dir
Loop
Workbooks("Master.xlsx").Activate
ActiveWorkbook.Close SaveChanges:=True
test:
ActiveWorkbook.Close SaveChanges:=False
Resume DoAgain
ActiveWorkbook.Save
End Sub
Copy Worksheet Ranges From Multiple Workbooks to a New Workbook
The Workbooks
The workbook containing this code (ThisWorkbook).
The source workbook i.e. each workbook (file) found in the source folder.
The destination workbook i.e. a newly added workbook that will be copied to.
Description
This will copy the first row of a same-named worksheet of each workbook (file) found in a folder to a newly added (and renamed) worksheet (multiple) of a new workbook (one).
Option Explicit
Sub CreateMaster()
Const ProcName As String = "CreateMaster"
On Error GoTo ClearError
' Source
Const sFolderPath As String = "D:\My Document\" ' maybe a missing 's'?
Const sFilePattern As String = "*"
Const sExtensionPattern As String = ".xls*"
Const swsName As String = "Master User"
' Destination
Const dFileName As String = "Master.xlsx"
' You never mentioned the destination path ('Master.xlsx') so I chose
' the same path as the path of the workbook containing this code.
' Omitting this path will lead to unexpected results (errors).
Dim dFilePath As String: dFilePath = ThisWorkbook.Path & "\"
Dim dFileFormat As XlFileFormat: dFileFormat = xlOpenXMLWorkbook
' Check if the source folder exists.
If Len(Dir(sFolderPath, vbDirectory)) = 0 Then
MsgBox "The folder '" & sFolderPath & "' doesn't exist.", _
vbCritical, ProcName
Exit Sub
End If
' Return the paths of the files of the source folder in a collection.
Dim sFilePaths As Collection
Set sFilePaths = CollFilePaths(sFolderPath, sFilePattern, sExtensionPattern)
If sFilePaths Is Nothing Then ' no files found
MsgBox "No '" & sExtensionPattern & "'- files found in folder '" _
& sFolderPath & "'.", vbCritical, ProcName
Exit Sub
End If
Application.ScreenUpdating = False
Dim swb As Workbook
Dim sws As Worksheet
Dim sFilePath As Variant
Dim dwb As Workbook
Dim dws As Worksheet
Dim dwbCreated As Boolean
' Loop through the elements (file paths) of the collection.
For Each sFilePath In sFilePaths
Set swb = Workbooks.Open(sFilePath)
' Attempt to create a reference to the source worksheet.
On Error Resume Next
Set sws = swb.Worksheets(swsName)
On Error GoTo ClearError
If Not sws Is Nothing Then ' source worksheet exists
' Add a new worksheet/workbook.
If dwbCreated Then ' destination workbook created
Set dws = dwb.Worksheets _
.Add(After:=dwb.Sheets(dwb.Sheets.Count))
Else ' destination workbook not created
Set dwb = Workbooks.Add(xlWBATWorksheet) ' one worksheet
Set dws = dwb.Worksheets(1)
dwbCreated = True
End If
' Attempt to rename the destination worksheet.
On Error Resume Next
dws.Name = Left(swb.Name, InStrRev(swb.Name, ".") - 1)
On Error GoTo ClearError
' Copy source to destination.
sws.Rows(1).Copy dws.Rows(1)
Set sws = Nothing
'Else ' source worksheet doesn't exist
End If
swb.Close SaveChanges:=False
Next sFilePath
If dwbCreated Then
dwb.Worksheets(1).Activate
Application.DisplayAlerts = False ' overwrite without confirmation
dwb.SaveAs dFilePath & dFileName, dFileFormat
Application.DisplayAlerts = True
dwb.Close
MsgBox "Master created.", vbInformation, ProcName
Else
MsgBox "Non of the opened workbooks contained a worksheet " _
& "named '" & swsName & "'.", vbExclamation, ProcName
End If
Application.ScreenUpdating = False
ProcExit:
Exit Sub
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns the paths of the files of a folder in a collection.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function CollFilePaths( _
ByVal FolderPath As String, _
Optional ByVal FilePattern As String = "*", _
Optional ByVal ExtensionPattern As String = "*") _
As Collection
Const ProcName As String = "CollFilePaths"
On Error GoTo ClearError
Dim pSep As String: pSep = Application.PathSeparator
Dim foPath As String: foPath = FolderPath
If Right(foPath, 1) <> pSep Then foPath = foPath & pSep
Dim ePattern As String: ePattern = ExtensionPattern
If Left(ePattern, 1) <> "." Then ePattern = "." & ePattern
Dim fiName As String: fiName = Dir(foPath & FilePattern & ePattern)
If Len(fiName) = 0 Then Exit Function
Dim coll As Collection: Set coll = New Collection
Do Until Len(fiName) = 0
coll.Add foPath & fiName
fiName = Dir
Loop
Set CollFilePaths = coll
ProcExit:
Exit Function
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Function
I want to run through a specific sheet (from & to) save those ws as a new file in a folder, if the folder doesn't exist then create.
I'm able to do it to one sheet.
ActiveSheet.Next.Select
If Range("F3").Value = "" Then
Windows("Import OT.xlsm").Activate
Sheets("Cash").Select
Dim filename101 As String
Dim path101 As String
Application.DisplayAlerts = False
path101 = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
filename101 = Range("B1").Value & ".xlsx"
ActiveWorkbook.SaveAs path101 & Range("A2") & "\" & Range("A1") & " " & filename101,xlOpenXMLWorkbook
Application.DisplayAlerts = True
Else
Cells.Select
Range("F3").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Dim Path1 As String
Dim fpathname1 As String
Path1 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\"
fpathname1 = Path1 & Range("F3") & "\" & Range("F2") & " " & Range("B3") & ".xlsx"
path01 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & Range("F3")
Dim path001 As String
Dim Folder As String
Folder = Dir(path01, vbDirectory)
If Folder = vbNullString Then
VBA.FileSystem.MkDir (path01)
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
Else
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
End If
End If
End Sub
I want this as a loop is because I have a few tens of sheets. For it to work I think I need to write it specific time, but with loop I learned I don't need to do that.
Excel file sheet
https://onedrive.live.com/view.aspx?resid=AF6FF2618C09AC74!29027&ithint=file%2cxlsx&authkey=!AHcJjYCu8D0NTNY
According to your comment where you wrote the steps:
Read the comments
Try to run the code using F8 key and see where you need to change it.
As you're learning, please note to first write the steps in plain English Norsk and then develop your code.
See how I just followed your steps with readable code.
Code:
Public Sub GenerateCustomersFiles()
' 1) Active sheet (oppgjør 1-20)
Dim targetSheet As Worksheet
For Each targetSheet In ThisWorkbook.Sheets
' Check only sheets with string in name
If InStr(targetSheet.Name, "Oppgjør") > 0 Then
' 2) look if value in F3 is empty
If targetSheet.Range("F3").Value = vbNullString Then
' 3) if it is, do select "cash" sheet and save this file (its name and path are given above what it should be named)
Dim fileName As String
Dim filePath As String
Dim folderPath As String
folderPath = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
fileName = targetSheet.Range("B1").Value & ".xlsx"
filePath = folderPath & targetSheet.Range("A2") & "\" & targetSheet.Range("A1") & " " & fileName
ThisWorkbook.Worksheets("Cash").Select
ThisWorkbook.SaveAs filePath, xlOpenXMLWorkbook
Else
' 4) if it doesn't, do open selected sheet to a new workbook and save that in clients name folder (folder and path given above in code section)
folderPath = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & targetSheet.Range("F3")
fileName = targetSheet.Range("F2") & " " & targetSheet.Range("B3") & ".xlsx"
filePath = folderPath & "\" & fileName
' 5) check if clients folder exist or not for the file to be saved in.
' if folder doesnt exist,
' create new and save file there.
CreateFoldersInPath folderPath
' if folder exist just save the file there
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Add
targetSheet.Copy before:=targetWorkbook.Sheets(1)
targetWorkbook.SaveAs filePath, 51
targetWorkbook.Close
End If
End If
Next targetSheet
End Sub
' Credits: https://stackoverflow.com/a/31034201/1521579
Private Sub CreateFoldersInPath(ByVal targetFolderPath As String)
Dim strBuildPath As String
Dim varFolder As Variant
If Right(targetFolderPath, 1) = "\" Then targetFolderPath = Left(targetFolderPath, Len(targetFolderPath) - 1)
For Each varFolder In Split(targetFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Let me know how it goes
How to copy the entire worksheet from a workbook and save it as new workbook to a specific directory with the customized filename(I am trying to pick the filename from on of the cells in the worksheet. The sheet that I need to copy has few merged cells too.
Sub CopyItOver()
Dim fname As String
Dim fpath As String
Dim NewBook As Workbook
Dim name as String
fpath = "C:\Users\..\"
fname = "List" & name & ".xlsm"
name = Range("c3").Value
Set NewBook = Workbooks.Add
ActiveWorkbook.Sheets("Generator").Copy Before:=NewBook.Sheets(1)
If Dir(fpath & "\" & fname) <> "" Then
MsgBox "File " & fpath & "\" & fname & " already exists"
Else
NewBook.SaveAs FileName:=fpath & "\" & fname
End If
End Sub
When I run this it, give me Subscript out of range error in this line
ActiveWorkbook.Sheets("Generator").Copy Before:=NewBook.Sheets(1)
Suggest you try it like this:
Check to see if Generator exists before progressing
If you use .Copy then the worksheet is automatically copied to a new workbook (so you don't need to add a new book first)
code
Sub CopyItOver()
Dim fname As String
Dim fpath As String
Dim name As String
Dim ws As Worksheet
fpath = "C:\Users\..\"
fname = "List" & name & ".xlsm"
name = Range("c3").Value
On Error Resume Next
Set ws = ThisWorkbook.Sheets("Generator")
On Error GoTo 0
If ws Is Nothing Then
MsgBox "sheet doesn't exist"
Exit Sub
End If
If Dir(fpath & "\" & fname) = vbNullString Then
ThisWorkbook.Sheets("Generator").Copy
ActiveWorkbook.SaveAs Filename:=fpath & "\" & fname
Else
MsgBox "File " & fpath & "\" & fname & " already exists"
End If
End Sub