Accessing Word fields and auto texts from embedded Excel - vba

I have some Word documents/templates with embedded Excel sheets/charts. Is it possible from Excel VBA to access data (bookmark contents, fields, auto texts) that is stored in the Word document?
An example of data could be patient ID stored in a Word auto text.
The VBA code must be inside the embedded Excel, not in the Word template, as I can't modify this.
The VBA code will probably be launched by double-clicking the embedded sheet, then pressing a shortcut key, but this is not part of my question.

Try
Sub HelloWord()
Dim wordApp As Object
Set wordApp = GetObject(, "Word.Application")
MsgBox wordApp.Activedocument.FullName
End Sub
Once you've got a handle on the the wordApp, you can access all the objects in the model as normal.
The downvote might be because this doesn't sound like a very efficient solution - might it be better to get the Excel data into a Word document or format the Excel document in an acceptable way. You're invoking two pretty chunky apps here to do one thing.

Related

Word VBA Runtime Error 5460 on second Documents.Add in global template

For a customer, I have created a Global template with a ’New Document” button that shows a userform letting the user create a new document from a choice of templates, e.g. Letter, Invoice, etc.
Recently, we have added the choice Report.
The code executed from this userform is very simple, using e.g.
Documents.Add Template:="Letter.dotm", NewTemplate:=False
to create the new documents.
The Report template is – by my standards – quite complex, with AutoNew and AutoClose macros, an EventClassModule, it writes to and reads from the CustomDocumentProperties, opens several specific Word documents from where it copies text and pastes it into the Report document, etc.
The first time a new Report is created it works as planned; but the second time (in the same Word session) the Report option is used, a ‘Runtime Error 5460’ occurs. And after that, any of the other document options returns the same error.
Quitting Word and starting a new Word session sets everything back to normal, until the Report template again is called the second time.
Strangely enough, the Report template works with no errors when new documents based on it are created directly from Explorer, as many times in the same Word session as needed.
The problem occurs in Word 2016 (365) with Windows 7 Pro, but not in Word 2013 with Windows 10.
Anybody that has ever experienced anything like this?? Help is really appreciated.
Runtime Error 5460: 'A file error has occured.'
Debug is not possible.
The Report template has thousands of lines of code and I have not been able to find out if it is in fact code in the Report template that causes the error, or code in the Global template.
As said, the Report template works fine when used from Explorer, and when called via the Global template in 2013 everything works there too.
Problem solved!
I followed the advice from #macropod and added the path also.
In stead of just using
'…
If OptionButton3.Value = True Then
Documents.Add Template:="Report.dot", NewTemplate:=False
End If
'…
I changed the code to:
Private Sub CommandButton1_Click()
Dim strPath As String
strPath = Options.DefaultFilePath(wdWorkgroupTemplatesPath)
Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")
'…
If OptionButton3.Value = True Then
wdApp.Documents.Add Template:=strPath & "\Report.dot", NewTemplate:=False
End If
'…
End Sub
Thanks!!

How to embed an Excel spreadsheet into a Word Document programmatically using VBA

I have an Excel VBA script that pulls data from a couple of files and builds a table in a certain format that suits the business need. I build the table in a hidden worksheet within my main Excel file and all works as intended.
However, I need to insert that table into a Word file. I know how to make a table, but I wanted to try to do an embedded Excel file instead because that way all of the formatting transfers.
I have created an accompanying Word file with a placeholder embedded Excel object. I gave the object (or "shape") a name in the Selection Pane. It's called InvoiceXLS.
I can get as far as opening the Word document and I know how to change basic OLEShapes / objects such as just changing text in named text boxes, but I can't figure out how to get a usable reference to the embedded sheet so that I can call Excel VBA commands on it, and basically replace it with the table I generated earlier in the script.
So far, this is how I open the link to the Word file:
Set wApp = CreateObject("Word.Application")
wApp.Visible = True
Set wDoc = wApp.Documents.Open(filename:=ThisWorkbook.path & "\TestAccount.docx")
With wDoc
.Shapes("InvoiceXLS").OLEFormat.Edit ' ???
' How do I get a Worksheet object that I can work with??
' Or, just paste in a whole table over top?
End With
Thanks in advance for any help!

Access The Nth Item of Clipboard

Is there a way to retrieve several items from the clipboard? I'm using something like this:
Dim clipboard As MSForms.DataObject
Dim str1 As String
Dim str2 As String
Set clipboard = New MSForms.DataObject
clipboard.GetFromClipboard
str1 = clipboard.GetText(1)
str2 = clipboard.GetText(2)
However, I get an error where I assign a value to my second variable that says the following:
Run-time error '-2147221404 (800040064)':
DataObject:GetText Invalid FORMATETC Structure
Help is much appreciated!
Turns out there are two clipboards: the Windows clipboard and the Office clipboard.
The Office clipboard can hold up to 24 items (all can be the same type), whereas the Windows clipboard can only hold one item of each type.
Copying to the Windows clipboard is as easy as highlighting then
typing Ctrl-C.
Copying to the Office clipboard is as easy as
highlighting then typing Ctrl-CC. The Office clipboard is only active
if there is at least one Office application open and active at the
time.
In VBA, using the MSForms.DataObject only gets you access to the Windows clipboard, so there is only a single text item available. After a variety of searches, I'm not able to find out how to open/control/copy/paste using the Office clipboard from VBA.
Having said all that, there is likely little reason to use any clipboard when writing and running a VBA macro. You can (temporarily) store those values in unused cells on a worksheet, in a public variable, in a public object, or even a private variable (probably with publically accessible properties). All of those methods serve exactly the same purpose as storing data in the clipboard.
In skimming around the interwebz on this topic, I ran across several references to using the clipboard to copy data between different workbooks, or between Office apps like Excel-to-Word. You still don't need the clipboard for this, as VBA can open the remote/external application/workbook/document and copy/paste the data directly.

VBA Inserting Excel complexe spreadsheet in .doc document

So I've been working on a word .dotm file that will combine several .doc and .xls documents into a single .pdf file.
Right now, I have two different problems, I will only detail the first one on this topic:
When inserting a complexe (very complexe) Excel sheet in my .doc document, the output is only a pile of meta data (Well mostly looks like it, if you prefer clearer language: it is a complete mess of characters and page breaks) instead of my file. I've looked for the entire day (really, I wasted my work day looking for answers) on the internet and even asked on MSDN forum (no answer at all) about this topic and everyone seems to have his code working like a charm.
Here is my code:
Sub MergeFiles()
Documents.Open FileName:="C:\test_cea\02.doc"
Selection.EndKey Unit:=wdStory
Selection.InsertFile FileName:="C:\test_cea\03.doc"
Selection.EndKey Unit:=wdStory
Selection.InsertFile FileName:="C:\test_cea\04.xls"
ActiveDocument.SaveAs2 FileName:="C:\test_cea\output.pdf", FileFormat:=wdFormatPDF
ActiveDocument.Close SaveChanges:=doNotSaveChanges
End Sub
I've tried a TREMENDOUS amount of things, from switching to opening the .xls first, to trying every single combination of parameters possible in my InsertFile() method and nothing works.
The most amusing part is: it works perfectly when trying to do it with Word UI, meaning Word can do it, but I'm doing it wrong somehow.
Here's the final answer to that question:
As Word cannot interpret an Excel file it is not possible to force file insertion this way.
Instead use the following code:
Sub MergeFiles()
Dim appExcel As Excel.Application
Dim wdDocument As Word.Document
Set appExcel = CreateObject("Excel.Application")
Set wdDocument = Documents.Open("mydoc.doc")
appExcel.Workbooks.Open("myxls.xls")
appExcel.ActiveWorkbook.Sheets(1).Range("Print_area").CopyPicture 'Copy picture prevents weird behavior from Word'
Selection.PasteSpecial Placement:=wdInLine, DataType:=wdPasteMetafilePicture
End Sub
Obviously this is a sample code that will do the whole process but the idea is to copy the Print Area (one must be defined, you can also use Sheets(1).UsedRange but this will be a problem if the Excel file is oddly formatted) as picture and paste it into Word. You can also simply copy it and paste it but it may mess up your output table formatting.
I don't even know why people down voted my question -_-
Anyway, if you encouter the same issue, simply tell me if this code works.

Updating/creating Table of Contents in Word using VBA

I'm new to VBA. I'm trying to update the Table of Contents in my Word document everytime I open the document, but it does not seem to update it at all.
In ThisDocument I've done the following:
Private Sub Document_Open()
ActiveDocument.TablesOfContents(1).Update
End Sub
Can anyone help me?
The issue is probably the use of Document_Open - you have to set up the event in the template, not the document you are opening. You can also use an Auto_Open macro. Note that ActiveDocument may also be part of the culprit - the document you open may not yet be the actual active document when you kick the Document_Open event - you may need to set a reference to the document you're opening like:
Dim doc As Document
set doc = Documents.Open(your path here)
doc.TablesOfContents(1).Update
Finally, your Macro Security settings could be disallowing anything from executing.
In all cases, have a good read of Take Control of Microsoft Word Through Events and Running a macro automatically when a document is created, opened or closed.