Saving Excel Files to Sharepoint using VBA - excel

I am attempting to run a query in Excel and update the data to Sharepoint (accessible via Teams) on a set schedule.
Desired folder destination:
https://rxsafeway.sharepoint.com/:f:/r/sites/EXELiveProductionTool/Shared%20Documents/General/Portland/Individual%20Performance%20Update?csf=1&web=1&e=oFwj6i
VBA code used:
ThisWorkbook.SaveAs Filename:="https://rxsafeway.sharepoint.com/sites/EXELiveProductionTool/Shared%20Documents/General/Portland/Individual%20Performance%20Update/" & ".xlsm"
Details:
-The above VBA code has been used successfully while connected to VPN and on the company network.
-It works inconsistently... Potentially an upload limit?
-Notice that the "/:f:/r/" has been removed, a "/" has been added after "Update", and everything passed "Update" has been removed in the working code
Question:
Sometimes the code works and sometimes I get a Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed
Is there a syntax error, or a smarter way to save the file?

You probably getting this error due to the MAX_PATH 256 limitation.
Your filename is too long and therefore will have a longer Windows path as well.
I suggest you to view your SharePoint files in File Explorer (see the documentation here). By doing so, every file/folder in your sharepoint will have a normal path and you'll not have anymore to use your file's url.
After that, you can use this formula to save your xlsm in some location in sharepoint :
Path="C:\Users\AKow\Sharepoint_Name\Path_to_your_file"
Filename = "Individual Performance Update"
ThisWorkbook.SaveAs Filename:= Path & Filename, FileFormat:=xlOpenXMLWorkbookMacroEnabled

Related

SaveAs to SharePoint

I am using the following to save a file to s SP folder
wbCO.SaveAs Filename:=strFile, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
The path and file name are all valid and correct so this is not the issue.
strFile = "https://xxx.sharepoint.com/sites/xxx/Shared Documents/Properties/PropertyName/PropertyName_16_Apr.xlsx"
I am getting an odd issue where the file saves with the stated filename but I get a 1004 error saying document not saved.
I have had thsi file working at times and then sometimes it doesn't and I'm guessing it's because it is saving to SP which I always have issues with when using.
I am running this on a Windows platform but it ultimately needs to work on a Mac platform. I know the majority of the code is working but the SaveAs line falls over so help with this would be useful too!
TIA

'Save As' of object '_workbook' failed

I am trying to save a workbook as xlsm, this is the code I use:
ThisWorkbook.SaveAs Filename:="path\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
I have done some testing, and It does in fact save in both a private folder and a public or shared folder
however when I save it in a shared folder I also get this:
Run-time error '1004' Method 'Save As' of object '_workbook' failed
why do I get error message when it is saved in a public/shared folder, or onedrive?
In your string containing path there is variable "path" i suppose. Then you should write it like this:
Dim path as String: path = "C:\Users\xxx\Desktop"
ThisWorkbook.SaveAs Filename:=path & "\workbook_name.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Or you can hardcode full path (but i recommend using variables - first example).
ThisWorkbook.SaveAs Filename:="C:\Users\xxx\Desktop\file.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Then when you can save it manually and you have permissions then i have no idea since i normally save files to shared folders and network drives... Maybe your specific path is wrong. It is best to save using servername and folders...
path = "\\servername\folder1\folder2\workbook_name.xlsm"
Because sometimes when you refefer to mapped drive for example X:\folder2 then you must ensure that all users have it mapped in same way (someone uses X someone uses R etc.). And if path is correct then only other way i can think of it is permission issue, but if you can save it manually then i have sadly no idea... :)

How do I upload a file to OneDrive Business (Sharepoint) with VBA

I'm trying to find a method to upload a file to Onedrive from VBA in Excel.
I've done a lot of searching for acceptable methods, but most methods will not work for my scenario or the proposed solution will give an error.
I can upload files just fine if I'm using UNC paths or OneDrive locations that are synced locally (e.g. "C:\Users(username)\OneDrive\File Share") but I need a method that lets me push(upload) files to a shared URL location (e.g. "https://my.sharepoint.com/:f:/r/personal/(email_address)/Documents/SharedFiles?csf=1&e=6WmUIO"). All the users that will need to use the tool will have access to this shared location in OneDrive.
I tried the normal "SaveAs" method in VBA but that won't work.
Set Excelwb = ThisWorkbook
Excelwb.SaveAs fileName:="https://my.sharepoint.com/:f:/r/personal/(email_address)/Documents/SharedFiles?csf=1&e=6WmUIO" _
, FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=xlLocalSessionChanges
Excelwb.Saved = True
Excelwb.Close SaveChanges:=False
Application.DisplayAlerts = True
I expected this to save the file, but I understand that since I'm saving to a URL and not a local file that another method is probably required, but I can't find one that will work.
The error I'm getting is:
Run-time error '1004'
Method 'SaveAs' of object '_Workbook' failed
I just tried this and it worked fine:
Activeworkbook.SaveAs "https://myComany.sharepoint.com/Departments/dept1/Documents/FGH/Text.xlsx"
To get the required path, browse to the destination in IE, then use Library tab >> Open with Explorer to open the destination in Windows Explorer: you can copy the path from the address bar there.
Maybe this will help someone pulling their hair out. Make sure and spaces in your SharePoint URL are replaced by %20. Example "New Folder" should be "New%20Folder, or remove the space from the folder name.

Unable to save as PDF from VBA in mac

I am trying to save a range from a sheet as PDF through VBA. Following is the code that I have written.
Sheets("PO Format").PageSetup.PrintArea = "$B$6 : $J$42"
Sheets("PO Format").Range("B6:J42").ExportAsFixedFormat Type:=xlTypePDF, Filename:=Sheets("User Settings").Range("B15") & "/" & Sheets("PO Format").Range("F7"), Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
The weird thing is that it is working fine on one system and I able to save it at the mentioned path and then also send out a mail, but while testing it on another system I am getting the error as "Error while printing". Completely clueless. Can anyone help??
In Mac Office 2016 Microsoft have to deal with Apple’s sandbox requirements due to which VBA needs permission to access folders and this is not prompted while trying to save via VBA instead it gives an error. But there are a few places on Mac that one can use to let the code do what it needs to do without user interaction.
one such path is /Users/username/Library/Group Containers/UBF8T346G9.Office
This folder gets created when Office 2016 is installed.
So I saved the PDF to this folder, moved it to the desired location and it is working fine now.
For more details and the code go through http://www.rondebruin.nl/mac/mac034.htm
Make sure that Excel SaveAsPDFandXPS addin is installed, if available for Mac then you should be able to find it on Microsoft site,it available for free. Install it then the code should work just fine.

ExportAsFixedFormat fails sometimes

I have a spreadsheet with forms and macros that worked until recently. The first time I saw the described behavior was the first time I tried using this particular function in Excel 2016 (Windows 10), though I'm not sure that's the cause.
The issue I'm having is with the following line
Worksheets("Label Template - 100X150").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFilePath, Quality:=xlQualityMinimum, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
Which comes from the following macro:
Sub PDFLabelsSheet()
'On Error GoTo errHandler
'enter name and select folder for file
strFile = "Labels_PrintGroup-" & lstPrintGroup.Value _
& "_" _
& Format(Now(), "yyyy-mm-dd\_hhmm") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
Worksheets("Label Template - 100X150").Visible = True
UnprotectTab "Label Template - 100X150"
pdfFilePath = Application.GetSaveAsFilename(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If pdfFilePath <> "False" Then
Worksheets("Label Template - 100X150").Select
Worksheets("Label Template - 100X150").Range("A1").Select
Worksheets("Label Template - 100X150").Range("A1").Activate
Cells.Activate
Worksheets("Label Template - 100X150").PageSetup.FirstPageNumber = 1
Worksheets("Label Template - 100X150").ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=pdfFilePath, Quality:=xlQualityMinimum, _
IncludeDocProperties:=False, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
exitHandler:
ExecutionEnd
Exit Sub
errHandler:
MsgBox "Something went wrong, a PDF could not be created", vbCritical
Resume exitHandler
End Sub
I've tried permutations of the ExportAsFixedFormat function, changing it to Worksheets("name"), (number), ActiveSheet.... etc.
Prior to executing this particular Sub, the worksheet is unhidden and unprotected. I've tried setting the entire range as PrintArea, I've tried selecting and activating the range to be exported as well.
The most frustrating part is it works sometimes. I've gone as far as putting in code that spits out every property of the PageSetup collection to make sure that something is not blowing things up since the output depends so strictly on the page setup.
When I navigate to this worksheet manually and choose the export function from the file menu, I get the same error. If I click around in that worksheet for a bit the Export function as well as the Macro work.
The PDFLabelSheets Sub does get called from another Sub (invoked by a form's button press) which compiles a boatload of data into this tab, though I've ruled it out as the culprit as successive runs of just the PDF code will succeed then fail without running the other code.
I’ve recently solved a problem that was similar in the following ways:
It involved the failure of the ExportAsFixedFormat, Type:=xlTypePDF
statement
The statement failed with no error message; it simply
stopped the execution of the VBA code
The failure was inconsistent,
and the conditions for failure or success were not obvious
Below is a summary of how I solved it; perhaps this will suggest some useful approaches you can use.
My Excel VBA code was running under Windows 7 as an unattended, end-of-day scheduled task in the background, usually when no one was logged in. Most of the time the code would work, but sometimes it would not. I could not capture the screen after a crash, and capturing the various window contents did not help: there was no useful diagnostic text. I finally tried logging program execution milestones to a disk file, reopening and closing the file for each milestone, so no text would be lost if the program subsequently crashed. That isolated the problem to the ExportAsFixedFormat statement but did not diagnose the problem.
I finally tried having the VBA code save a copy of the workbook just prior to the point of failure. I was hoping that, on re-opening the copy, I’d be able to see what was wrong. That did not help. However, I did notice something strange when comparing the .xlsm files saved on successful and unsuccessful executions – the former were just a little larger.
Digging into the .xlsm files (which are really .zip files), I noticed that, in the xl\printerSettings subfolder, the printerSettings1.bin file was larger after successful runs. Using the SysInternals Strings utility to inspect the .bin files, I found that, in the unsuccessful runs, this file contained only the name of the default printer on the home computer where I had developed the application, which was not the office computer where it was executing. On the successful runs, the .bin file also contained the name of the default printer in the office.
This was the critical difference. In that office, the main computer executes the Excel program shortly after the end of the working day. Ordinarily, during the day this computer prints to a laser printer (set as the default printer) attached to another computer on the network, and that other computer is turned off at the end of the working day. Therefore, depending on accidents of timing, sometimes the end-of-day Excel program would see a valid, available default printer, sometimes not.
Some Excel commands, including the command to save as a .pdf, work properly only when the active printer is valid. There is a similar observation at can't set PageSetup.Orientation = xlLandscape from MS Project, concerning assignments to the fields of .PageSetup. In my case, failing to work properly meant crashing without generating any error message.
I later discovered that my problem was not simply the unavailability of the default laser printer over the network; it was also caused by something irregular about the printer definition. I had added code to log the VBA property Application.ActivePrinter; just prior to a crash, it was returning the value “unknown printer (check your Control Panel)”, rather than containing the name of the printer. When I re-installed the default printer, Application.ActivePrinter always returned the proper printer name, whether or not that printer was available for use, and the program stopped crashing.
My problem was a true Heisenbug – it disappeared whenever I re-ran the Excel workbook at random times. That ultimately turned out to help me confirm its diagnosis. Running unattended, sometimes there was no valid printer. When I logged into my account and ran it attended, either it was during the business day or else LogMeIn temporarily assigned my home printer as a valid default printer. This finally made sense of the fact that the program failed only when it wasn’t being closely observed at the time of execution.
In summary, I’d look at inconsistent printer availability and irregular printer installation as possible underlying causes of failure to consistently export .pdf files using Excel VBA.
Frogrammer-Analyst's analysis is great, but the error is not that ambiguous. You will not have this issue if you login to the server using the user that is running the unattended script. But if you sign out and then try rerunning your script unattended you will see that no printers are mapped and {ExportAsFixedFormat} fails for PDF and or XPS formats.
I have found a solution for my case. A true headeache. Maybe it can help others:
Try uncheking the "PDF/A compliant" option under Options dialog when you export as PDF. After that, run the VBA code again.
For my, it was the solution.
PDF Options

Resources