Loading an XLS file is a bit of a pain for a quick app we’re throwing together (we know about how to do that but it’s not worth the time especially in C++) so we’re going to take the simple approach of have the user export a CSV copy. However to save them the trouble I wondered if we can have a macro which will automatically save a CSV version whenever they save the XLS(X) in Excel 2007?
Update:
Following Timores’ answer, I dug in a bit and came up with this:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFileName As String
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set Sourcewb = ActiveWorkbook
TempFileName = Sourcewb.FullName + ".csv"
'Copy the sheet to a new workbook
ActiveSheet.Copy
Set Destwb = ActiveWorkbook
'Save the new workbook and close it
With Destwb
.SaveAs Filename:=TempFileName, FileFormat:=xlCSV, ConflictResolution:=xlLocalSessionChanges
.Close SaveChanges:=False
End With
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
This works except I can’t make it force-save the CSV, rather than asking me if I want to overwrite, even after adding ConflictResolution:=xlLocalSessionChanges
Original version:
In the VB editor part of Excel, select “ThisWorkbok” in the left navigation menu. In the editor on the right, select Workbook on the left drop-down, and BeforeSave on the right one.
Replace the macro by:
This will make a copy with the CSV extension.
Please note that an XLSX file cannot have a macro (you need an XLSM extension, or the older XLS one) and that users will need to have a medium or low level of security in order for the macro to run (or you have to sign the document).
Edited version:
I tested it again, after seeing the comments below. Strangely enough, it did not work like it did the first time. Here is a fixed version. Again, in the ‘This Workbook’ part of the macro editor:
What is surprising is that calling ActiveWorkbook.SaveAs triggers the macro again => the global boolean to prevent infinite recursion.