Save word document as PDF with a variable in the filepath? - vba

I'm making a word-macro that saves a word document as PDF, with an array variable in the name, the code as of now looks like this:
Private Sub CommandButton2_Click()
'SavePDF
Dim i As Integer
i = ActiveDocument.MailMerge.DataSource.ActiveRecord
Debug.Print i
ActiveDocument.SaveAs2 FileName:="C:\temp\PDFSaves\" & finalArray(0, i) & ".pdf"
End Sub
But it does not work, any suggestions?
Also, if I set it to save to a filepath that doesn't exist, it will create it right? And I want a copy to be saved as a PDF, not the actual word document since it is a template.

You need to use the ExportAsFixedFormat.
ActiveDocument.ExportAsFixedFormat OutputFileName:="C:\temp\PDFSaves\" & finalArray(0, i) & ".pdf", ExportFormat:=wdExportFormatPDF

Related

Word - Prevent SaveAs2 (VBA) from overwriting

Somewhere on the internet I found this code to easily save a .docx file out of a .dotx file into the desired folder:
Sub SaveFileInTheCorrectDirectory()
ActiveDocument.SaveAs2 "[the correct directory, put in manually by me in the VBA code]" & InputBox("Type the desired file name", "Save As")
End Sub
However, this code automatically overwrites an already existing file with the same name (and in the same directory, of course). I've tried looking for code to fix this, and found a few suggestions:
Trying to save word file, from excel vba, without over-writing any existing files
https://answers.microsoft.com/en-us/msoffice/forum/all/vba-macro-saveas-overights-exsiting-file-without/e6fce3b1-ee72-498d-8fe5-fbc3e0cdbf23
http://computer-programming-forum.com/1-vba/2fb545278f4311ff.htm
https://groups.google.com/g/microsoft.public.word.vba.customization/c/Q4W2CK4gQOg?pli=1
But I can't figure out how to implement them...
Could someone be so kind to assist me?
Thanks!
PS Is there added value to use "SaveAs2" instead of "SaveAs" or the other way around?
That's as simple as:
Dim StrName as String
StrName = InputBox("Type the desired file name", "Save As")
If Trim(StrName) = "" then Exit Sub
If Dir(StrPath & StrName & ".docx") = "" Then ActiveDocument.SaveAs2 StrPath & StrName & ".docx"
where StrPath & StrName are the path & name, respectively.
Note: I haven't added any code for what to do if the file exists because you haven't said what you want to do in that case. Post a new question if you need help with that.

Error when Printing to PDF with excel macros. Will only work with actual Adobe and not Adobe Reader

I have this Excel sheet that consolidates a bunch of reports and prints them to PDF. The code works fine when I was on a pc that had the actual Adobe software installed. I tried using it on my personal lap top which only has a adobe reader and the macros crashed with:
Sub JoinPDFFile(strPDFToLocation As String, strPDFTo As String, _
strPDFFromLocation As String, strPDFFrom As String)
Dim objAcroExchApp As Object
Dim objAcroExchNewPDDoc As Object
Dim objAcroExchExistPDDoc As Object
Dim intLastPage As Integer
Dim intNewPages As Integer
Set objAcroExchApp = CreateObject("AcroExch.App") <---This is the error
'New PDF document object
Set objAcroExchApp = CreateObject("AcroExch.PDDoc")
If Dir(strPDFToLocation & strPDFTo & ".pdf") = strPDFTo & ".pdf" Then
objAcroExchApp.Open strPDFToLocation & strPDFTo & ".pdf"
Else
objAcroExchApp.Create
End If
Where it says Set objAcroExchApp = CreateObject("AcroExch.App") <---This is the error
So I was wondering. Would I have to go back and change everything in the code so that it works with whatever PDF file reader the current user has?
I tried using On Error Resume Next above that and all it did was forgo the entire process and just print the first page when there was supposed to be 20 pages.
Is there a way to just simply the entire code just so that it makes a PDF file and not be contingent upon whether I have Adobe? So even if you use Foxit, Dejvu, etc.. it still works?
Excel does not require any specific library to be there for it to ExportAsFixedFormat Type:=xlTypePDF but to use
AcroExch.App Adobe Pro is required. So it really depends on what you want to do with the PDF (it is not clear from your code, I guess it is not just open or create), to do certain things Adobe Pro might be better suited, another might do certain things better, etc.
For example, BYTESCOUT SDK are powerful, easy to use and support multiple functionality and If I need to create CSV from PDF I can do it by adding 3 lines
in your code:
Sub JoinPDFFile(strPDFToLocation As String, strPDFTo As String, _
strPDFFromLocation As String, strPDFFrom As String)
Dim objAcroExchApp As Object
Dim objAcroExchNewPDDoc As Object
Dim objAcroExchExistPDDoc As Object
Dim intLastPage As Integer
Dim intNewPages As Integer
Dim extractor As New Bytescout_PDFExtractor.CSVExtractor
'Set objAcroExchApp = CreateObject("AcroExch.App") '<---This is the error
'New PDF document object
'Set objAcroExchApp = CreateObject("AcroExch.PDDoc")
If Dir(strPDFToLocation & strPDFTo & ".pdf") = strPDFTo & ".pdf" Then
'objAcroExchApp.Open strPDFToLocation & strPDFTo & ".pdf"
extractor.LoadDocumentFromFile strPDFToLocation & strPDFTo & ".pdf"
extractor.SaveCSVToFile (strPDFToLocation & strPDFTo & ".csv")
Else
'objAcroExchApp.Create
End If
End Sub
Thanks
A reply here :
VBA: Acrobat Run time error 429; ActiveX component can't create object
This OLE interface is available with Adobe Acrobat, not Adobe Reader.
EDIT
Try to create a Macro and test this. It works for me. (only xls file)
Sub PDF()
Dim sPDFFileName As String
sPDFFileName = ThisWorkbook.Path & "\" & "Essai.pdf"
Application.ScreenUpdating = False
Sheets(Array("Sheet1")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=sPDFFileName _
, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=False
Sheets("Sheet1").Select
Application.ScreenUpdating = True
End Sub

word vba to set sPath as current directory

Simple code to loop paste .emf files into word:
Sub LoopEMF()
Dim sPic As String
Dim sPath As String
sPath = "C:\Users\me\Desktop\Test2\"
sPic = Dir(sPath & "*.emf")
Do While sPic <> ""
Selection.TypeParagraph
Selection.InlineShapes.AddPicture _
FileName:=sPath & sPic, _
LinkToFile:=False, SaveWithDocument:=True
sPic = Dir
Selection.TypeParagraph
Loop
End Sub
Rather than a specified directory, I simply want to look in the active directory in which the word file (that is open) is located. Much searching has yielded no clue - which is surprising, embarrassing and probably means I'm not using the right key words.
Help?
When I open an Excel document D:\db\tmp\test1.xlsm:
CurDir() returns C:\Users\[username]\Documents
ActiveWorkbook.Path returns D:\db\tmp
So CurDir() has a system default and can be changed.
ActiveWorkbook.Path does not change for the same saved Workbook.
For example, CurDir() changes when you do "File/Save As" command, and select a random directory in the File/Directory selection dialog. Then click on Cancel to skip saving. But CurDir() has already changed to the last selected directory.
From:
How to get current working directory using vba?
Even more embarrassing - I had been using the correct code:
Sub NewLoopEMF()
Dim sPic As String
Dim sPath As String
sPath = ActiveDocument.path & "\"
sPic = Dir(sPath & "*.emf")
Do While sPic <> ""
Selection.TypeParagraph
Selection.InlineShapes.AddPicture _
FileName:=sPath & sPic, _
LinkToFile:=False, SaveWithDocument:=True
sPic = Dir
Selection.TypeParagraph
Loop
End Sub
Unfortunately, the active directory is in a synced SharePoint folder, so the returned name is in hypertext (http://all the rest/) and with this, all you know what breaks loose. I figured this out by using this code:
Sub GetActiveDocumentPath()
MsgBox ActiveDocument.path
End Sub
So it seems the simple solution is to not use a sharepoint folder to store the items. Anyone have a clever solution for those of us working in the SharePoint environment?

Excel Add-in changes the file name to the add-in`s name although it should not

I need your help regarding an add-in I created using VBA, then I saved as add-in to be able to use on all Excel workbooks and also send it to my friends.
The add-in simply saves the printed area in the active sheet as a PDF file with the same name of the workbook, it saves the PDF to the desktop and works fine as a macro.
But when I save as PDF and use it, it saves the PDF file with the same name of the add-in, not as the workbook`s name.
Any suggestions?
The VBA code is:
Sub Save_as_pdf()
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
End Sub
To elaborate on Matteo NNZ's comment above:
ThisWorkbook refers to the workbook in which the code is currently being executed from (in this case, the add-in)
ActiveWorkbook refers to the workbook that is currently active within the same instance of Excel.

Get destination of save in DocumentBeforeSave

I have a template in which I want to display the document path in the footer just before a save happends.
I have got the DocumentBeforeSave Sub all ready and functioning but the problem is I seem to have no way to get the destination path for the document, unless i'm missing something.
Private WithEvents App As Word.Application
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
' UPDATE FOOTER HERE '
End Sub
I first thought that maybe the parameter Doc contained the destination, but I've only found the current directory.
The problem is only when doing a 'Save As', otherwise the footer don't need changing.
By now you know you need to save as a '.docm' if you have VBA code. Not that the following will do what you want, but it is an example of how to see the default save path, and the 'latest' save path for this document. I set it to display different messages (on close) if someone does a SaveAs.
Option Explicit
Dim strPath As String
Private Sub Document_Open()
MsgBox "On Open, default save path is: " & Options.DefaultFilePath(wdDocumentsPath)
strPath = ActiveDocument.Path
End Sub
Private Sub Document_Close()
If strPath <> ActiveDocument.Path Then
MsgBox "Document now in DIFFERENT path." & vbCrLf & _
"On Close, document was saved at: " & ActiveDocument.Path & vbCrLf & _
"Originally the document was in path: " & strPath
Else
MsgBox "Document still in same path." & vbCrLf & _
"On Close, document was saved at: " & ActiveDocument.Path & vbCrLf & _
"Full Path & Name: " & ActiveDocument.FullName
End If
End Sub