Code Or Command To Open XLSM Files And Close And Save As CSV

Dazzawm

Well-known Member
Joined
Jan 24, 2011
Messages
3,748
Office Version
  1. 365
Platform
  1. Windows
Hi, is there a code or command that will open a load of xlsm files within a folder and then close and save them as csv files either in the same folder or a specified location? Thanks.
 

Excel Facts

Select all contiguous cells
Pressing Ctrl+* (asterisk) will select the "current region" - all contiguous cells in all directions.
Surely someone can help with this please??!! :)
 
Upvote 0
Hi Daz, thanks for the pm.

This will probably need some editing at your end so I will walk you through the code.

First we set up the folder to process, REMEMBER the trailing backslash, and set the file variable to the first XLSM file in that folder.
Rich (BB code):
   sPath = "C:\temp\" 'REMEMBER TRAILING BACKSLASH
   sFile = Dir(sPath & "*.xlsm")

You will get an alert when saving as a csv file, i.e., only one sheet, lose Excel functionality, etc; so we will disable alerts. An error trap will ensure the application settings are reset before the code ends.
Rich (BB code):
   'disable saving CSV alerts - use error trap to ensure application settings are reset
   On Error GoTo errHandler
   Application.DisplayAlerts = False

We loop through the files until no more XLSM files are found:
Rich (BB code):
   'loop through the folder
   Do Until sFile = ""

Set the source workbook variable, open the SOURCE wourbook and build up the new file name:
Rich (BB code):
      'open the workbook and build the new file name
      Set wbSource = Workbooks.Open(sPath & sFile)
      newFileName = sPath & Replace(wbSource.Name, "xlsm", "") & ".csv"

ASSUME the sheet to be saved as csv is the first worksheet - EDIT if necessary.
Copy this sheet into a new target workbook.
Save the target workbook as a csv file.
Close source and target files.
Rich (BB code):
      'ASSUME sheet to be saved as csv is first worksheet
      wbSource.Worksheets(1).Copy
      Set wbTarget = ActiveWorkbook
      wbTarget.SaveAs Filename:=newFileName, FileFormat:=xlCSV
      wbTarget.Close SaveChanges:=False
      wbSource.Close SaveChanges:=False

Clear the variables from memory and get the next file.
Rich (BB code):
      'get next fileThis will probably need some editing at your end
      Set wbSource = Nothing
      Set wbTarget = Nothing
      sFile = Dir()
   Loop

And end of with our error trap ensuring the Application setting we disabled are reset.
Rich (BB code):
errHandler:
   Application.DisplayAlerts = True
End Sub

Putting it all together, place the code in a standard module, i.e., Insert=>Module.
Rich (BB code):
Option Explicit


Sub SaveAsCsv()
   Dim sPath As String
   Dim sFile As String
   Dim wbSource As Workbook
   Dim wbTarget As Workbook
   Dim newFileName As String
   
   sPath = "C:\temp\" 'REMEMBER TRAILING BACKSLASH
   sFile = Dir(sPath & "*.xlsm")
   
   'disable saving CSV alerts - use error trap to ensure application settings are reset
   On Error GoTo errHandler
   Application.DisplayAlerts = False
   
   'loop through the folder
   Do Until sFile = ""
      
      'open the workbook and build the new file name
      Set wbSource = Workbooks.Open(sPath & sFile)
      newFileName = sPath & Replace(wbSource.Name, "xlsm", "") & ".csv"
      
      'ASSUME sheet to be saved as csv is first worksheet
      wbSource.Worksheets(1).Copy
      Set wbTarget = ActiveWorkbook
      wbTarget.SaveAs Filename:=newFileName, FileFormat:=xlCSV
      wbTarget.Close SaveChanges:=False
      wbSource.Close SaveChanges:=False
      
      'get next fileThis will probably need some editing at your end
      Set wbSource = Nothing
      Set wbTarget = Nothing
      sFile = Dir()
   Loop
   
errHandler:
   Application.DisplayAlerts = True
End Sub

Hope this helps,
Bertie
 
Upvote 0
Update - I have edited the highlighted line.

Rich (BB code):
Option Explicit


Sub SaveAsCsv()
   Dim sPath As String
   Dim sFile As String
   Dim wbSource As Workbook
   Dim wbTarget As Workbook
   Dim newFileName As String
   
   sPath = "C:\temp\" 'REMEMBER TRAILING BACKSLASH
   sFile = Dir(sPath & "*.xlsm")
   
   'disable saving CSV alerts - use error trap to ensure application settings are reset
   On Error GoTo errHandler
   Application.DisplayAlerts = False
   
   'loop through the folder
   Do Until sFile = ""
      
      'open the workbook and build the new file name
      Set wbSource = Workbooks.Open(sPath & sFile)
      newFileName = sPath & Replace(wbSource.Name, ".xlsm", ".csv")
      
      'ASSUME sheet to be saved as csv is first worksheet
      wbSource.Worksheets(1).Copy
      Set wbTarget = ActiveWorkbook
      wbTarget.SaveAs Filename:=newFileName, FileFormat:=xlCSV
      wbTarget.Close SaveChanges:=False
      wbSource.Close SaveChanges:=False
      
      'get next file
      Set wbSource = Nothing
      Set wbTarget = Nothing
      sFile = Dir()
   Loop
   
errHandler:
   Application.DisplayAlerts = True
End Sub
 
Upvote 0
Daz also asked for my help, so we have two people working on the same thing. Here is my approach:

Code:
Sub UseFileDialogOpen()
' use these key combinations on the file selecting dialog:
' one file = click      block = shift+click         non contiguous = control+click


Dim cnt%, ws As Worksheet
With Application.FileDialog(msoFileDialogOpen)
    .AllowMultiSelect = True
    .Show
    For cnt = 1 To .SelectedItems.Count
        Application.Workbooks.Open (.SelectedItems(cnt))
        For Each ws In ActiveWorkbook.Worksheets
            ws.SaveAs "C:\Users\Public\Documents\" & ws.Name & Replace(Time, ":", "_") & ".csv", xlCSV
        Next
        ActiveWorkbook.Close False
    Next
End With
End Sub
 
Upvote 0
Update - I have edited the highlighted line.
Rich (BB code):
Rich (BB code):
Option Explicit


Sub SaveAsCsv()
   Dim sPath As String
   Dim sFile As String
   Dim wbSource As Workbook
   Dim wbTarget As Workbook
   Dim newFileName As String
   
   sPath = "C:\temp\" 'REMEMBER TRAILING BACKSLASH
   sFile = Dir(sPath & "*.xlsm")
   
   'disable saving CSV alerts - use error trap to ensure application settings are reset
   On Error GoTo errHandler
   Application.DisplayAlerts = False
   
   'loop through the folder
   Do Until sFile = ""
      
      'open the workbook and build the new file name
      Set wbSource = Workbooks.Open(sPath & sFile)
      newFileName = sPath & Replace(wbSource.Name, ".xlsm", ".csv")
      
      'ASSUME sheet to be saved as csv is first worksheet
      wbSource.Worksheets(1).Copy
      Set wbTarget = ActiveWorkbook
      wbTarget.SaveAs Filename:=newFileName, FileFormat:=xlCSV
      wbTarget.Close SaveChanges:=False
      wbSource.Close SaveChanges:=False
      
      'get next file
      Set wbSource = Nothing
      Set wbTarget = Nothing
      sFile = Dir()
   Loop
   
errHandler:
   Application.DisplayAlerts = True
End Sub


Thanks Bertie works great for saving in the same location, how about if I want to save to a different folder, what needs changing please?
 
Upvote 0
When building the new file name, replace the path variable with the new path in this line:
For example., change this:
Rich (BB code):
      newFileName = sPath & Replace(wbSource.Name, ".xlsm", ".csv")

to (again, REMEMBER the trailing backslash)
Rich (BB code):
      newFileName = "C:\temp\archive\" & Replace(wbSource.Name, ".xlsm", ".csv")
 
Upvote 0
Thanks so much Bertie works great. Could I ask one last thing without trying to over complicate things. All the files I will be opening are named in the format of WRegs_Catalog2.3N or Leads_Catalog2.6F etc. When I save them in the specified location can everything before (and including the underscore) be removed and overwrite everything in the file. So I would be left in this instance with Catalog2.3N or Catalog2.6F etc. Thanks.

If its too tricky or having to rewrite a lot I understand.
 
Upvote 0

Forum statistics

Threads
1,215,094
Messages
6,123,071
Members
449,092
Latest member
ipruravindra

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top