I am using a macro to open the latest file (downloaded from web service) from a folder and to save it from .xls to .xlsx for further operations.
The main operations (open latest and save as.xlsx) are done.
The last line in the code gets
Runtime Error 53.
The re-saved .xlsx file is there.
Sub TEST()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date
MyPath = "C:\Downloads\Test"
If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\"
MyFile = Dir(MyPath & "*.xls", vbNormal)
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile
LatestFile = Left(LatestFile, InStrRev(LatestFile, ".") - 1)
ActiveWorkbook.SaveAs Filename:=LatestFile, FileFormat:=51
ActiveWorkbook.Close
Kill LatestFile
End Sub
Look carefully what you are doing with your filename(s).
After the loop finishes, LatestFile
will contain the name of the latest file, without path.
You open that file - so far, so good.
Now you remove the extension from LatestFile
and uses this as file name for the SaveAs command. Here you have your first issue because you don't provide any path. Excel will store the file where ever it guesses is right. This used to be the current working directory, but I am not sure this is valid any more. You should in any case provide the path.
Ok, file is saved. Now you want to delete the xls
-version of the file. However, using LatestFile
now has 2 issues: Firstly, you cut the extension, so you try to delete a file that has no extension (and that doesn't exist). And furthermore, you provide no path, so the kill-command looks in the current working directory (which is likely not the download folder).
Workbooks.Open MyPath & LatestFile
Dim newFileName As String
' (Change the following line if you want to save the copy to a different location)
newFilename = MyPath & Left(LatestFile, InStrRev(LatestFile, ".") - 1)
ActiveWorkbook.SaveAs Filename:=newFileName, FileFormat:=51
ActiveWorkbook.Close
Kill MyPath & LatestFile
Hint: Learn to use the debugger, step thru the code and check what is going on. That helps you to understand your code and to see such problems.