Duplicate workbook when saved into OneDrive sync folder - excel

I am having this weird problem when saving my sheet into onedrive sync folder. Basically what i am doing with the below code is that I copy a sheet from my workbook then save it into a sync folder. When it does this, a saved copy with the filename that is stored in a specific cell together with another copy with the same saved name with a 1 at the back of the file name will appear in the sync folder. When i step over to test the code, no such error occur. The error only occur if I run the macro. May i know why? Below is my code;
Sub SheetSplit1()
'
'Creates an individual workbook for each worksheet in the active workbook.
'
Dim wbDest As Workbook
Dim wbSource As Workbook
Dim sht As Object
Dim strSavePath As String
Dim sname As String
Dim relativepath As String
Set wbSource = ActiveWorkbook
'For Each sht In wbSource.Sheets
Sheet10.Copy
Set wbDest = ActiveWorkbook
sname = Sheet9.Range("I5") & "_" & _
Format(Sheet9.Range("I8"), "ddmmmyyyy") & ".xlsx"
relativepath = "C:\Users\" & Environ$("Username") & _
"\SharePoint\Open Project Transition Check - Doc\Transition Dashboard Report\" & sname 'use path of wbSource
'wbDest.Sheets(1).Range("A1").Clear 'clear filename from new workbook cell A1
Application.DisplayAlerts = False
ActiveWorkbook.CheckCompatibility = False
ActiveWorkbook.SaveAs Filename:=relativepath, FileFormat:=xlOpenXMLWorkbook, _
CreateBackup:=False
Application.DisplayAlerts = True
wbDest.Close False 'close the newly saved workbook without saving (we already saved)
'Next
MsgBox "DashBoard Report Saved!"
End Sub
Greatly appreciate anyone who could assist me. Thanks.

I wish I could give a definitive answer, or Microsoft would contribute.
I have similar connected problems. It seems that another version of the file may be or "appear to be" open elsewhere, thus preventing excel/Onedrive from completing the save action.
Rather than overwrite it(lets face t, that was the command) it creates a "version" filename(1).
I am guessing this is the same as when you do it manually and you are asked to resolve a conflict.
So far I have failed to find out how you can discover and solve the problem in code.
I solved it in one instance by mapping a drive on the offending desktop and first closing any open versions before save, but that is not a robust long term solution.
Test this by setting Application.DisplayAlerts = True and capturing errors.
"On error got catch" after the last dimension line then
"exit function
catch:
msgbox err.description"
before "end sub"

Related

Copy a Worksheet into a new Workbook

I get a runtime error with ws.copy -> without the code works but just creates an empty workbook.
Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
' Create a new workbook
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add
' Copy the worksheet to the new workbook
ws.Copy 'After:=newWorkbook.Worksheets(1)
' Save the new workbook
newWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
newWorkbook.Close SaveChanges:=False
End Sub
Copy Sheet to a New Workbook
If you replace As Worksheet with As Object, the procedure will also work for charts.
To reference the last opened workbook, you can safely use Workbook(Workbooks.Count).
Turn off Application.DisplayAlerts to overwrite without confirmation. If you don't do this, when the file exists, you'll be asked to save it. If you select No or Cancel, the following error will occur:
Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed
If your intent is to reference the sheet's workbook, you can use the .Parent property. Then the procedure will not be restricted just to the workbook containing this code (ThisWorkbook). Otherwise, replace Sheet.Parent with ThisWorkbook.
If you instead of the backslash (\) use Application.PathSeparator, the procedure will also work on computers with a different operating system than Windows.
For a new workbook, the default type is .xlsx so you don't need to specify the file extension or format.
Sub SaveSheetAsXlsx(ByVal Sheet As Object)
' Copy the sheet to a new single-sheet workbook.
Sheet.Copy
' Reference, save and close the new workbook.
Dim nwb As Workbook: Set nwb = Workbooks(Workbooks.Count)
Application.DisplayAlerts = False ' overwrite without confirmation
nwb.SaveAs Sheet.Parent.Path & Application.PathSeparator & Sheet.Name
Application.DisplayAlerts = True
nwb.Close False
End Sub
set newWorkbook = workbooks.Add creates a new workbook. But ws.Copy without arguments copies ws to a new workbook. Now you have two new workbooks which is clearly not what you intend. MS learning documents gives an example of how to do copy a worksheet in its documentation on the copy command. Reference: https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.copy
Sub foo()
Call SaveWorksheetAsXlsx(Worksheets("Sheet3"))
End Sub
Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
If Not CreateObject("Scripting.FileSystemObject").FileExists(filePath) Then
ws.Copy
ActiveWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=False
Else
MsgBox "Error: unable to save file. File already exists: " + filePath
End If
End Sub
This obviously relies on the expected behavior that when you copy a worksheet to a new workbook that workbook becomes the active workbook. I have used this before without any problems (for many years I guess), although it does make me a little nervous relying on default behaviors. So you may consider adding some guard clauses, perhaps only saving the workbook if it has an empty path (i.e., ensure it is a newly added workbook -> if ActiveWorkbook.Path = "". So, coding prophylacticly and very cautiously:
Sub foo()
Call SaveWorksheetAsXlsx(Worksheets("Sheet3"))
End Sub
Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
If Not CreateObject("Scripting.FileSystemObject").FileExists(filePath) Then
ws.Copy
If ActiveWorkbook.Path = "" Then 'Extra check to ensure this is a newly created and unsaved workbook
ActiveWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close SaveChanges:=False
Else
MsgBox "Unexpected error attempting to save file " + filePath
End If
Else
MsgBox "Error: unable to save file. File already exists: " + filePath
End If
End Sub

To save single worksheet in Excel to source folder with desired name

I have a macro enabled workbook in my local folder. This workbook consists of 7 worksheet in total. Last sheet named as "AnsSheet".
I want to save the last sheet (AnsSheet only) in the same folder location with modified name.
Here is the code I am using which is not giving desired result.
Could you please guide?
Sheets("AnsSheet").Select
Set wb = Workbooks.Add
ThisWorkbook.Sheets("AnsSheet").Copy Before:=wb.Sheets(1)
ActiveSheet.SaveAs Filename:=ActiveWorkbook.Path & "\WF_Macro_" & Format(Date, "DD-MMM-YYYY") & ".xls"
Your Filename will be incomplete as ActiveWorkbook.Path will be blank. The ActiveWorkbook will be your newly created Workbook, and as you haven't saved it yet the Path will be empty. Use ThisWorkbook instead to get the path of the current Workbook.
I'm not sure if the ActiveSheet.SaveAs method will work but I haven't looked into it. Personally I would use the Workbook.SaveAs method to save the new Workbook. Also, instead of adding ".xls" to the end of the filename, you should specify the filetype using the FileFormat parameter MSDN FileFormat Enum
I've updated your code below with comments to help see what is going on:
Dim wb As Excel.Workbook
'\\ Create a new Workbook with only one Worksheet
Set wb = Workbooks.Add(xlWBATWorksheet)
'\\ Copy Sheet to start of new Workbook
ThisWorkbook.Sheets("AnsSheet").Copy Before:=wb.Sheets(1)
'\\ Turn off alerts and delete the unused sheet, turn alerts back on
Application.DisplayAlerts = False
wb.Sheets(2).Delete
Application.DisplayAlerts = True
'\\ Save new Workbook as a standard Workbook
wb.SaveAs Filename:=ThisWorkbook.Path & "\WF_Macro_" & Format(Date, "DD-MMM-YYYY"), _
FileFormat:=xlWorkbookNormal

Getting "method saveas of object _workbook failed" error while trying to save an XLSM as CSV

I'm trying to save a macro-enabled Excel workbook as a csv file, overwriting the old one (below I had to change the name of the folder and the Sheet, but that doesn't seem to be the issue).
Sub SaveWorksheetsAsCsv()
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
SaveToDirectory = "\MyFolder\"
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
Sheets("My_Sheet").Copy
ActiveWorkbook.SaveAs Filename:=SaveToDirectory & "My_Sheet" & ".csv", FileFormat:=xlCSV
ActiveWorkbook.Close SaveChanges:=False
ThisWorkbook.Activate
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
Application.AlertBeforeOverwriting = True
End Sub
Sometimes it fails with
Runtime Error 1004: method saveas of object _workbook failed**)
The debugger points out:
ActiveWorkbook.SaveAs Filename:=SaveToDirectory & "My_Sheet" & ".csv", FileFormat:=xlCSV
I googled and some of the solutions I tried were:
Specifiying that the directory is a string
Avoid any special character in the file name or folder (seen here)
Copy paste the worksheet as value before saving it as .csv (seen here)
Specifying the FileFormat with the .csv code number (seen here)
Disabling/Re-enabling some of the alerts
Adding other fields in the ActiveWorkbook.SaveAs row, regarding passwords, creating backups etcetc
Still, it might run correctly up to 50-60 times in a row, and then at some point fail again.
Any suggestion, except stop using VBA/Excel for this task, which will happen soon, but I can't for now.
EDIT: Solved thanks to Degustaf suggestion. I made only two changes to Degustaf's suggested code:
ThisWorkbook.Sheets instead of CurrentWorkbook.Sheets
FileFormat:=6 instead of FileFormat:=xlCSV (apparently is more robust
to different versions of Excel)
Sub SaveWorksheetsAsCsv()
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
Dim TempWB As Workbook
Set TempWB = Workbooks.Add
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
SaveToDirectory = "\\MyFolder\"
Application.DisplayAlerts = False
Application.AlertBeforeOverwriting = False
ThisWorkbook.Sheets("My_Sheet").Copy Before:=TempWB.Sheets(1)
ThisWorkbook.Sheets("My_Sheet").SaveAs Filename:=SaveToDirectory & "My_Sheet" & ".csv", FileFormat:=6
TempWB.Close SaveChanges:=False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
ActiveWorkbook.Close SaveChanges:=False
Application.DisplayAlerts = True
Application.AlertBeforeOverwriting = True
End Sub
I generally find that ActiveWorkbook is the problem in these cases. By that I mean that somehow you don't have that workbook (or any other) selected, and Excel doesn't know what to do. Unfortunately, since copy doesn't return anything (the copied worksheet would be nice), this is a standard way of approaching this problem.
So, we can approach this as how can we copy this sheet to a new workbook, and get a reference to that workbook. What we can do is create the new workbook, and then copy the sheet:
Dim wkbk as Workbook
Set Wkbk = Workbooks.Add
CurrentWorkbook.Sheets("My_Sheet").Copy Before:=Wkbk.Sheets(1)
Wkbk.SaveAs Filename:=SaveToDirectory & "My_Sheet" & ".csv", FileFormat:=xlCSV
Wkbk.Close SaveChanges:=False
Or, there is an even better approach in a situation like this: WorkSheet supports the SaveAs method. No copy necessary.
CurrentWorkbook.Sheets("My_Sheet").SaveAs Filename:=SaveToDirectory & "My_Sheet" & ".csv", FileFormat:=xlCSV
I will warn you to resave the workbook to its original name afterwards, if it is staying open, but you already have that in your code.
This is a year old, but I'll add something for future readers
You won’t find a lot of documentation in Excel help for Run-time error 1004 as Microsoft doesn't consider it to be an Excel error.
The answers above are 100% valid but sometimes it helps to know what is causing the problem so you can avoid it, fix it earlier or fix it more easily.
The fact that this is an intermittent fault, and it is fixed by saving with the full path and file name tells me that either your macro may be trying to save an .xlsb file to the autorecover directory after an auto file recovery.
Alternatively, you may have edited the file's path or filename yourself.
You can check the path and filename with:-
MsgBox ThisWorkbook.FullName
You should see something like this in the message box.
C:\Users\Mike\AppData\Roaming\Microsoft\Excel\DIARY(version 1).xlxb
If so the solution is (as stated above by others) to save your file to its correct path and file name. This can be done with VBA or manually.
I am now in the habit of manually saving the file with its correct path and filename as a matter of course after any autorecover action as it takes seconds and I find it quicker (if this is not a daily occurrence). Thus, the macros will not encounter this fault you run it. Remember that while my habit of manually saving .xlxb files to .xlsm files immediately after a recovery won't help a novice that you give the worksheet to.
A note on Hyperlinks
After this error: If you have hyperlinks in your worksheet created with Ctrl+k in all likelihood, you will have something like "AppData\Roaming\Microsoft\", "\AppData\Roaming\", "../../AppData/Roaming/"or "....\My documents\My documents\" in multiple hyperlinks after file recovery. You can avoid these by attaching your hyperlinks to a text box or generating them with the HYPERLINK function.
Identifying and Repairing them is a little more complicated
First, examine the hyperlinks and determine the erroneous strings and the correct string for each error. Over time, I have found several.
Excel doesn't provide a facility in the 'Go To Special' menu to search for hyperlinks created with Ctrl+k.
You can automate the identification of erroneous hyperlinks in a helper column, say column Z and using the formula
=OR(ISNUMBER(SEARCH("Roaming", Link2Text($C2),1)),ISNUMBER(SEARCH("Roaming", Link2Text($D2),1)))
where Link2Text is the UDF
Function Link2Text(rng As Range) As String
' DO NOT deactivate.
' Locates hyperlinks containing 'roaming' in column Z.
' Identify affected hyperlinks
If rng(1).Hyperlinks.Count Then
Link2Text = rng.Hyperlinks(1).Address
End If
End Function
My VBA to correct the errors is as follows
Sub Replace_roaming()
' Select the correct sheet
Sheets("DIARY").Select
Dim hl As Hyperlink
For Each hl In ActiveSheet.Hyperlinks
hl.Address = Replace(hl.Address, "AppData\Roaming\Microsoft\", "")
Next
For Each hl In ActiveSheet.Hyperlinks
hl.Address = Replace(hl.Address, "AppData\Roaming\", "")
Next
For Each hl In ActiveSheet.Hyperlinks
hl.Address = Replace(hl.Address, "../../AppData/Roaming/", "..\..\My documents\")
Next
For Each hl In ActiveSheet.Hyperlinks
hl.Address = Replace(hl.Address, "..\..\My documents\My documents\", "..\..\My documents\")
Next
Application.Run "Recalc_BT"
' Move down one active row to get off the heading
ActiveCell.Offset(1, 0).Select
' Check active row location
If ActiveCell.Row = 1 Then
ActiveCell.Offset(1, 0).Select
End If
' Recalc active row
ActiveCell.EntireRow.Calculate
' Notify
MsgBox "Replace roaming is now complete."
End Sub
I also recommend you get in the habit of doing regular backups and not relying on autorecover alone. If it fails, you have nothing since your last full backup.
While the worksheet is being fragile backup often, like every hour or after any significant import of new data.
The following shortcuts will backup your worksheet in seconds: Ctrl+O, [highlight the filename], Ctrl+C, Ctrl+V, [ X ]. Regular backups allow you to go immediately to your most recent backup without having to restore from last night's backup file especially if you have to make a request of another person to do this.
It's been a while since the last answer here, but I want to share my experience from today:
After weeks of reliable operation, I ran into the same error all of a sudden without having anything changed in the code section where the workbook is saved.
Thanks to the previous answers I updated my saveas statement from a simple
wb.saveas strfilename
to
wb.saveas Filename:=strfilename, Fileformat:= xlWorkbookDefault
et voilà: it worked again.
Sometimes the Microsoft applications behave really strange...
Try combining the Path and the CSV file name into a string variable and drop the .csv; that is handled by the FileFormat. Path must be absolute starting with a drive letter or Server Name:
Dim strFullFileName as String
strFullFileName = "C:\My Folder\My_Sheet"
If on a Server then it would look something like this:
strFullFileName = "\\ServerName\ShareName\My Folder\My_Sheet"
Substiture ServerName with your Server name and substitute ShareName with the your network Share name e.g. \\data101\Accounting\My Folder\My_Sheet
ActiveWorkbook.SaveAs Filename:=strFullFileName,FileFormat:=xlCSVMSDOS, CreateBackup:=False
I had a similar issue however for me the problem was I was creating the Filename based on strings extracted from a workbook and sometimes these strings would have characters that can't be in a filename.
Removing these characters did the trick for me!
For me there was an issue with not all formulas being calculated, despite having it on "Automatic". I pressed calculate on the bottom left 100 times and then it magically worked.

Merging workbooks into a new file

I'm trying to merge multiple Excel files from one Folder into a new file. I've found a solution on the Internet, that is adding my files into an open one. I'm not really into VBA Excel, so I think it's a basic problem, but I can't do it, things I've tried haven't worked properly. I would like to change the following code to create a new file called "summary" in the "Path" and copy the Sheets into this new file, overwriting the file every time I do it and deleting the several source files after doing this.
Is there a possibility of merging all those files into one without opening everyone of it?
Sub GetSheets()
Path = "C:\Merging\"
FileName = Dir(Path & "*.xls")
Do While FileName <> ""
Workbooks.Open FileName:=Path & FileName, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(FileName).Close
FileName = Dir()
Loop
End Sub
Your code almost works as is, just needs a couple of slight tweaks. I also agree with #AnalystCave that if this is a repeating exercise, you may consider a more streamlined solution. But this will work for you.
EDIT: changed to deal with existing destination file -- if it exists and is open, then connect to it otherwise open it; then delete all sheets in the existing file to prepare for the copies
Option Explicit
Function IsSheetEmpty(sht As Worksheet) As Boolean
IsSheetEmpty = Application.WorksheetFunction.CountA(sht.Cells) = 0
End Function
Sub GetSheets()
Dim Path, Filename As String
Dim Sheet As Worksheet
Dim newBook As Workbook
Dim appSheets As Integer
Dim srcFile As String
Dim dstFile As String
Dim dstPath As String
Dim wasntAlreadyOpen As Boolean
Application.ScreenUpdating = False 'go faster by not waiting for display
'--- create a new workbook with only one worksheet
dstFile = "AllSheetsHere.xlsx"
dstPath = ActiveWorkbook.Path & "\" & dstFile
wasntAlreadyOpen = True
If Dir(dstPath) = "" Then
'--- the destination workbook does not (yet) exist, so create it
appSheets = Application.SheetsInNewWorkbook 'saves the default number of new sheets
Application.SheetsInNewWorkbook = 1 'force only one new sheet
Set newBook = Application.Workbooks.Add
newBook.SaveAs dstFile
Application.SheetsInNewWorkbook = appSheets 'restores the default number of new sheets
Else
'--- the destination workbook exists, so ...
On Error Resume Next
wasntAlreadyOpen = False
Set newBook = Workbooks(dstFile) 'connect if already open
If newBook Is Nothing Then
Set newBook = Workbooks.Open(dstPath) 'open if needed
wasntAlreadyOpen = True
End If
On Error GoTo 0
'--- make sure to delete any/all worksheets so we're only left
' with a single empty sheet named "Sheet1"
Application.DisplayAlerts = False 'we dont need to see the warning message
Do While newBook.Sheets.Count > 1
newBook.Sheets(newBook.Sheets.Count).Delete
Loop
newBook.Sheets(1).Name = "Sheet1"
newBook.Sheets(1).Cells.ClearContents
newBook.Sheets(1).Cells.ClearFormats
Application.DisplayAlerts = True 'turn alerts back on
End If
Path = "C:\Temp\"
Filename = Dir(Path & "*.xls?") 'add the ? to pick up *.xlsx and *.xlsm files
Do While Filename <> ""
srcFile = Path & Filename
Workbooks.Open Filename:=srcFile, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
'--- potentially check for blank sheets, or only sheets
' with specific data on them
If Not IsSheetEmpty(Sheet) Then
Sheet.Copy After:=newBook.Sheets(1)
End If
Next Sheet
Workbooks(Filename).Close (False) 'add False to close without saving
Kill srcFile 'deletes the file
Filename = Dir()
Loop
'--- delete the original empty worksheet and save the book
If newBook.Sheets.Count > 1 Then
newBook.Sheets(1).Delete
End If
newBook.Save
'--- leave it open if it was already open when we started
If wasntAlreadyOpen Then
newBook.Close
End If
Application.ScreenUpdating = True 're-enable screen updates
End Sub
Firstly, regardless of your solution you will still need to OPEN every Excel workbook if you want to merge all of them.
Secondly, I think you might want to rephrase your question to "Is there a possibility of merging all those files into one faster or in any easier way?"
From the level of Excel VBA there is really no other way then opening each Workbook within the same Application level. If this is a one-time exercise I would stick to the code you already have and bear with it.
However, if this is an exercise you will be doing repeatedly and need an efficient solution, your only option is resorting to the OpenXML format which does not require a heavyweight Excel process e.g. creating a C# solution using the ClosedXML library. This will definitely reduce the time needed to consolidate your workbooks.

Why does VBA ActiveWorkbook.SaveAs change the open spreadsheet?

My function is as follows:
Sub saveCSV()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= _
"c:\temp\file.csv", FileFormat:=xlCSV _
, CreateBackup:=False
End Sub
I'm trying to export the active worksheet to CSV. When I run the code in the title, Book1.xlsm changes to file.csv and Sheet1 changes to file. The export works fine. How can I do the export without these unwanted side effects?
That's always how SaveAs has worked. The only way to get around this is to copy the worksheet and do a SaveAs on the copy, then close it.
EDIT: I should add an example as it's not that difficult to do. Here's a quick example that copies the ActiveSheet to a new workbook.
Dim wbk As Workbook
Set wbk = Workbooks.Add
ActiveSheet.Copy wbk.Sheets(1) ' Copy activesheet before the first sheet of wbk
wbk.SaveAs ....
wbk.Close
A complicated workbook may get issues with links and macros, but in ordinary scenarios this is safe.
EDIT 2: I'm aware of what you're trying to do, as your other question was about trying to trigger an export on every change to the sheet. This copy sheet approach presented here is likely to be highly disruptive.
My suggestion is to write a CSV file by hand to minimise GUI interruption. The sheet is likely to become unusable if the saves are occurring at high frequency. I wouldn't lay the blame for this at the door of Excel, it simply wasn't built for rapid saves done behind the scenes.
Here's a little routine that does what you want by operating on a copy of the original ... copy made via file scripting object. Hardcoded to operate on "ThisWorkbook" as opposed to active workbook & presumes ".xlsm" suffix - could tweak this to do the job I think:
Public Sub SaveCopyAsCsv()
Dim sThisFile As String: sThisFile = ThisWorkbook.FullName
Dim sCsvFile As String: sTempFile = Replace(sThisFile, ".xlsm", "_TEMP.xlsm")
ThisWorkbook.Save ' save the current workbook
' copy the saved workbook ABC.xlsm to TEMP_ABC.xlsm
Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Call fso.deletefile(sTempFile, True) ' deletes prev temp file if it exists
On Error GoTo 0
Call fso.CopyFile(sThisFile, sTempFile, True)
' open the temp file & save as CSV
Dim wbTemp As Workbook
Set wbTemp = Workbooks.Open(sTempFile) ' open the temp file in excel
' your prev code to save as CSV
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs FileName:="c:\temp\file.csv", FileFormat:=xlCSV, CreateBackup:=False
wbTemp.Close ' close the temp file now that the copy has been made
Application.DisplayAlerts = True
' delete the temp file (if you want)
On Error Resume Next
Call fso.deletefile(sTempFile, True) ' deletes the temp file
On Error GoTo 0
End Sub

Resources