Saving as PDF through VBA corrupts the file - excel

I have a hard time identifying this issue. I have a macro that selects multiple sheets within a workbook and saves it as a PDF. The file is placed correctly into the folder and sometimes it even opens correctly. However, most of the time the PDF is corrupted and gives me the following error.
I cannot replicate instances when it works. The sheet "MSPG Chart" is a chart sheet, i.e. I moved a chart to its own sheet called "MSPG Chart". If I manually save the file it works.
Below is the code I use:
NewPathAssembly is my save path, which works as intended.
Sub Create_PDF_StandAlone()
Dim NewPathAssembly as String, Name as String
Dim PDFName as Variant
On Error GoTo ErrLine
NewPathAssembly = "C:\"
Name = "B2110 - xx_30 - MS Peergroup"
PDFName = InputBox("Enter PDF name here.", "PDF title", Name)
Sheets(Array("Overview", "MSPG Chart")).Select
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False, PrToFilename:= _
NewPathAssembly & PDFName & ".pdf"
Sheets(1).Select
Exit Sub
ErrLine: MsgBox "Please close the current PDF file"
End Sub

Adding the argument ActivePrinter:="Microsoft Print To PDF"
worked. It appears that since it defaulted to another printer it somehow corrupted the file.

Related

I am unable to get VBA in Excel to save a file. The Save As dialog box opens with the file name as scripted but it never saves [duplicate]

So i have this VBA at work, that I made a while ago. It used to work perfectly, but as of today it will not save my file after it opens the Save as window. It just goes to the MsgBox ive given it.
At first the problem was that LDate = Date somehow started returning the date with a forward slash. Ive fixed this by adding a format for LDate. But the bigger problem remains. No matter what i do, what code i remove or add, what name i write manually, the file wont save in any folder i give it.
Sub Export()
'
' Export Macro
'
' copy range from work workbook, create a new workbook and paste selection
Sheets("NewTemplate").Range("A1:M29").Copy
Workbooks.Add
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteColumnWidths, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
ActiveSheet.Paste
' rename active sheet and active workbook
ActiveSheet.Name = "Create"
ActiveWorkbook.Windows(1).Caption = "Newly Generated Table"
Range("A1").Select
Application.CutCopyMode = False
' open Save As window, set file save name to custom prefix + date
Dim IntialName As String
Dim fileSaveName As Variant
InitialName = "Import_Feature_Values_"
Dim LDate As String
LDate = Date
LDate = Format(Now, "dd_mm_yyyy")
fileSaveName = Application.GetSaveAsFilename(FileFilter:= _
"Microsoft Excel Macro- Enabled Worksheet (*.xlsm), *.xlsm", InitialFileName:=InitialName & LDate)
'error box if filesavename fails
If fileSaveName <> False Then
MsgBox "Failed to Save as " & fileSaveName
End If
'
End Sub
GetSaveAsFilename does not save a file.
It only does what the function name says: Get a SaveAs filename from the dialog box.
So your variable fileSaveName just contains a file path and file name that was chosen in the dialog box, and you still need to save the file yourself.
Fore example to save the current workbook (that workbook code is running at) with the chosen filename:
ThisWorkbook.SaveAs Filename:=fileSaveName
or for the active workbook (that workbook that is on top):
ActiveWorkbook.SaveAs Filename:=fileSaveName
For macro enabled files define a file format according to XlFileFormat-Enumeration:
ActiveWorkbook.SaveAs Filename:=fileSaveName, FileFormat:=xlOpenXMLWorkbookMacroEnabled

VBA 1004 error on selecting "No" or "Cancel" when asked to replace file during SaveAs

I have VBA where the user fills out a template, then saves as .XLSM and PDF.
The .XLSM saves as the entire workbook, but the PDF is only 2 worksheets. Both files are named after a variable cell in the workbook and a file location is suggested, but can be changed by the user.
Everything works until the user is warned that they are overwriting an existing file. If they select "no" or "cancel," then they get an error. Ideally, I would like for the sub to just exit and neither the PDF or .XLSM is saved. I have tried On Error, but cannot get the whole thing to work. Other solutions seem to take away some functionality (variable file name, different sheets printing/saving, initial file location, etc.).
Below is my code if anyone can help:
Sub SaveToPDF2()
Dim strFilename As String
Dim rngRange As Range
Dim fileSave As FileDialog
Set fileSave = Application.FileDialog(msoFileDialogSaveAs)
'Considering Sheet1 to be where you need to pick file name
Set rngRange = Worksheets("template").Range("b3")
'Create File name with dateStamp
strFilename = rngRange.Value & ".process." & Format(Date, "mm.dd.yyyy")
With fileSave
' Your default save location here
.InitialFileName = "U:\221 Released Drawings\" & strFilename
If .Show = -1 Then
ActiveWorkbook.SaveAs filename:=strFilename & ".xlsm", FileFormat:=52
ThisWorkbook.Sheets(Array("process", "signoff")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=strFilename _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=True
Else: Exit Sub
End If
End With
End Sub
Try inserting the next code line, just before With fileSave:
If Dir(strFilename & ".xlsm") <> "" then Exit Sub
If such a file already exists, the code is exited on the above inserted line...

How to assign a specific button in excel sheet to do some specific task?

I would like to have a button on this excel sheet whose name should be “Save as PDF”.
When I press this button it should save the excel sheet’s all data into PDF at the path- M:\formats\ ‘File Name’
‘File Name’ should be the value of cell No H8.
In another words when I click “Save as PDF” button it should save the excel file in pdf form, into the above mentioned path and also with the name whichever is written in cell no H8.
For example, if the name ANDREW PITTERSON is written in H8 cell then it should save with the same name I.e. ANDREW PITTERSON.
Kindly look at this snapshot.
http://i.imgur.com/JJdlFSi.jpg
THANKS
Here's a link to a great simple article, to do this sort of thing. http://www.contextures.com/excelvbapdf.html
I've tested the code example in Excel 2013 and it works fine. The code asks the user what directory to save the PDF in.
But your question says that you also want to save to a specific location (without user intervention) and to get the filename from a cell.
Update - And you'd also like to save the file as an XLSM, once the PDF is created.
The code below does what you're after (all credit to the original author, but my own OCD led me change var names to a format that I like).
I'm guessing the OP would like to know HOW it was done, rather than just have the answer, so I've tried to make the example easy to follow, rather than trying to observe best practice - I'd appreciate not being down-voted for this.
Please note, you must first open the Excel Code window, got to Tools, then References and select 'Microsoft Scripting Runtime' then click Ok. This lets you use many useful functions.
I keep the directory path (hard coded) and the filename separate, so that I can get the 'BaseName' in a clearer way. Obviously this could be done in less lines, but at the risk of making it harder to follow.
Sub ExportAPDF_and_SaveAsXLSM()
Dim wsThisWorkSheet As Worksheet
Dim objFileSystemObject As New Scripting.FileSystemObject
Dim strFileName As String
Dim strBasePath As String
strBasePath = "M:\formats\"
strFileName = Range("H8")
On Error GoTo errHandler
Set wsThisWorkSheet = ActiveSheet
wsThisWorkSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strBasePath & strFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
MsgBox "PDF file has been created."
' Now we need to get rid of the .PDF extension. Many ways to code round this, but here is a built in function.
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsm"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
MsgBox "Workbook now saved in XLSM format."
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Just add the button (ActiveX Button) to your worksheet and call this sub from the buttons code window (or just paste the code directly into the Button code window).
Hope that helps.
ADDED:
To save the file as an XLSX (No Macros), then replace the code toward the end of the SUB with:
Application.DisplayAlerts = False
strFileName = objFileSystemObject.GetBaseName(strFileName) & ".xlsx"
wsThisWorkSheet.SaveAs Filename:=strBasePath & strFileName, FileFormat:=xlOpenXMLWorkbook
Application.DisplayAlerts = False

Code being saved to formatted workbook

I have a template that user will open up, select the text file and VBA does all the magic. At the end of the code I have the SaveAs dialog box come up, user type in name and saves to appropriate location. I have this code sitting in a module of the main temmplate. The problem I have is the formatted file has the module in it where the code sits. I don't want that. I know I've figured this out before but today is not that day. Relevant code pasted below. I've tried changing the file formats, moving code to a worksheet. What am I missing/forgetting?
Filename = "WhateverName_"
SaveThiisFile = Application.GetSaveAsFilename(InitialFileName:=Filename, _
fileFilter:="Excel Files (*.xls), *.xls", _
FilterIndex:=1, Title:="Save As")
If ThisFile = False Then Exit Sub
ActiveWorkbook.SaveAs Filename:=SaveThisFile
ActiveWorkbook.Close (False)

csv output from excel error but other data types work correctly?

Ok I am attempting to write a Macro that saves an excel Workbook into a csv file. I have tried many different solutions but I am still having issues getting the values to print properly. when I open the file it produces. The rest of the code I left out all it does is takes the original spreadsheet and copys the contents into a temporary sheet so I can take multiple sheets from the same WB and print them to the same csv file. it also has a module that will clear all formatting and contents of that temporary file. I ran the code to just print it to a new excel spreadsheet and it worked fine just will not print to a csv not sure why
out put looks like this:
K ! bîh^ [Content_Types].xml ¢(
[… skip a bunch of binary lines …]
KÆ8k¡~¥-ÙÔäá ûÜ
My code looks like this:
Sub SaveFile()
Dim NewName As String
Dim nm As Name
Dim ws As Worksheet
If MsgBox("Copy specific sheets to a new workbook" & vbCr & _
"New sheets will be pasted as values, named ranges removed" _
, vbYesNo, "NewCopy") = vbNo Then Exit Sub
With Application
.ScreenUpdating = False
' Copy specific sheets
' *SET THE SHEET NAMES TO COPY BELOW*
' Array("Sheet Name", "Another sheet name", "And Another"))
' Sheet names go inside quotes, seperated by commas
On Error GoTo ErrCatcher
Sheets(Array("Raw Data Copy")).copy
On Error GoTo 0
' Paste sheets as values
' Remove External Links, Hperlinks and hard-code formulas
' Make sure A1 is selected on all sheets
For Each ws In ActiveWorkbook.Worksheets
ws.Cells.copy
ws.[A1].PasteSpecial Paste:=xlValues
ws.Cells.Hyperlinks.Delete
Application.CutCopyMode = False
Cells(1, 1).Select
ws.Activate
Next ws
Cells(1, 1).Select
' Remove named ranges
For Each nm In ActiveWorkbook.Names
nm.Delete
Next nm
' Input box to name new file
NewName = "test"
' Save it with the NewName and in the same directory as original
ActiveWorkbook.SaveCopyAs ThisWorkbook.path & "\" & NewName & ".csv"
ActiveWorkbook.Close SaveChanges:=False
.ScreenUpdating = True
End With
Exit Sub
ErrCatcher:
MsgBox "Specified sheets do not exist within this workbook"
End Sub
SaveCopyAs only saves an Excel Workbook in Excel format. Even if you append .csv to your filename, the file is still an .xls formatted file.
The Workbook SaveAs method lets you to specify the type of file you want to save to.
However, if you use the SaveAs method, it changes the name of your current file.
This earlier question on Stack Overflow has some options on how to use the SaveAs method without changing the name of the file you are working on.
Why does VBA ActiveWorkbook.SaveAs change the open spreadsheet? has some comments on how to properly use the SaveAs method and not have the name of your current file changed in the process.

Resources