简体   繁体   中英

Method 'SaveAs' of object '_Workbook' failed

I have a macro opening a set of Excel files in the Downloads folder, formatting data as table and then saving them into an online location on Sharepoint. Today, out of the blue, the macro stopped working (after about a month of problem-less usage), giving an error on the line Call wb.SaveAs... The error message is Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed . I am absolutely unable to find out what causes the error:

  • the wb variable is populated with the proper workbook reference
  • the target URL is valid and exists
  • the name does not contain any invalid character
  • I have access to the URL in question (in fact the macro is in a file stored in the same location)
  • there is no file of the same name on that location
  • it works when I debug.print the Filename argument and save on that location/name manually

There is a billion of questions on this error on Stack, however most of them seem to be tied with an issue with ActiveSheet object but I have a specific hard reference, so the solutions offered are not really applicable.

  Sub DataPrep()
    
    Dim wbTgt As Workbook: Set wbTgt = ThisWorkbook
    Dim wb As Workbook
    Dim sSrcPath As String: sSrcPath = Environ("UserProfile") & "\Downloads\"
    Dim sTgtPath As String: sTgtPath = "https://evilcorpportal.sharepoint.com/sites/folder1/folder2/folder3/folder4/folder5/"
    Dim sDate As String: sDate = Year(Date) & "-" & Format(Month(Date), "00") & "-" & Format(Day(Date), "00")
    Dim sWBs() As String: sWBs = Split("Rep1 " & sDate & ";Rep2 " & sDate & ";Rep3 " & sDate & ";Report4", ";")
    Dim sWBLocs() As String: sWBLocs = GetFileLocations(sSrcPath, sWBs)
    Dim sTblName As String
    
    Dim i As Integer
    
    For i = LBound(sWBLocs) To UBound(sWBLocs)
        Set wb = Workbooks.Open(sWBLocs(i))
        sTblName = Split(wb.Name, ".")(0)
        
        If InStr(sTblName, " ") > 0 Then sTblName = Left(sTblName, InStr(sTblName, " ") - 1)
        
        Call CreateTable(wb, sTblName)
        Call wb.SaveAs(Filename:=sTgtPath & sTblName & ".xlsx", FileFormat:=51)
        wb.Close
    Next i

  End Sub

So the issue was not in the code but somewhere on the Sharepoint. When I tried to do this step manually, it worked only in some 25 % of the cases (when I tested it before raising the question, I got lucky), otherwise it failed mid upload (both during saving into the online location, or saving offline and uploading manually). I presume the same happened during the macro execution and made it fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM