Insert pdf as a package from VBA, to avoid application associations - vba

I am attempting to speed up insertion of pdf's as embedded files into a Word document.
In MS Word, from the insert object dialog, it is possible to select 'package' as an option. Doing this avoids the automatic association of the inserted file with a particular application, which is required, as not all users of this document have the same PDF reader installed.
After manually inserting a file that does not have associations, I have switched to field codes to view the class type of the inserted package, the field code reads: { EMBED Package }
So I have tried the following:
Application.Selection.InlineShapes.AddOLEObject _
ClassType:="Package", _
FileName:=FiletoInsert, _
LinkToFile:=False, _
DisplayAsIcon:=True, _
Range:=Application.Selection.Range.Next(Unit:=wdCell, Count:=1)
But the embedded file resulting from this is still associated with Foxit or Adobe applications.
On comment suggestion, I've tried the macro recorder to check the parameters input by the application when using that approach, output in Macro:
Selection.InlineShapes.AddOLEObject ClassType:="Package", FileName:="", _
LinkToFile:=False, DisplayAsIcon:=True, IconFileName:= _
"C:\WINDOWS\system32\packager.dll", IconIndex:=0, IconLabel:="Package"
I have tried changes based on this, but still including the FileName of the file to be inserted, but the application association remains.
How do I go about embedding these files without the association with an application, so that any user can open the pdf?

Related

Export discontinuous range of pages to PDF

I am trying to save a Word template in .pdf format. I need to print the following range (1-3,18). The problem is that using "ExportAsFixedFormat2" does not allow me to select that range or at least I dont know how:
wdapp.ActiveDocument.ExportAsFixedFormat2 OutputFileName:=savenamepdf, ExportFormat:=wdExportFormatPDF, Range:=wdExportFromTo, From:=1, To:=3
If I use "printout" I can select the range and create the pdf file, but when I try to open it I get an error message like it is broken or corrupted:
wdapp.ActiveDocument.PrintOut OutputFileName:=savenamepdf,_ Range:=wdPrintRangeOfPages, Copies:=1, Pages:="1-3,18"
Anyone knows how to print that range?
here is the whole code block
Select Case cell
Case 100
With wdApp
.ActiveDocument.SaveAs2Filename:=savenameword,ReadOnlyRecommended:=False
.ActiveDocument.ExportAsFixedFormat2OutputFileName:=savenamepdf,ExportFormat:=wdExportFormatPDF,Range:=wdExportFromTo, From:=1, To:=4
.ActiveDocument.Close
End With
Case 189
With wdApp
.ActiveDocument.SaveAs2 savenameword
.ActiveDocument.PrintOut OutputFileName:=savenamepdf,Range:=wdPrintRangeOfPages, Copies:=1, Pages:="1-3,18"
.ActiveDocument.Close
End With
End Select
What you want is not supported. The only way around it would be to bring together the content into a different/new document, then save that to PDF.
Or, a copy of the document can be opened in Word, the material that's no wanted deleted, then save the document as PDF.
The PrintOut method to a file generates a text file that can later be sent to the printer. It's in a special format and the Word content is in a binary format. It's not a converter to other file formats, even if you append a pdf extension to the file name, the content won't be PDF.
For more information about what printing to a file is used for:
https://answers.microsoft.com/en-us/windows/forum/windows_vista-windows_programs/what-does-print-to-file-mean/2e73491c-634f-4067-8b7e-c158f647129d
https://word.tips.net/T000462_Printing_to_a_File.html
http://ask-leo.com/what_is_print_to_file_used_for.html
I have experienced similar issues.
Before calling PrintOut set the wdApp.ActivePrinter to "Microsoft Print to PDF".
wdApp.ActivePrinter = "Microsoft Print to PDF"
If your default/application printer is some other printer (even cutepdf or 7-pdf, etc) the resulting pdf is likely to be corrupted.
I tried the same, and couldn't find a way based on word alone.
What I do now is to save the whole document to a pdf file, then extract the pages I need with pdftk. Of course you mast have pdftk installed.
It can be automated in a VBA macro, thus:
ActiveDocument.ExportAsFixedFormat OutputFileName:="tempfile.pdf", _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportFromTo, From:=page1, To:=99999, _
Item:=wdExportDocumentContent, _
IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=True
With ActiveWindow.View
.MarkupMode = wdInLineRevisions
.RevisionsFilter.Markup = wdRevisionsMarkupAll
.RevisionsFilter.View = wdRevisionsViewFinal
End With
commandstring = "pdftk tempfile.pdf cat " & pagerange & " output outfile.pdf"
StatusBar = commandstring
SynchronousShell (commandstring)
Kill "tempfile.pdf"
the variable "pagerange" contains the desired page range following pdftk conventions.
"Item" can be set to 'wdExportDocumentWithMarkup' if you want. ( I often need to do that )
The code works for me but may not be suitable for production. For one thing, it does not check contention on the temporary file.

Problems saving document immediately after Document Merge

I have an application where I need to merge several nearly identical documents which had been sent out to several users and received with minor changes and comments. The documents are fairly large (500K - 1M) and can contain tables and embedded graphics. The point of this is to consolidate the changes and comments from the various users into one document, keeping track of who did or said what.
The heart of this is the following procedure which uses Application.Merge.
Public Sub runMerge(files As String)
Dim i As Integer
Dim v() As String
v = Split(files, vbCr)
Word.Application.ScreenUpdating = False
Word.Documents.Open fileName:=v(0), ReadOnly:=False, addtorecentfiles:=False
For i = 1 To UBound(v)
ActiveDocument.Merge fileName:=v(i), _
MergeTarget:=wdMergeTargetCurrent, _
DetectFormatChanges:=True, _
UseFormattingFrom:=wdFormattingFromCurrent, _
addtorecentfiles:=False
DoEvents
Next i
Word.Application.ScreenUpdating = True
Word.Application.ScreenRefresh
ActiveDocument.SaveAs2 "Merge " & Replace(Now, ":", "."), , , , False
End Sub
The code opens the first file explicitly, then merges the remaining documents in a loop. Apart from being a bit fragile, this works correctly as long as the first document was explicitly opened.
Once merged, I use SaveAs2 with a new unqualified file name (i.e. no explicit directory). This works fairly well.
However, if I attempt to use SaveAs2 to place the file in a different directory, as in
ActiveDocument.SaveAs2 "C:\.....\Merge " & Replace(Now, ":", "."), , , , False
the resulting document does not re-appear on the screen after the merge. Further, when explicitly opened later, the document appears somehow damaged, strangely formatted, in one case, some of the text appeared in an orange colour. This behaviour has been seen in Word 2013 and 2016.
Apart from saving the document in whatever default directory (My Documents, in my case), then explicitly moving the file in VBA using copy and Kill and what not, how would one save this without an extra step?
In the end, I did the following to solve the save problem.
Using the super-easy FileCopy VBA function, I copied the first file in the merge group to the directory where I wanted the merged file to end up.
The merge loop remains unchanged.
When the merge loop is done, I used the solution from an earlier post, VBA word table copy loses data, ActiveDocument.Select followed by Selection.Collapse.
ActiveDocument.Save, not SaveAs

How can I change the path of a saved export from a form in Access using VBA?

I'm using 'Saved exports' to update an application in Access. Until recent it has been working fine because every user was using the same location. Since Windows 8, this location is protected and some have relocated the target file. An input box asks for the path to this new location.
Now I'm looking for a way to introduce this path into the Saved Export or a VBA-way to export forms and queries to the target file.
My research showed me a lot of export of data, but never the export of components.
If you really want to continue using Saved Exports to transfer the database objects then you'll have to tweak the XML in the ImportExportSpecification object as described in the answers to the question here:
How to specify a different file path for a saved Excel import
However, that approach offers little benefit in your case because you don't need the extra features of a Saved Import/Export (column mapping, date formats, character sets, etc.). It would be much more straightforward to use the VBA DoCmd.TransferDatabase method like this
targetDbSpec = "C:\Users\Public\SomeOtherDb.accdb"
DoCmd.TransferDatabase _
TransferType:=acExport, _
DatabaseType:="Microsoft Access", _
DatabaseName:=targetDbSpec, _
ObjectType:=acQuery, _
Source:="ClientQuery", _
Destination:="ExportedQuery"

Embed a file into a Word doc using VBA

I am attempting to do this from Access 2010 using Word 2010. I have a WordDoc object and cannot find a way to embed a file.
I tried starting from nothing using a bookmark:
bmFile.Range.InsertFile "C:\Users\Me\Desktop\TestFile.xlsx"
and that trew an error about the File being corrupted.
I tried editing an existing embeded file using WordDoc.InlineShapes(1) but no properties were changable or relevant.
Any ideas would be greatly appreciated.
Thanks
theWordDocObject.InlineShapes.AddOLEObject _
FileName:="pathtofile", _
LinkToFile:=False, DisplayAsIcon:=False
(works at least with Excel files)
From an existing file (as per your example) you should be able to do this
bmFile.Range.InlineShapes.AddOLEObject ClassType:="Excel.Sheet.12", _
FileName:="C:\Users\Me\Desktop\TestFile.xlsx", _
LinkToFile:=False, _
DisplayAsIcon:=False
It's actually nastier to insert an object without using a file. You can do it by setting the FileName parameter to "", but then the OLE server will be started and display its UI (which doesn't happen when you embed from a file).
As for modifying anything in the embedded object, it isn't particularly straightforward because the object's UI tends to get in the way, but the starting point is the OLEFormat member of the Shape (or InlineShape). Difficult to find because "OLEFormat" is not a particularly informative name.

MS Word Macro ... unable to insert PNG

Has anyone had problems inserting a PNG file into a word document, using a VBA Macro?
I have an MS Word document that contains a very large directory listing of image files, inside a table. I've been asked to update the document by inserting the corresponding image in front of the name.
Now, if I enter the image manually (using Insert|Image|From File), I'm able to successfully place the PNG image ... so I decided to write a quick VBA Macro to insert the image for me. The following is a sample of the code:
Dim myFile As String
Selection.SelectCell
Selection.Copy
myFile = _
Chr(34) & "C:\Documents and Settings\...\Project\Images\" _
& Left(Selection.Text, Len(Selection.Text) - 2) & Chr(34)
Selection.InlineShapes.AddPicture _
FileName:=myFile, LinkToFile:=False, SaveWithDocument:=True
Outcomes:
Whenever I execute the macro, I get the "Unable to Convert" error dialog, and no image is inserted.
I even changed the code to invoke the wdDialogInsertPicture Dialog instead, and it worked just fine.
This is very confusing ... using a manual process, the insert works, but going with an automated solution, the insert doesn't work!
Any ideas or suggestions?
I've tried the macro several times and it works ... it seems that I'm no longer able to re-create the error again. So, I'm going to mark this under the "mysteries of Office VBA" column and leave it as is ... this is not a high-priority project, so there is no need for me to continue investigating.
Thanks to Alain and Joel Spolsky for their help.