Activate an open Word file in order to use SendKeys - vba

From a macro in Excel, I open a .docm Word doc then search for "<>" (the only text on its line) and replace it with a page break. After the page break is inserted, it leaves an empty line at the end of the previous page where "<>" was.
So I'd like to use the SendKeys function to simulate pressing the up arrow key and then backspace to go up to this empty line and then delete it.
SendKeys works in the active window, so I'm trying to switch the currently active window (Excel) to the Word doc. But everything I have tried hasn't worked. I can't figure out why VBA won't activate the Word Doc! Please help! Thanks in advance! :)
(Below I labeled what I tried that didn't work)
'EARLY BINDING
Dim WordApp As Word.Application
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Dim WordDoc As Word.Document
Set WordDoc = WordApp.Documents.Open(Filename:=word_template_path, ReadOnly:=False)
With WordDoc.Application.Selection
.Find.Text = "<<new page>>"
.Find.Execute
.InsertBreak
' AppActivate "Microsoft Word" - didn't work
' Dim wn As Window
' For Each wn In Application.Windows
' Debug.Print wn.Caption
' Next wn
'^ This loop doesn't even show the word file either! It only iterates once, showing the Excel file the macro is saved in!
' WordDoc.Activate - didn't work
' WordApp.Activate - didn't work
' WordDoc.Windows(1).Activate - didn't work
SendKeys "{UP}"
.TypeBackspace
.EndOf
End With

Use the Document.Activate method which activates the specified document so that it becomes the active document.
WordDoc.Activate

When the code is launched from the Excel document, your original code would effectively not activate Word.Application. But AppActivate WordApp.Caption worked from a button click on an Excel Worksheet body:
As WordApp.Caption = "Word" rather than "Microsoft Word" as you used in the OP.
Sub so5477097ActivateWord()
'EARLY BINDING
'Dim WordApp As word.Application
Dim WordApp As Object
Dim word_template_path As String
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Dim WordDoc As Object
word_template_path = "mypath\template.docx"
Set WordDoc = WordApp.Documents.Open(fileName:=word_template_path, ReadOnly:=False)
'WordDoc.Activate
'WordApp.Activate
With WordDoc.Application.Selection
.Find.Text = "<<new page>>"
.Find.Execute
.InsertBreak
' AppActivate "Microsoft Word" - didn't work
' Dim wn As Window
' For Each wn In Application.Windows
' Debug.Print wn.Caption
' Next wn
'^ This loop doesn't even show the word file either! It only iterates once, showing the Excel file the macro is saved in!
' WordDoc.Activate - didn't work
' WordApp.Activate - didn't work
' WordDoc.Windows(1).Activate - didn't work
AppActivate WordApp.Caption
SendKeys "{UP}"
.TypeBackspace
.EndOf
End With
End Sub
Some images:

Related

Copy table from Word and paste into another Word document

I'm trying to open a Word Document and copy the whole table inside it and then paste it into another already-open document after a specific heading/bookmark (that I have bookmarked in the document). Then finally prompt the user to save the document with the newly pasted table.
Examples seen online are Excel-to-Word or Word-to-Excel; I need Word-to-Word.
I'm able to pull up the first document (I think it successfully copies it, too--I haven't tested it), but when it activates the second document, it stops and gives an error that it doesn't have an object assigned.
The debugger highlights Set WrdRng = Active.Bookmarks("AppendixA").Range.
Sub TEST()
'
' Declare Table Document Var as Object
Dim tb As Object
Dim bk As Bookmark
Dim WrdRng As Range
'
'
'Set up Word Application
Set tb = CreateObject("Word.Application")
tb.Visible = True
'Opens Pre-Saved Document & activates it to use
tb.Documents.Open "C:\ Desktop\Table.dotm"
tb.Activate
Selection.WholeStory
'ActiveDocument.Tables(1).Select
Selection.Font.Name = "Calibri"
Selection.Copy
'Activate Rolling Trend Report Document and Paste
Windows("TEST - Compatibility Mode").Activate
' where the error occurs and the debugger highlights
Set WrdRng = Active.Bookmarks("AppendixA").Range
'Paste to Bookmark
With WrdRng
Selection.InsertAfter
End With
'Save Completed Report to Desktop
ChangeFileOpenDirectory "C: \Desktop\"
ActiveDocument.SaveAs2 FileName:="TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
'
'
'
End Sub
Your code is failing because Set WrdRng = Active.Bookmarks("AppendixA").Range should be Set WrdRng = ActiveDocument.Bookmarks("AppendixA").Range
However, your code is badly written, will also fail in other places and will create an extra instance of Word.
The code below is to run from Word
Sub TEST()
'store a pointer to the document you wnat to insert table into
'assumed to be currently active document
Dim targetDoc As Document
Set targetDoc = ActiveDocument
'Open Pre-Saved Document
Dim tblDoc As Document
Set tblDoc = Documents.Open("C:\ Desktop\Table.dotm")
Dim source As Range
Set source = tblDoc.Content
'exclude the paragraph that comes after the table
source.MoveEnd Unit:=wdCharacter, Count:=-1
source.Font.Name = "Calibri"
Dim appxA As Range
Set appxA = targetDoc.Bookmarks("AppendixA").Range
appxA.Collapse wdCollapseEnd
'transfer the text and close the source document
appxA.FormattedText = source.FormattedText
tblDoc.Close wdDoNotSaveChanges
'it is necessary to pass the full file path to the SaveAs command
ActiveDocument.SaveAs2 FileName:="C: \Desktop\TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
End Sub

Opening and then breaking links to a Word document from Excel

I have an excel spreadsheet that is linked to multiple Word documents (.docx), which act as templates.
I have written a macro that opens the required word template from excel (the template chosen is dependent on the value of cell M17). The links in the word template update automatically as word opens. I am then trying to break the links of the document that I opened. This is what I have so far:
Function FnOpeneWordDoc()
Dim objWord
Dim objDoc
Dim path As String
path = Range("M17")
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("*file_path*" & path & ".docx")
objWord.Visible = True
Application.Wait (Now + TimeValue("0:00:30"))
objDoc.Fields.Unlink
End Function
I suspect that it isn't working because the macro is trying to break the links before the document has fully loaded (and therefore the existing links haven't had a chance to update?), which is why I added the wait. Unfortunately this doesn't seem to be the solution.
The above code would have been fine, but I didn't realise that the code had to be different if the text was in textboxes.
I struggled to break the links within textboxes, and kept getting run-time error 438. However, I found a workaround:
I wrote a sub in the word documents:
Sub Unlink
Selection.Fields.Unlink
End Sub
I then called this macro from my excel document:
Sub FnOpeneWordDoc()
Dim objWord
Dim objDoc
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("filename")
objWord.Visible = True
For i = 1 To objDoc.Shapes.Count
objDoc.Shapes(i).Select
objDoc.Application.Run ("unlink")
Next
End Sub

Check if Word document closed from Excel VBA

I'm performing several prints of embedded Word document witch has some fields linked to some cells, by my PrintOut macro, in a For..Next loop, as below.
I need after each print task, that the program wait for document to close and then doing the next print.
In this situation I receive error. Can anyone help ?
Sub contract()
Dim i As Integer
For i = 1 To 100
Cells(Sheets("SheetName").ListObjects("StaffInfo").ListRows.Count + 9, 8).Value = i
General.PrintIt ("EmbeddedDoc") 'Doc has many linked fields
Next i
End Sub
Print method
Sub PrintIt(P As String)
Dim objWord As Object
Dim ObjDoc As Object
Dim Oshp As Object
Application.ScreenUpdating = False
ActiveSheet.OLEObjects(P).Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = False
Set ObjDoc = objWord.ActiveDocument
ObjDoc.Fields.Update
For Each Oshp In ObjDoc.Content.ShapeRange
Oshp.TextFrame.TextRange.Fields.Update
Next
ObjDoc.PrintOut Background:=False
ObjDoc.PrintOut
objWord.Quit SaveChanges:=False
Application.ScreenUpdating = True
End Sub 'Print it
Introduced problem was solved by this code.
Above code do open and close embedded word document, 100 times, and that problem was happening in close document.
Exactly, I cant understand why closing document immediately after printout command that where after open and update fields, generating that error.
Thus I cleaned the problem ask!
By integrating "PrintIt" method in "Contract" method that is parent of that, without calling "PrintIt" for each document printout, embedded document opens each one, perform doc links updating and printing 100 times in for next loop and close word app and document, at last, each one too.
In short, I cant find reason of problem in several Open-Print-Close document in order immediately; But i change the algorithm to Open-Several print-Close and problem been cleaned!
Sub contract()
Application.ScreenUpdating = False
Sheets("SheetName").Unprotect
'Declare variables
Dim i As Integer
Dim objWord, ObjDoc As Object
'Core
ActiveSheet.OLEObjects("Contract").Activate
Set objWord = GetObject(, "Word.Application")
objWord.Visible = False
Set ObjDoc = objWord.ActiveDocument
For i = 1 To 100
Cells(x, y).Value = i 'A specific cell that
' word embedded document fields are linked to
'corresponding fields they values change
'by changing this cell.
ObjDoc.Fields.Update
ObjDoc.PrintOut Background:=False
ObjDoc.PrintOut
Next i
objWord.Quit SaveChanges:=False
Sheets("SheetName").Protect AllowFiltering:=True
End Sub

Can not copy from Excel and paste to a Form Edit restricted Word document unless restriction is turned off

I am copying Excel cell contents to a bookmark on a Form Edit restricted (2010) Word document but it will only paste if the protection is turned off.
The code I currently have to turn the protection on again afterwards errors. What is the correct code?
Is there a way to make this copy and paste without turning off the protection?
Second problem is that when the text is pasted to the bookmark the font is Red (if manually entered on the document it is in black). The Word default is set as black (I reset the default for good measure). Typing in a new document is in black, however, when Word opens the font icon shows red even though checking the default it is still shows black. Can I define the font colour in the VBA to override this issue until is is resolved or can you suggest a way to fix the Word default?
Sub Arzbericht_Brandstetter()
' x - Defined Cell Names - ARTBrandPATH , ARTBrandDOC
' Excel Word Bookmark
' x - Defined Cell Names - ARZKrankenhaus Text65
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Dim Wd As Object
Dim wdDoc As Object
Dim BrandstetterDoc As Object
Dim BrandstetterPath As String
Dim f As Boolean
BrandstetterPath = ActiveSheet.Range("ARTBrandPATH").Value & ActiveSheet.Range("ARTBrandDOC").Value & ".doc" ' x
' On Error Resume Next
Set BrandstetterDoc = GetObject(BrandstetterPath)
If BrandstetterDoc Is Nothing Then
Set Wd = GetObject(, "Word.Application")
If Wd Is Nothing Then
Set Wd = CreateObject("Word.Application")
If Wd Is Nothing Then
MsgBox "Failed to start Word!", vbCritical
Exit Sub
End If
f = True
End If
Set BrandstetterDoc = Wd.Documents.Open(BrandstetterPath)
If BrandstetterDoc Is Nothing Then
MsgBox "Failed to open Brandstetter Document!" & vbNewLine & _
" Check File Directory is correct", vbCritical
If f Then
Wd.Quit
End If
Exit Sub
End If
Wd.Visible = True
Else
With BrandstetterDoc.Parent
.Visible = True
.Activate
' Turn Protection OFF
With ActiveDocument
.Unprotect "xxxxx"
.Protect wdAllowOnlyRevisions, , Password:="xxxxx"
End With
BrandstetterDoc.Bookmarks("Text65").Range.Text = ws.Range("ARZKrankenhaus").Value
' Turn Protection ON (Restricted Editing)
' ActiveDocument.Protect Type:=wdAllowOnlyFormFields, NoReset:=True
End With
End If
End Sub
Because its a Formfield and not just a bookmark I changing the code as below which resolved the strange red font issue. I can now copy to the document protected.
From
BrandstetterDoc.Bookmarks("Text65").Range.Text = ws.Range("ARZKrankenhaus").Value
To
ActiveDocument.FormFields("Text65").Result = ws.Range("ARZKrankenhaus").Value

Using VBA, how can I write text of different heading levels in Word from Excel?

Using VBA 2007, how can I create a Word document from Excel and write text of different headings (heading1, heading2, normal) so that the headings would appear in the document map?
This example will run from Excel. It uses Early Binding so you need to ensure you have a reference to Word set in the VBA References (Tools->References).
Word can be a fickle best with putting text in the document. Generally it needs to go a the currently selected point. You can use Bookmarks and/or field codes to put text in different locations within a document.
Sub MakeWordDocumentWithHeadings()
Dim wdApp As Word.Application, wdDoc As Word.Document
'Use on error resume next so VBA doesn't produce an error if it can't find Word Open
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
'If it is nothing the open a new instance of word
If wdApp Is Nothing Then Set wdApp = New Word.Application
'Reset the errors
On Error GoTo 0
'Add a new document
Set wdDoc = wdApp.Documents.Add
'Word works by the location of the 'selection'
wdApp.Selection.Style = ActiveDocument.Styles("Heading 1")
wdApp.Selection.TypeText Text:="Heading One"
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 2")
wdApp.Selection.TypeText Text:="Heading Two"
wdApp.Selection.TypeParagraph
wdApp.Selection.Style = ActiveDocument.Styles("Heading 3")
wdApp.Selection.TypeText Text:="Heading Three"
wdApp.Selection.TypeParagraph
'Save close or whatever here
'Always set objects to nothing.
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub