ExportAsFixedFormat fails sometimes - excel

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

Related

Excel VBA SaveAs sometimes works, sometimes fails; no idea why

I have used this macro for years on a server based solution, moving over to Sharepoint and I have changed the locations but am hitting a wall. All the code is doing is saving the file as a different name, and then saving it again back as the original name; oddly it only ever fails on the first part, never the second; and often it works all the way through, and then other times when trying to do the first saveas it fails. It also always seems to work if there is no existing filename on the first, its when overwriting that it sometimes works and sometimes doesn't. I would kill the file first, but Kill doesnt seem to work with Sharepoint either so that has stopped me doing that to solve the issue. When it fails I get one of two messages but mostly "Run-time error 1004: Method 'SaveAs' if object'_Workbok;failed". But as I say, I can hit it 10 times in a row and it be fine, then suddenly it wont work anymore and I know I am the only person in the file so its not that someone else has it open or anything like that. I have looked at several chains with this error code and they all seem to suddenly say they worked it out because a DIM was in the wrong place or a filename was wrong etc etc, I cannot seem to find such issue, certainly as it works 50% of the time.
ThisWorkbook.SaveAs Filename:= _
"https://x.sharepoint.com/sites/Company/Shared Documents/F-Drive/FUND ADMINISTRATION/Monthly Reporting/" & (ThisWorkbook.Sheets("Misc Data").Range("J3").Value) & "/Factsheets_Presentations_" & (ThisWorkbook.Sheets("Misc Data").Range("J3").Value) & ".xlsm", _
FileFormat:=52, CreateBackup:=False
ThisWorkbook.SaveAs Filename:= _
"https://x.sharepoint.com/sites/Company/Shared Documents/F-Drive/FUND ADMINISTRATION/Monthly Reporting/Factsheet & Presentation Generator.xlsm", _
FileFormat:=52, CreateBackup:=False

Excel VBA Create PDF using ExportAsFixedFormat frequently hangs

I have a process that takes a series of inputs, retrieves some data, and generates a PDF in a loop.
If I test it on a single entry, it always works. When I run it in a loop, it frequently hangs at some point.
I have isolated the issue that it always occurs on when executing the same line:
Range("Print_Area").ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDF_filename, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
I have confirmed that the issue is NOT the filename I am trying to save.
When I repeat the process, the same file can be produced successfully.
I have read that this issue can be related to the availability of the printer.
I have tried printing out Application.ActivePrinter before attempting to produce the PDF, but I get the same result before a successful attempt and an attempt that hangs Excel.
I am hitting this issue on Microsoft Excel for Microsoft 365 MSO - 64 bit running in Windows 10.
I would really appreciate any suggestions how to fix this issue.
I solved my own problem.
It turned out that the root of the problem was data retrievals that had not completed when the process of generation the PDF started. Once I ensured that there was no possibility of new data arriving during the PDF process, the problem disappeared.

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.

Outlook 2010 - strange item.Attachments error

I have the following code, that should save a specific Excel file attached to an email. The code is combined with a rule, that trigger this script when an emai lwith a specific subject is received.
The code is triggered, but here comes the strangest error I saw lately: itm.Attachments.Count appear to be zero and obviously the file is not saved! But... if I put a breakpoint on "For each..." line and add itm.Attachments.Count to watch window, it is shown as zero. If I add itm only, then browse to Attachments property, then to Count property it shows 1 for Count (as it should) and the code is executed fine. I spent half a day trying to understand what's going on, but I can't figure it out.
The behaviour is the same both on a Outlook 2010 x64 on a Windows 7 x64 and on a Outlook 2010 x86 on a Windows 7 x86. Macros are enabled in Trust Center. I have attached some screenshot with the code and rule settings and also a movie showing the watch windows strangeness.
The script was built some time ago and it worked well on a couple of PCs and it was based on the steps from here: iterrors.com/outlook-automatically-save-an-outlook-attachment-to-disk/.
Any ideas?
Rule screen here
1 min. movie here
Public Sub Kona(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\test"
For Each objAtt In itm.Attachments
If InStr(objAtt.DisplayName, "Kona Preferred Fixed Price Matrix (ALL)") Then
objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
End If
Set objAtt = Nothing
Next
End Sub
In case if you have an IMAP account configured in Outlook: your Offline Settings might be set to only store up to 1 month, 3 months, 12 month worth of emails on your local disk.
If you’ve got enough space on your disk and want to cache more emails locally, you can set the sync slider in the following way:
File-> Account Settings-> Account Settings…-> double click on your IMAP account.
Try to increase the offline storage in Outlook. See Empty Inbox and other IMAP synching issues in Outlook 2013 for more information.
My best understanding of this behavior is that Microsoft Outlook (at least the versions of 2010 that I tested) has a bug. There may be other factors that I'm not aware of contributing to this, but I was able to reproduce the error using different service pack levels / builds of Outlook 2010 on Windows Vista. Office 2013 does not appear to be affected.
I managed to create a workaround.
I found that by displaying the message while stepping through the code in debug mode using
objMailItem.GetInspector.Activate
the number of attachments was subsequently correctly detected (without having to do strange things like setting up a watch for the object variable and then clicking on it in the IDE).
However, this only worked while stepping through the code, not during normal execution.
For this reason, I suspected the message might not be displaying long enough during normal code execution for Outlook to get the twist out of its knickers. I reasoned that it might be possible to insert a delay to allow sufficient time for this.
I tried out several methods of inserting a delay. Here is the one that worked for me. I created a form called
frmTimer
and added the freeware RSTimer OCX control (http://www.softpedia.com/get/Programming/Components-Libraries/RS-Timer.shtml) to it.
I set the
Interval
property of the OCX to 1000 ms.
The form is loaded right after displaying the message like this:
objMailItem.GetInspector.Activate
frmTimer.Show ' <-- form is loaded and displayed (it is not sufficient to just 'load' it)
objMailItem.Close OlInspectorClose.olDiscard
The form has one single event handler:
Private Sub RSTimer1_Timer()
Unload frmTimer
End Sub
When the event fires, the form is unloaded and code execution continues with
objMailItem.GetInspector.Activate
frmTimer.Show
objMailItem.Close OlInspectorClose.olDiscard ' <-- code execution continues here
Here is a complete function that allows the attachment to be detected correctly.
Function EmailHasAttachments(ByVal objMailItem As Outlook.MailItem) As Boolean
On Error GoTo ErrHandler
objMailItem.GetInspector.Activate
frmTimer.Show
objMailItem.Close OlInspectorClose.olDiscard
If objMailItem.Attachments.Count > 0 Then
EmailHasAttachments = True
Else
EmailHasAttachments = False
End If
ExitHere:
Exit Function
ErrHandler:
Debug.Print Err.Number, Err.Description
Select Case Err.Number
Case 12345
' handle the error
Case Else
MsgBox "An unknown error has occurred."
Exit Function
End Select
End Function

Losing VBA code under 'ThisWorkbook' (Private Sub WorkBook_Open() )

First three elements of the background:
I have created a Excel Template which is used, in turn, to create a 'personalised template' where user name, user comment, and save data pathnames are embedded in the personalised template.
The personalised template is used to produce monthly workbooks (actually, time sheets)
The template has been created in Office/Excel 2007 running under Vista but the (current) target environment is a corporate network running Office/Excel 2003 under XP Professional. Both templates are therefore created as Excel 2003 templates (which in the development environment run in compatibility mode)
So far, so good - the templates work well in the development environment - the 'personalisation' code is in a WorkBook_Open() routine under 'ThisWorkbook' - it runs, DELETES ITSELF, and saves as the personalised template. Both templates have the 'process macros' in the Sheet1 code (the principle here is that the initial template has macros in 'ThisWorkbook' and 'Sheet1'; the personalised template has macros only in 'Sheet1' and the workbooks created from the personalised template have NO MACROS AT ALL.
In 'beta testing' I had problems with Excel2000 under XP (fileformats) and on a target machine my WorkBook_Open routine was deleted in the main template (instead of in the personalised template) - even though everything worked OK on Excel2007/Vista.
I felt at the time that the invalid deleting of Workbook_Open was probably a coding error -but whilst researching the issues I found a number of references to 'Macafee deleting VBA modules'. I did not look into these - but was conscious that the target machine (and environment) run Macafee whilst all my computers run Norton.
Having recoded, I successfully retested in the following:
a) Excel 2007/Vista/Norton
b) Excel 2007/XP Professional/Norton
c) Excel 2000/XP Home/Norton
so felt comfortable to re-test in Excel 2003/XP Professional/Macafee
This time I was watching for it - so, once again, saw the WorkBook_Open routine incorrectly deleted from the main template - unfortunately this was only moments before the USB Memory Key (where the template was running from) was completely destroyed.
So to the question(s) - before I go through the whole process again:
Is there any objective evidence of Macafee removing 'auto-run' VBA modules?
If yes, is there any work-around (this template will be use by three people in a enterprise of ten thousand - so there is no way I will be able to influence/modify the security policies!!! :( ) - if there is a problem with Macafee then I will have to re-think the whole thing!
To answer your actual question... YES, many antivirus programs absolutely consider autorun code that runs on opening Excel or Word docs to be unsafe, and deletes it, because for a brief moment ten years ago this was actually the way some worms worked. I don't know if MacAfee in particular does this but I've definitely heard of it happening.
JUst in case anyone else comes to this thread - I have now fully checked out my template - and re-run it in the target environment - and the Workbook_Open routine was again deleted. after doing some digging around on the target machine I found the Macafee event log and lo and behold...
Event Type: Warning
Event Source: McLogEvent
Event Category: None
Event ID: 258
Date: 09/07/2011
Time: 15:45:40
User: NT AUTHORITY\SYSTEM
Computer:xxxxxxxxxx
Description:
The file F:\Timesheets\Timesheet Generator.xlt\1.OLE contained X97M/Generic Virus. The file was successfully cleaned with Scan engine version 5400.1158 DAT version 6400.0000.
So there is the definitive proof.
Same thing happens with Workbook_Activate()
The 'offending' lines appear to be
With ThisWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
.DeleteLines 1, _
.CountOfLines
I have managed to get to the client machine again - and added a new simple template to prove or otherwise my issue. The new WorkBook_Open routine is...
Private Sub WorkBook_Open()
MsgBox "Hello World"
With ThisWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
.DeleteLines 1, _
.CountOfLines
End With
MsgBox "Goodbye to all that!"
End Sub
...and this works exactly as required i.e. the routine executes then deletes itself (the second msgbox displays even though the code has been deleted!
So, this test invalidates my question - McAfee is NOT deleting the routine as part of AV protection - so I am no longer looking for a workaround!
Now all I need to do is to figure out what my problem really is!
Thanks for the comments

Resources