0

I've been running into issues for a while with trying to save Excel files in new folders. I think that it's connected to OneDrive folders trying to sync, but I can't find anything that helps confirm this issue. I've included a sample piece of code that replicates the issue I've had. If I run this once (creating a new folder), then I will get a SaveAs error. But if I immediately run it again, it will just ask to overwrite the file and it will save just fine. Is there a way to go about handling the save as error or to continue to try until it's saved successfully?

Sub save_file()

    Dim folder_path As String
    
    folder_path = "C:\Users\" & Environ("USERNAME") & "\OneDrive - Company Name\Desktop\Test Folder"
    
    If Len(Dir(folder_path, vbDirectory)) = 0 Then
        MkDir (folder_path)
    End If
    
    Dim new_book As Workbook
    
    Set new_book = Workbooks.Add
    
    new_book.SaveAs Filename:=folder_path & "\Test Book", FileFormat:=51
    
End Sub

EDIT: I was able to find a potential workaround, although I haven't done much yet to test it. This file is still being saved to the folder, so I can close the file that gives the save error, and then just reopen it (here also setting it as the same Workbook object for reuse.

Sub save_file()

    Dim folder_path As String
    
    folder_path = "C:\Users\" & Environ("USERNAME") & "\OneDrive - Company Name\Desktop\Test Folder " & Format(Now, "HHMMSS")
    
    If Len(Dir(folder_path, vbDirectory)) = 0 Then
        MkDir (folder_path)
    End If
    
    Dim new_book As Workbook
    
    Set new_book = Workbooks.Add
    
    book_name = folder_path & "\Test Book " & Format(Now, "HHMMSS")
    
    On Error GoTo savehandler
    new_book.SaveAs Filename:=book_name, FileFormat:=51
    
    Exit Sub
    
savehandler:
    new_book.Close
    Set new_book = Workbooks.Open(book_name)
    
End Sub
tydangel
  • 1
  • 3
  • 1
    Runs fine against OneDrive for me. You could look into [Error](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/on-error-statement) [Handling](https://stackoverflow.com/questions/1038006/what-are-some-good-patterns-for-vba-error-handling) and loop the save a few times if it throws an error. What exactly is the error? – Christofer Weber Jan 25 '22 at 16:38
  • @ChristoferWeber, it's Run-time error '1004': Method 'SaveAs of object '_Workbook' failed – tydangel Jan 25 '22 at 17:00

0 Answers0