Activate Word window from Excel with VBA - vba

I am trying access window of MS Word from Excel. I found methods to access a new Word document or a specific one, like the one at
Copy Text from Range in Excel into Word Document,
But in my case I do not know the name of the document, it should be the last active one. I was hoping to use something like
Word.ActiveDocument
but no success. I also tried to simulat Alt+Tab keystroke to activate the window with
Application.SendKeys("%{TAB}")
but it does not work too. Any hint?
I am trying to create a macro that will just copy charts and some text around to Word and do some formating of the text along with it. So basically I can use any approach to this task.
Thanks a lot.

You can access an open instance of Word by using late binding (http://support.microsoft.com/kb/245115) and GetObject. If you have multiple instances of Word open you are not guaranteed of getting any one of them in particular though.
Getting an instance of Word will allow you to access the ActiveDocument or the Application's current Selection. I'd still suggest doing some error checking to make sure you've got what you want.
Sub GetWordDocument()
Dim wdApp As Object
'Turn off error handling since if the Application is not found we'll get an error
'Use Late Binding and the GetObject method to find any open instances of Word
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
On Error GoTo 0
'Check to see if we found an instance. If not you can create one if you desire
If wdApp Is Nothing Then
MsgBox "No instances of Word found"
Exit Sub
End If
'Check if there are documents in the found instance of Word
If wdApp.Documents.Count > 0 Then
wdApp.Selection.TypeText "Cool, we got it" & vbCr
'You can now access any of the active document properties too
wdApp.ActiveDocument.Range.InsertAfter "We did indeed"
End If
'Clean up the Object when Finished
Set wdApp = Nothing
End Sub

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!!

Open Word from Excel, pass variables and text (VBA macro), remote-control Word

I'm completely new to VBA, especially across different programs, but I have created myself a little real-world task that quickly got complicated, someone could give me some pointers or code snippets to try out to achieve the following:
I have an Excel file that's filled with names and numbers (see below) and I would like to transfer them individually to a Word document.
If I have highlighted cell A2 and click on [BUTTON], I want Word to open automagically and type out something like
--"Hi Mike, your current amount is $12.37 and you live in 23 One Street. Thanks."--
The amount should be printed in bold, and after that Word should save the file and close itself without further input needed.
Similarly, when I have selected A3, it should open another document, write the same text but with Julia's variables filled in, save it to a specified location and close.
A B C
1 Name Address Amount
2 Mike 23 One Way $12.37
3 Julia 3949 Street $39.23
[BUTTON]
So essentially, I guess, I'm trying to "remote-control" Word from within Excel and feed some variables from Excel into Word. I am at a complete loss how to do that, to be honest.
What I have found so far is this:
Dim wdApp As Word.Application, wdDoc As Word.Document
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word isn't already running
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdDoc = wdApp.Documents.Open("C:\temp\[NAME AFTER SELECTED FIELD A2].docx")
wdApp.Visible = True
...
Now I don't know what to do!
How to pass the standard text with the variables from the row of the selected field over to Word?
How to format them (bold, Arial, red, etc.)?
How to save under the specified filename?
Is this even possible to do? I know VBA is very powerful, so I hope you can help me out!
I'm using Office 2013, so any caveats related to macro programming or VBA language should take that into account.
Thank you so much!
Don't use get/create object. My macros are all coded as follows:
dim wdApp as New Word.Application 'Always use a new instance
Set wdDoc = wdApp.Documents.Open("C:\temp\[NAME AFTER SELECTED FIELD A2].docx")
wdApp.visible = true
From there you simply work as you would in word. Passing variables is pretty simple as the datatypes exist on both sides (double, integer, string etc are all included in the standard VBA libraries that are included by default so no need to add references). So if I want to tell word to add a paragraph:
wdDoc.paragraphs.add
wdDoc.paragraphs(wdDoc.paragraphs.count).range.text = "Hello World!"
Want to add text from a specific range?
dim xlRange as Excel.Range
dim wdApp as New Word.Application 'Always use a new instance
Set wdDoc = wdApp.Documents.Open("C:\temp\[NAME AFTER SELECTED FIELD A2].docx")
wdApp.visible = true
set xlRange = activesheet.range("A1") 'Just as an example
wdDoc.paragraphs.add
wdDoc.paragraphs(wdDoc.paragraphs.count).range.text = xlRange.value
Finally, say you want to use a variable name form excel to open a specified word document:
dim name as string
name = selection.cells(1).value 'Assuming they selected the cell
dim wdApp as New Word.Application 'Always use a new instance
Set wdDoc = wdApp.Documents.Open("C:\temp\" & name & ".docx")
wdApp.visible = true
I know this is a year late, but hey, hope it helps.
As a final note:
Use exit sub just prior to end sub in the word macro. Exit sub returns to caller where as end sub does not.
sub test
'do the word stuff
exit sub 'Stop it short of end sub
end sub
You could do this but it would be quite difficult.
Much easier is to use your spreadsheet from Work.
In Word (2013) go to the Design ribbon, and use the Start Mail Merge wizard. The source of addresses will be your spreadsheet. I think this will be much easier than what you are planning.
Cheers -

Update linked fields in Word document from Excel VBA

I am trying to automatically update certain information (such as names, dates and numbers) across 3 different Word documents by putting the data into a spreadsheet and linking to the respective cells from Word. The spreadsheet has some Macros in it which auto-update parts of the spreadsheet internally.
Everything is working fine, except for updating the links in the Word documents.
When trying to update a link in Word by right-clicking on it and selecting the "update link" option it brings up the Macro warning dialog for the spreadsheet, asking whether I want to activate Macros or not. It doesn't do this just once but constantly during the 20s or so the update process takes (which seems unusually long to me). So updating the link works, but only if you're willing to click the "activate Macros" button of a few dozen times.
I tried to automate updating all fields in a document from Word with VBA, but that has the same problem, it also brings up the Macros dialog constantly for half a minute.
Here's my code for that:
Sub UpdateFields()
ActiveDocument.Fields.Update
End Sub
I also tried to update the Word documents directly from the spreadsheet, but that does not work either, because when Excel tries to open a Word document via VBA the program stops executing and trows this error:
"Excel is waiting for another application to complete an OLE action."
Clicking ok and waiting does not help because the error message reappears after a few seconds, and the only way to stop it is to manually kill the Excel process.
Here's my Excel Macro code:
Sub LoopThroughFiles()
Path = Application.ActiveWorkbook.Path
Dim WordFile As String
WordFile = Dir(Path & "\*.doc")
Do While Len(WordFile) > 0
Run Update(Path & "\" & WordFile)
WordFile = Dir
Loop
End Sub
Function Update(Filepath As String)
Dim WordDoc As Word.Document
Set WordApplication = CreateObject("Word.Application")
Set WordDoc = WordApplication.Documents.Open(Filepath) 'This produces the error
ActiveDocument.Fields.Update
End Function
Note that the only files in the folder are the 3 documents and the spreadsheet, and the program does find the files without any problems.
I have searched for solutions online but I did not really find anything, which I found odd, since it seems like a pretty common thing that someone would do with VBA.
Then again, I have very little experience with VBA, so I might be completely missing the point and there is a super simple solution I am just not aware of.
I think I see the error, which is a silent failure, becuase the document contains links, there is an open dialog waiting for you to say "yes" or "no" to update the links.
We can suppress this dialog by disabling the automatic link updates (WordApplication.Options.UpdateLinksAtOpen = False).
Function Update(Filepath As String)
Dim WordApplication As Word.Application
Dim WordDoc As Word.Document
Dim updateLinks As Boolean
Set WordApplication = CreateObject("Word.Application")
updateLinks = WordApplication.Options.UpdateLinksAtOpen 'capture the original value
WordApplication.Options.UpdateLinksAtOpen = False 'temporarily disable
Set WordDoc = WordApplication.Documents.Open(Filepath)
WordDoc.Fields.Update
'MsgBox "Links updated in " & WordDoc.Name
'## Save and Close the Document
WordDoc.Save
WordDoc.Close
'## reset the previous value and Quit the Word Application
WordApplication.Options.UpdateLinksAtOpen = updateLinks '
WordApplication.Quit
End Function
Also, remember to Save and Close the document, and Quit the word application inside the function.
I made this other modification:
In your function, ActiveDocument is not an object in Excel, so you would need to qualify it, otherwise that line will also throw an error. Rather than refer to WordApplication.ActiveDocument, I just simply refer to the WordDoc which you have already assigned.

User defined type not defined- controlling Word from Excel

I am trying to do some relatively simple copy and pasting from Excel 2007 into Word 2007. I've looked through this site and others, and keep getting hung up on the same thing- the third line n the code below keeps giving me the "User type note defined" error msg. I am really confused since I just lifted this from another solution (and had similar issues with other solutions I tried to lift). Could someone please educate me on what is causing the error, and why?
Sub ControlWord()
' **** The line below gives me the error ****
Dim appWD As Word.Application
' Create a new instance of Word & make it visible
Set appWD = CreateObject("Word.Application.12")
appWD.Visible = True
'Find the last row with data in the spreadsheet
FinalRow = Range("A9999").End(xlUp).Row
For i = 1 To FinalRow
' Copy the current row
Worksheets("Sheet1").Rows(i).Copy
' Tell Word to create a new document
appWD.Documents.Add
' Tell Word to paste the contents of the clipboard into the new document
appWD.Selection.Paste
' Save the new document with a sequential file name
appWD.ActiveDocument.SaveAs Filename:="File" & i
' Close this new word document
appWD.ActiveDocument.Close
Next i
' Close the Word application
appWD.Quit
End Sub
This answer was mentioned in a comment by Tim Williams.
In order to solve this problem, you have to add the Word object library reference to your project.
Inside the Visual Basic Editor, select Tools then References and scroll down the list until you see Microsoft Word 12.0 Object Library. Check that box and hit Ok.
From that moment, you should have the auto complete enabled when you type Word. to confirm the reference was properly set.
As per What are the differences between using the New keyword and calling CreateObject in Excel VBA?, either
use an untyped variable:
Dim appWD as Object
appWD = CreateObject("Word.Application")
or
Add a reference to Microsoft Word <version> Object Library into the VBA project via Tools->References..., then create a typed variable and initialize it with the VBA New operator:
Dim appWD as New Word.Application
or
Dim appWD as Word.Application
<...>
Set appWd = New Word.Application
CreateObject is equivalent to New here, it only introduces code redundancy
A typed variable will give you autocomplete.

Get the filename of open Excel workbook in Word VBA

Does anyone know how to get the filename of an open Excel wordbook using Word VBA, so that I can copy some information to my Word document?
This can get a lot more complicated depending on how sure you need to be, and whether it is for personal or public use:
Set objWithName = GetObject("C:\docs\testx.xls")
Set objClassOnly = GetObject("", "Excel.Application")
Debug.Print objWithName.Name
Debug.Print objClassOnly.Name
It is possible to have more than one instance of Excel running and each instance may have more than one workbook open, but get object will only return one instance. If you know the name of the file you want, it is a lot easier, because you can use the first version above.
If you know the application will be open and it’ll be the first (if only) instance open, using the following code. In Word, you’ll need to add Excel 12 reference (Tools| References, Microsoft Excel 12.0 Object Library).
Sub test()
Dim objClassOnly As Excel.Application
Set objClassOnly = GetObject(, "Excel.Application")
Debug.Print objClassOnly.Name
Debug.Print objClassOnly.ActiveWorkbook.Name
End Sub