Microsoft Word - Dynamically Pull in HTML File and Append It - Possible? - scripting

Do Word documents have any scripting capabilities for presenting dynamic information? What I want to do is have the document dynamically pull in the contents of an HTML file and append it at the end of the document every time it is opened.
Anybody know if this is possible?

Put the following in a code module. The AutoOpen routine is run each time the document is opened.
Public Sub AutoOpen()
Dim currentDocument As Document
Set currentDocument = ActiveDocument
Dim sourceDocument As Document
Set sourceDocument = Application.Documents.Open(FileName:="e:\mySourceName.docx")
sourceDocument.Range.Copy
sourceDocument.Close wdDoNotSaveChanges
Set sourceDocument = Nothing
Dim pasteRange As Range
Set pasteRange = currentDocument.Range
pasteRange.Collapse wdCollapseEnd
pasteRange.Paste
End Sub

Related

Pasting multiple images in a word doc

I need assistance in building a macro that would take the image that is stored in the clipboard and paste it in the word doc. There will be multiple images so sequential images must be pasted at the end of the document.
Here is my current code so far
' Create word document and paste to word
Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
wordobj.Visible = True
Set objSelection = wordobj.Selection
objSelection.Paste
' Paste in the active end of the word document
'??? tried multiple lines but it gives "object" error
objdoc.ActiveDocument.Content
objdoc.Collapse Direction:=wdCollapseEnd
objSelection.Paste.Paste
Any assistance will be helpful
Since your code creates a new document each time it's run, the only way there'd be anything to paste over is if that new document already has some content. But since you don't even specify a template to load from, that can only mean Word's 'Normal' template, which should never have any content. Regardless, it's as simple as:
Sub Demo()
Dim wordobj As Object, objdoc As Object
Set wordobj = CreateObject("Word.Application")
Set objdoc = wordobj.Documents.Add
With objdoc.Range
.InsertAfter vbCr
.Characters.Last.Paste
End With
End Sub

How to fix: ThisDocument.Close freezes MS Word

Why is following code running from MS Word (MailMerge main document) freezing the application on ThisDocument.Close False?
Do I need to close the Scripting.Dictionary in some way other than setting the object to nothing?
There is only one instance of Word active, it is visible, ThisDocument is not the active document.
I am even explicitly activating the last opened document, even if it is already active. Not sure if I even need to set the oWorkbook and oExcel to nothing.
Sub MailMergeAlternative()
Dim oExcel As Object
Dim oWorkbook As Object
Dim oFirstCell As Object
Set oExcel = CreateObject("Excel.Application")
Set oWorkbook = oExcel.workbooks.Open(SOUBOR)
Set oFirstCell = oWorkbook.sheets(SESIT).Cells(1, 1)
Dim Dict As Object
Set Dict = MakeDictionary() ' Scripting.dictionary
Dim oDoc As Object
Dim Radek As Long
Dim Radku As Long
Radku = oFirstCell.currentregion.Rows.Count
For Radek = 2 To Radku
' ... fill Dict, use MailMerge to create new document for active record ...
Set oDoc = ActiveDocument ' the new document after MailMerge
' ... insert values, save the new document, do not close it ...
Next
Closing:
oDoc.Activate ' <== set to active, not needed
Set Dict = Nothing
oWorkbook.Close
oExcel.Quit
Set oWorkbook = Nothing ' probably not needed, closed above
Set oExcel = Nothing ' probably not needed, closed above
ThisDocument.Close False ' <== Problem
End Sub
Expected:
The code runs, creates new document(s) and closes the document which is containing the macro and from where it was called. The last active document stays open (the newly created one), or if nothing was created, Word app closes.
What is happening:
The document closes, the last active document stays open. But Word freezes and the document needs to be found in Task Manager and "brought to foreground". This is not a problem when using MailMerge alone (with additional vba work) and seems to be connected to use of Excel and Scripting.Dictionary.
Since you don't provide a [mcve] so that we can test exactly what you're doing it's possible that the following solution won't work for your exact environment. My test was run on the code below, which essentially creates a number of new documents then closes a document. (I have no access to your Excel content or to MakeDictionary())
I created a template (dotm) and put the code in that, closed it, created a new document from the template. This document has access to the code, via its link to the template. Closing the document will also release the template (unless another document based on it is opened). But in my test the code finished without an error.
Sub TestCloseSelfDocument()
Dim docMmMainMerge As Word.Document
Set docMmMainMerge = ActiveDocument
Dim Dict As Object
Dim oDoc As Object
Dim Radek As Long
Dim Radku As Long
Radku = 5
For Radek = 2 To Radku
Documents.Add
' ... fill Dict, use MailMerge to create new document for active record ...
Set oDoc = ActiveDocument ' the new document after MailMerge
' ... insert values, save the new document, do not close it ...
Next
Closing:
Set Dict = Nothing
docMmMainMerge.Close False
End Sub

MS Word VBA: Get document's attached template

(Using Windows 10 and MS Word 2016. Global templates are: Normal.dotx and Autoload.dotm. Attached template to some docs is: Reference.dotx)
Hello everyone,
I'm having problems in VBA getting the attached template of a document.
I have a global template that loads when I load MS Word, called Autoload.dotm. But, for some specific documents, they use an attached template, which is not the global template (Autload.dotm) or the regular template (Normal.dotx). This attached template is called Reference.dotx.
So I use ActiveDocument.AttachedTemplate. But this returns Autoload.dotm, not Reference.dotx. I need to find out if the attached template defined in Developer->Document Template->Templates tab->Document Template is Reference.dotx. (Don't think it makes a difference, but the "Automatically update document styles" checkbox is checked.) Does anyone know how I can find if a document uses Reference.dotx? I don't need any of the global templates returned.
The code I'm using to try to get the attached template is simple:
If (ActiveDocument.AttachedTemplate = "Reference.dotx") Then
PrepareDocument_enabled = True
End If
Maybe this will help you? It will show the template used.
Sub Macro1()
Dim strPath As String
strPath = Dialogs(wdDialogToolsTemplates).Template
MsgBox strPath
End Sub
Otherwise, you can use this to change the template
Sub ChangeAttachedTemplate()
Dim oDoc As Document
Dim oTemplate As Template
Dim strTemplatePath As String
Set oDoc = ActiveDocument
If oDoc.Type = wdTypeTemplate Then Exit Sub
Set oTemplate = oDoc.AttachedTemplate
Debug.Print oTemplate.FullName
' Path is probably: C:\Users\USERNAME\AppData\Roaming\Microsoft\Templates\
If InStr(UCase(oTemplate.FullName), UCase("Path of the template")) > 0 Then
oDoc.AttachedTemplate = "PATH TO TEMPLATE" & "TEMPLATE NAME.dotm"
End If
End Sub

Automation of PDF String Search using Excel VBA - OLE error

I'm getting this error, "Microsoft Excel is waiting for another application to complete an OLE action" when trying to automate a PDF string search and record findings in excel. For certain PDFs this error is not popping. I assume this is due to the less optimized PDFs taking a longer time to search string while indexing page by page.
To be more precise, I have a workbook containing two sheets. One contains a list of PDF file names and the other has a list of words that I want to search. From the file list the macro would open each PDF file and take each word from the list of words and perform a string search. If found it would record each finding in a new sheet in the same workbook with the file name and the found string.
Below is the code I'm struggling with. Any help is welcome.
Public Sub SearchWords()
'variables
Dim ps As Range
Dim fs As Range
Dim PList As Range
Dim FList As Range
Dim PLRow As Long
Dim FLRow As Long
Dim Tracker As Worksheet
Dim gapp As Object
Dim gAvDoc As Object
Dim gPDFPath As String
Dim sText As String 'String to search for
FLRow = ActiveWorkbook.Sheets("List Files").Range("B1").End(xlDown).Row
PLRow = ActiveWorkbook.Sheets("Prohibited Words").Range("A1").End(xlDown).Row
Set PList = ActiveWorkbook.Sheets("Prohibited Words").Range("A2:A" & PLRow)
Set FList = ActiveWorkbook.Sheets("List Files").Range("B2:B" & FLRow)
Set Tracker = ActiveWorkbook.Sheets("Tracker")
'For each PDF file list in Excel Range
For Each fs In FList
'Initialize Acrobat by creating App object
Set gapp = CreateObject("AcroExch.App")
'Set AVDoc object
Set gAvDoc = CreateObject("AcroExch.AVDoc")
'Set PDF file path to open in PDF
gPDFPath = fs.Cells.Value
' open the PDF
If gAvDoc.Open(gPDFPath, "") = True Then
'Bring the PDF to front
gAvDoc.BringToFront
'For each word list in the range
For Each ps In PList
'Assign String to search
sText = ps.Cells.Value
'This is where the error is appearing
If gAvDoc.FindText(sText, False, True, False) = True Then
'Record findings
Tracker.Range("A1").End(xlDown).Offset(1, 0) = fs.Cells.Offset(0, -1).Value
Tracker.Range("B1").End(xlDown).Offset(1, 0) = ps.Cells.Value
End If
Next
End If
'Message to display once the search is over for a particular PDF
MsgBox (fs.Cells.Offset(0, -1).Value & " assignment complete")
Next
gAvDoc.Close True
gapp.Exit
set gAVDoc = Nothing
set gapp = Nothing
End Sub
I have now found the answer to this problem.
I'm using Acrobat Pro and whenever I open a PDF file, it opens with limited features due to Protected View settings. If I disable this function or if I click Enable All Features and save changes to the PDF files, VBA macro runs smooth.
It's funny, I'm posting an answer to my own problem.

Selecting Outlook Emails to Paste to Word Document - VBA Macro

I want to:
Select all emails from a certain sender
Copy the body of the email to a new Word document
Save the word document to a specific directory
Clear the clipboard
I'd like to know what else I need to do, especially in the the FindSetAside() and SaveToDicrectory() functions.
Sub FindSetAside() 'find all set-aside emails
End Sub
Sub PasteToWord()
Dim Word As Word.Application
Dim Doc As Word.Document
Dim activeMessage As Outlook.MailItem 'the email to copy
Dim activeBody As String
If TypeName(ActiveExplorer.Selection.Item(1)) = "MailItem" Then
'get the active email
Set activeMessage = ActiveExplorer.Selection.Item(1)
'setup Word
Set Word = CreateObject("Word.Application")
WordApp.Visible = True
setDoc = Word.Documents.Add
'Copy selection to document
activeMessage.GetInspector().WordEditor.Range.FormattedText.Copy
Doc.Range.Paste
Call ClearClipboard
End If
End Sub
Sub SaveToDirectory() 'Save the Word Document to the correct directory
End Sub
Public Sub ClearClipboard()
Dim Data As New DataObject
Data.SetText Tex:=Empty
Data.PutInClipboard
End Sub
I am using Outlook 2010. I am also considering adding some code to send the Word document as an attachment to specific emails, but perhaps that is irrelevant to this question.
Using Explorer.Selection won't help if you need to execute a search for certain emails (unless you use Explorer.Search, which executes a search in the UI). Take a look at this to help determine the search method you need to use:
https://msdn.microsoft.com/EN-US/library/ff869846.aspx
Then it is just a matter of traversing the returned collection and accessing the MailItem objects within.
To save the Word document, use Document.SaveAs2.