Home » excel » excel – Copying File: ThisWorkbook.Path with FileSystemObject gives Bad Filename or Number error

excel – Copying File: ThisWorkbook.Path with FileSystemObject gives Bad Filename or Number error

Posted by: admin May 14, 2020 Leave a comment

Questions:

So before saving to the current XML file that my VBA code is working on, I want to create a timestamp based backup of the XML file in VBA. This is how I plan to do it:

Sub CreateBackup()
    Dim objFSO As FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    oldFilePath = ThisWorkbook.Path & "\DEMO.xml"
    newFilePath = ThisWorkbook.Path & "\DEMO" & Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss") & ".xml.bak"
    objFSO.CopyFile oldFilePath, newFilePath
End Sub

However, everytime I get a Bad Filename or Number error. I have double checked (using the debugger) that my variables are reading the correct filepath with filename. What gives?

How to&Answers:

: is not allowed in file names.

Replace

Format(DateTime.Now, "yyyy-MM-dd hh:mm:ss")

with

Format$(DateTime.Now, "yyyy-MM-dd hh_mm_ss")

for example.

Note that using Format$() returns a string instead of a variant (using Format()).