Embed a file into a Word doc using VBA - 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.

Related

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

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?

MS Word macro - use system variable for template path

I have a template that contains several macros, this template will be distributed on several devices.
I have the following macros to insert a text using quick parts of ms word.
Application.Templates( _
"C:\Users\user_name\AppData\Roaming\Microsoft\Word\STARTUP\template_name.dotm" _
).BuildingBlockEntries("alphabet").Insert Where:=Selection.Range, _
RichText:=True
ActiveDocument.TrackRevisions = Not ActiveDocument.TrackRevisions
The issue is, the code contains the absolute path to the template, which won't be the same on different machines.
I have tried using %Appdata% instead, but there macro did nothing, with no error messages.
is there any way around this ?
Thank you
You can use Environmental Variables in your VBA code to get the 'UserName' i.e.
"C:\Users\" & LCase(Environ("UserName")) & "\AppData\Roaming\.."
Here is one link to show other variables (or just search for 'VBA using environmental variables' (without quotes: https://www.wiseowl.co.uk/blog/s387/environment-variable-vba.htm

Converting ms word files to .docx; what's the point of the .Convert function?

I am trying to figure out if the .Convert function is actually doing anything, what is the difference between these 2 code snippets? Just saving the document in the new file format seems to automatically convert everything I need.
Difference between this:
oDoc = oWord.Documents.Open(FileName:=sOldFile, AddToRecentFiles:=False, Visible:=False, ReadOnly:=False, OpenAndRepair:=True)
oDoc.Convert()
oDoc.Save()
oDoc.Close()
And this:
oDoc = oWord.Documents.Open(FileName:=sOldFile, AddToRecentFiles:=False, Visible:=False, ReadOnly:=False, OpenAndRepair:=True)
oDoc.SaveAs(FileName:=sNewFile, FileFormat:=p_eDestType, AddToRecentFiles:=False, ReadOnlyRecommended:=False)
oDoc.Close()
Thank you.
The Convert method of the document object converts the document to the latest version of the .docx format supported by the version of Word that you are using.
Whether you notice much difference visually will depend on what is in your document. You may notice that if Word was displaying "Compatibility mode" in the document's title bar before, that may disappear, and if you look inside the .docx you may see differences, e.g. in the XML namespace URIs, some details of the encoding, and so on.
The method is (sort of) documented here.

document.customdocumentproperties not being saved

I have searched high and low on stackexchange and other sites (vbaexpress, MSDN, etc...). There is extensive dialog around this, I have tried most of the examples, and still nothing is working.
Scenario:
User clicks 'Create Report' button in Access.
vba creates a new instance of a Word doc from the default template associated with a SharePoint library.
The Word template is formatted with tables and bookmarks to accept data, AND already has a number of custom property fields stored (NULL at this time)
vba pulls data from tables (tables are linked to SharePoint lists) and populates the entire Memo.
the code then saves the new document to the SP library (same one with the template) and checks it in.
All of this works fine.
The vba also includes the code to store both built-in and the custom properties:
example of the code:
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add(tName)
objWord.Visible = True
objDoc.BuiltinDocumentProperties("Title") = "2040"
With objDoc.CustomDocumentProperties
.Add name:="DocLevel", _
LinkToContent:=False, _
Type:=msoPropertyTypeString, _
Value:="Confidential"
.Add name:="UserDiscipline", _
LinkToContent:=False, _
Type:=msoPropertyTypeString, _
Value:="Broker"
End With
objDoc.SaveAs (fPath)
objDoc.CheckIn
Also, assuming that the properties are already objects in the template, I tried this just setting without the .Add:
objDoc.CustomDocumentProperties name:="DocLevel", LinkToContent:=False, _
Type:=msoPropertyTypeString, Value:="Confidential"
Everything works - EXCEPT - the custom doc properties are not saved. Even the built ones are saved - but not the custom ones.
I have the MS Office 14.0 Object Library, 14.0 Access library and VB for extensibility included. Is there some other reference that I need?
Thanks in advance to the Overflow community for any help...
And The answer is....
There is a completely different method available for this: ContentTypeProperties!
'customdocumentproperties' are properties of the Word document. Since this was an attempt to supply custom content to the SharePoint library, a different method was required:
doc.ContentTypeProperties("UserDiscipline").Value = "Broker"
Posting this so hopefully others here won't have to redo this same research.
I have come across the similar issue in Word using VSTO: the custom document properties are there before you close Word but they cannot be saved. I tried to use ContentTypeProperties instead as user3662334 suggested however I cannot access ContentTypeProperties at all due to the following exception "This document must contain Content Type properties. Content Type properties are a common requirement for files in a document management system."
The solution I have found is extremely simple: you just need to update the document content slightly (e.g. add a space in the end of the text) and save the document:
document.Content.Text += " ";
document.Save();

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.