I am using the below mentioned code to print a sheet. My task is complete, however I get the error message stating "Run-time error '-2147024773 (8007007b)': Document not saved."
Also, in the below code, can I add a text to the file name (other than cell A1 text?). I would like the file name to be name (which is on cell A1) and add a text "- Workpaper" in the end.
Can some one help?
Sub PrintFile()
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Foldername\" & Range("A1").Text, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With
End Sub
Try changing "Range("A1").Text" to "Range("A1").Value"
Text vs Value
Also, you should be checking for a valid filename prior to using the value.
Function ValidateFileName(ByVal name As String) As Boolean
' Check for nothing in filename.
If name Is Nothing Then
ValidateFileName = False
End If
' Determines if there are bad characters.
For Each badChar As Char In System.IO.Path.GetInvalidPathChars
If InStr(name, badChar) > 0 Then
ValidateFileName = False
End If
Next
' If Name passes all above tests Return True.
ValidateFileName = True
End Function
First of all type e.g. "test" into A1 cell - probably there is something wrong with the filename. You can also use Excels's data validation or some VBA code to sanitizate the filename. You can also add some check if directory exists to make sure it isn't a problem.
Sub PrintFile()
' check if folder exists
If Dir("C:\Foldername\", vbDirectory) = "" Then
MkDir "C:\Foldername\"
End If
' check if name in A1 is not blank
If IsEmpty(Range("A1")) Then
MsgBox "Fill A1 Cell with name of the pdf file first"
Else
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Foldername\" & Range("A1").Value & "- Workpaper", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With
End If
End Sub
So there is a problem with your path or/and filename. Maybe it is a Mac and C:\ is not proper address?
The reason for this error might be insufficient privileges or any invalid characters in the name of the file.
Could you try to save it in a different drive than C and see if that works?
Replace this line of your code with below line to add -Workpaper at the end of your file name.
Assuming that you're trying to save this in D drive in a temp folder.
Filename:="D:\temp\" & Range("A1").Text & "-Workpaper", _
Related
So I have this code below that currently works. All of the data is on a tab called "Table" and feed into a tab called "Att A" that gets produced into 100+ pdf files and named based on the value that is in column A in the "Table" tab.
I would like to add a conditional statement to the following code that checks the value in column CH in the "Table" tab and if it is greater than 0 save in one location, if it equals 0 then save in another location. Since there are 100+ lines of data, the value in column A needs to check the value in the same row for column CH.
So the logic goes to column A (Uses this value as the file name), creates a file, and checks column CH to determine which folder to save the file in. How do I add this condition to the following code?
Sub Generate_PDF_Files()
Application.ScreenUpdating = False
Sheets("Table").Activate
Range("A7").Activate
Do Until ActiveCell.Value = "STOP"
X = ActiveCell.Value
Range("DLR_NUM") = "'" & X
Sheets("Att A").Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"L:\Mike89\Sales" & X & ".pdf", Quality:=xlQualityStandard, _IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Sheets("Table").Activate
ActiveCell.Offset(1, 0).Activate
Loop
End Sub
Since your code works, we would typically suggest you post it on Code Review, however you're also looking for some help on a conditional statement.
So a few quick things...
Avoid Select and Activate
Use Descriptive Variable Naming
Always Define and Set References to Worksheets and Workbooks
Never Assume the Worksheet
The conditional itself is very straightforward as shown in the example below, which also incorporates the ideas shared in the links above:
Option Explicit
Sub Generate_PDF_Files()
Dim tableWS As Worksheet
Dim attaWS As Worksheet
Dim filename As Range
Dim checkValue As Range
Dim filepath As String
Const ROOT_FOLDER1 = "L:\Mike89\Sales"
Const ROOT_FOLDER2 = "L:\Mike99\Sales"
Set tableWS = ThisWorkbook.Sheets("Table")
Set attaWS = ThisWorkbook.Sheets("Att A")
Set filename = tableWS.Range("A7")
Set checkValue = tableWS.Range("CH7")
Application.ScreenUpdating = False
Dim dlrNum as Range
set dlrNum = tableWS.Range("DLR_NUM")
Do Until filename = "STOP"
dlrNum = "'" & filename
If checkValue > 0 Then
filepath = ROOT_FOLDER1 & filename
Else
filepath = ROOT_FOLDER2 & filename
End If
attaWS.ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filepath, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Set filename = filename.Offset(1, 0)
Set checkValue = checkValue.Offset(1, 0)
Loop
Application.ScreenUpdating = True
End Sub
Sheets("Key Indicators").ExportAsFixedFormat Type:=xlTypePDF,
Filename:=ArchivePath, Quality:=xlQualityStandard,
IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Currently this is what I have.
I understand how to ExportAsFixedFormat PDF but what I need to know how to do is to access the Create PDF function under Acrobat (As show in the picture below) using VBA. If I do ExportAsFixedFormat the links get flattened. Acrobat "Create PDF" would allow me to convert an Excel to PDF with hyperlinks included.
How would I do that?
I am using Excel 2016 and Adobe Pro DC
These are my adobe references
Sub PDF()
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\PCNAME\Documents\Book1.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Please try the above codes
Acrobat Reference should work
Here is the guide from Adobe
Once added, you may use the following code
Tip: It may lead you to correct coding -I'm not quite sure since I coded it "blindly" because I don't have Acrobat in my PC-. Debug step by step to see what's doing.
Sub ExportWithAcrobat()
Dim AcroApp As Acrobat.CAcroApp 'I'm not quite sure it's needed since we are creating the doc directly
Dim AcrobatDoc As Acrobat.CAcroPDDoc
Dim numPages As Long
Dim WorkSheetToPDF As Worksheet
Const SaveFilePath = "C:\temp\MergedFile.pdf"
Set AcroApp = CreateObject("AcroExch.App") 'I'm not quite sure it's needed since we are creating the doc directly
Set AcrobatDoc = CreateObject("AcroExch.PDDoc")
'it's going to be 0 at first since we just created
numPages = AcrobatDoc.GetNumPages
For Each WorkSheetToPDF In ActiveWorkbook.Worksheets
If AcrobatDoc.InsertPages(numPages - 1, WorkSheetToPDF, 0, AcrobatDoc.GetNumPages(), True) = False Then 'you should be available to work with the code to see how to insert the sheets that you want in the created object ' 1. If Part1Document.InsertPages(numPages - 1, "ExcelSheet?", 0, AcrobatDoc.GetNumPages(), True) = False
MsgBox "Cannot insert pages" & numPages
Else ' 1. If Part1Document.InsertPages(numPages - 1, "ExcelSheet?", 0, AcrobatDoc.GetNumPages(), True) = False
numPages = numPages + 1
End If ' 1. If Part1Document.InsertPages(numPages - 1, "ExcelSheet?", 0, AcrobatDoc.GetNumPages(), True) = False
Next WorkSheetToPDF
If AcrobatDoc.Save(PDSaveFull, SaveFilePath) = False Then ' 2. If Part1Document.Save(PDSaveFull, "C:\temp\MergedFile.pdf") = False
MsgBox "Cannot save the modified document"
End If ' 2. If Part1Document.Save(PDSaveFull, "C:\temp\MergedFile.pdf") = False
End Sub
Following pages may provide better assistance: Link1, Link2
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:="N:\JKDJKDJ", _
Quality:=xlQualityStandard, IncludeDocProperties:=True,
IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
You can publish any Excel Range as a PDF using ExportAsFixedFormat. There is no need to set a refernce to Acrobat.
' Usage:
' PublishRangePDF(Thisworkbook, fileName) : Will Publish the entire Workbook
' PublishRangePDF(AvtiveSheet, fileName) : Will Publish all selected worksheets
' PublishRangePDF(Range("A1:H100"), fileName) : Will Publish Range("A1:H100")
Sub PublishRangePDF(RangeObject As Object, fileName As String, Optional OpenAfterPublish As Boolean = False)
On Error Resume Next
RangeObject.ExportAsFixedFormat Type:=xlTypePDF, fileName:=fileName, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=OpenAfterPublish
On Error GoTo 0
End Sub
I recently received help here for an Excel spreadsheet we have that allows users to create quotations for customers. The spreadsheet uses VBA to allow the user to press a button which generates a PDF out from certain sheets, and attaches them to a new Outlook email.
Unfortunately this isn't working on one of the user's computers. The problem seems to be with the generating of the PDF. Initially when pressing the button, nothing happened. I suspected it was to do with the Microsoft Add-in to Save as PDF, so I made sure it was installed, which it was. After 'commenting out' the error message coming from the code to get to the real error message from Visual Basic, I found it to be this:
run-time error '-2147467261 (80004003)': Document not saved.
When clicking 'Debug' it highlights:
FileName = Create_PDF_Sheet_Level_Names(NamedRange:="addtopdf1", _
FixedFilePathName:=ThisWorkbook.Path & "\" & "Quotation - " & Range("G18") & ".pdf", _
OverwriteIfFileExist:=True, _
OpenPDFAfterPublish:=False)
Which relates to:
Function Create_PDF_Sheet_Level_Names(NamedRange As String, FixedFilePathName As String, _
OverwriteIfFileExist As Boolean, OpenPDFAfterPublish As Boolean) As String
'This function will create a PDF with every sheet with
'a sheet level name variable <NamedRange> in it
Dim FileFormatstr As String
Dim Fname As Variant
Dim Ash As Worksheet
Dim sh As Worksheet
Dim ShArr() As String
Dim s As Long
Dim SheetLevelName As Name
'Test If the Microsoft Add-in is installed
If Dir(Environ("commonprogramfiles") & "\Microsoft Shared\OFFICE" _
& Format(Val(Application.Version), "00") & "\EXP_PDF.DLL") <> "" Then
'We fill the Array with sheets with the sheet level name variable
For Each sh In ActiveWorkbook.Worksheets
If sh.Visible = -1 Then
Set SheetLevelName = Nothing
On Error Resume Next
Set SheetLevelName = sh.Names(NamedRange)
On Error GoTo 0
If Not SheetLevelName Is Nothing Then
s = s + 1
ReDim Preserve ShArr(1 To s)
ShArr(s) = sh.Name
End If
End If
Next sh
'We exit the function If there are no sheets with
'a sheet level name variable named <NamedRange>
If s = 0 Then Exit Function
If FixedFilePathName = "" Then
'Open the GetSaveAsFilename dialog to enter a file name for the pdf
FileFormatstr = "PDF Files (*.pdf), *.pdf"
Fname = Application.GetSaveAsFilename("", filefilter:=FileFormatstr, _
Title:="Create PDF")
'If you cancel this dialog Exit the function
If Fname = False Then Exit Function
Else
Fname = FixedFilePathName
End If
'If OverwriteIfFileExist = False we test if the PDF
'already exist in the folder and Exit the function if that is True
If OverwriteIfFileExist = False Then
If Dir(Fname) <> "" Then Exit Function
End If
Application.ScreenUpdating = False
Application.EnableEvents = False
'Remember the ActiveSheet
Set Ash = ActiveSheet
'Select the sheets with the sheet level name in it
Sheets(ShArr).Select
'Now the file name is correct we Publish to PDF
On Error Resume Next
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
FileName:=Fname, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=OpenPDFAfterPublish
On Error GoTo 0
'If Publish is Ok the function will return the file name
If Dir(Fname) <> "" Then
Create_PDF_Sheet_Level_Names = Fname
End If
Ash.Select
Application.ScreenUpdating = True
Application.EnableEvents = True
End If
End Function
I'm really scratching my head here! Checked all settings side-by-side with my machine on Excel and Outlook, including Trust Centre settings. Also checked add-ins.
Please check if there is enough disk space where the user wants to save the PDF file to!
I would recommend to check the length of the PDF fullname (path, filename and file extension; in your example it is the variable "Fname") as well before calling "ActiveSheet.ExportAsFixedFormat(...)", because filenames (or rather fullnames) under Microsoft Windows regularly cannot exceed more than 255 characters (see: Naming Files, Paths, and Namespaces).
How can I save a Word document as the value in a table? I've tried this and get a "Type mismatch" error:
Sub saveas_cell()
ActiveDocument.SaveAs FileName:= _
"c:\mydocuments" ActiveDocument.Tables(1).Cell(1, 2) & ".doc"
End Sub
I've also tried an object reference (activedocument.table1.("text3"))
Thanks for the help!
You get an error message because Table.Cell does not return a string, but a cell object. Instead, use this:
"c:\mydocuments" ActiveDocument.Tables(1).Cell(1, 2).Shape.TextFrame.TextRange.Text & ".doc"
You can find more information here.
In my document I have the Format Page Numbers / Start at: set to 0 so that the title page is not counted.
When I do a SaveAs via VBA the document loses that setting! It was also losing the Different First Page setting so I set that directly in VBA which fixed that problem. I think that because I am formatting the footer via VBA before I do the SaveAs I am somehow affecting the settings? Anyway, I tried setting the Start At page number after the SaveAs but it doesnt set it.
' Save our new Workbook - the output file
' That makes the new file the ActiveDocument
ActiveDocument.SaveAs filename:=fname & ".docx", FileFormat:= _
wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False
' Sets this option correctly
ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = True
' Problem: Doesnt set this option
ActiveDocument.Sections(1).Footers(wdHeaderFooterPrimary).PageNumbers.StartingNumber = 0
' Update the TOC
ActiveDocument.TablesOfContents(1).Update
Any ideas?
Thanks,
Murray
"The RestartNumberingAtSection property, if set to False, will override the StartingNumber property so that page numbering can continue from the previous section." (http://msdn.microsoft.com/en-us/library/office/ff821408.aspx)
Therefore, you have to set the RestartNumberingAtSection property to true:
With ActiveDocument.Sections(1)
.Footers(wdHeaderFooterPrimary).PageNumbers.RestartNumberingAtSection = True
.Footers(wdHeaderFooterPrimary).PageNumbers.StartingNumber = 0
End With
Regards,
Leo