Close/Release Word object in VBA? - vba

I have the following code to open the manual for an Excel Workbook application I have developed:
Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
End Sub
This gives me 2 issues though:
The document opens, but in the background. The user doesn't know the document has opened unless they know to check Microsoft Word in the Taskbar.
When I try to close the word document I receive:
This file is in use by another application or user. (C:\Users\Me\AppData...\Normal.dotm)
When I click ok on that dialogue, I receive a "Save As" screen.
If I cancel out of that and try to close the blank Microsoft Word instance I then get:
Changes have been made that affect the global template, Normal. Do you want to save those changes?
Then if I click No, everything finally closes.
Can anyone help me out with these 2 issues? Do I need to release the object somehow? Have never seen this before.
EDIT:
After trying #Layman-Coders method:
Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
'Open an existing Word Document from Excel
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
' Should open as the forefront
objWord.Activate
'Change the directory path and file name to the location
'of the document you want to open from Excel
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
objWord.Quit
Set objWord = Nothing
End Sub
When I have one other word document open and click the button, the following occurs:
Manual opens in the forefront, but I immediately receive This file is in use by another application or user. (C:\Users\Me\AppData\...\Normal.dotm)
I press OK and receive the Save As dialogue.
Cancel out of the Save As dialogue and am presented my Manual document.
When I click the Red X to close the document, I receive Changes have been made that affect the global template, Normal. Do you want to save those change? I click No and the document closes.
If this document is the first instance of word I have opening:
The document opens.
As soon as code hits the objWord.Quit line the document immediately closes.
I am just wanting the document to open to the forefront allowing users to view the Manual for assistance when they need it, and let them close the document at their discretion.

So the problem you are having with Word asking you to save the global template is because there is already a copy Word open which has rights to the Normal template. When you use CreateObject to set your Word object you are loading up Word a second time which opens Normal template as read only.
What you need to do is check if Word is open or not and if it is grab that copy of Word. If it's not then you can open up Word.
Sub OpenManual()
Dim objWord As Object
'We need to continue through errors since if Word isn't
'open the GetObject line will give an error
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
'We've tried to get Word but if it's nothing then it isn't open
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
End If
'It's good practice to reset error warnings
On Error GoTo 0
'Open your document and ensure its visible and activate after openning
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
objWord.Visible = True
objWord.Activate
Set objWord = Nothing
End Sub
One other nice line of code is to surpress display alerts. This will stop the 'do you want to save' type dialog boxes from appearing.
objWord.DisplayAlerts = 0

Try something like this:
Sub OpenManual()
'Word.Application.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Activate 'Should make it the forefront (1)
objWord.Documents.Open "\\filePath\FormFlow To MSExcel\FeedSampleReport-Manual.docx"
'If you just want to close it afterwards...
objWord.Quit 'Changes are discarded
'Either way, you should have the following somewhere
Set objWord = Nothing
End Sub
Setting the object to nothing should eliminate the connection

I had the same problem. And only code below closed this Word window:
Dim X As Variant
X = Shell("powershell.exe kill -processname winword", 1)
I found this code in one of the answers Closing word application from excel vba

Related

Simple Outlook macro to convert selected text to 'code'

I'm trying to create a macro in Outlook to allow me to select text and convert that text to 'code' (Courier New, black). I'm using Outlook for Microsoft 365 which (I think) uses the Word editor...
I've copied some code I found in another answer and tweaked it, but no dice, and I fear I'm missing something obvious.
Public Sub FormatSelectedText()
Dim objItem As Object
Dim objInsp As Outlook.Inspector
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objSel As Word.Selection
On Error Resume Next
Set objItem = Application.ActiveInspector.CurrentItem
If Not objItem Is Nothing Then
If objItem.Class = olMail Then
Set objInsp = objItem.GetInspector
If objInsp.EditorType = olEditorWord Then
Set objDoc = objInsp.WordEditor
Set objWord = objDoc.Application
Set objSel = objWord.Selection
With objSel
.Font.Name = "Courier New"
.Font.Color = RGB(0, 0, 0)
End With
End If
End If
End If
End Sub
I'm not a VBA guy, so it's likely something obvious :) I'm not even sure if it's a problem with the code or with the general macro support.
FWIW, in the past I wrote a separate VBA script to throw a warning message when I send an email to multiple people with different email domains (to avoid accidental data cross-sharing) which works fine, so I know a little bit...
To be clearer, I have added this code into a macro within the ThisOutlookSession object
I then open a new email and add some random text, select some of the text and run the macro, but the text in the email body doesn't change.
The code works correctly. You just need to add a COM reference to the Word object model to be able to use the Word object model in Outlook VBA macros.
In VBA editor window, click the “Tools” button in the menu bar.
Then, from the drop down list, select the “References” option.
The “References – Project 1” dialog box will display.
In this dialog box, you can pull the scrolling bar down until you locate what you need, in your case it is “Microsoft Word 16.0 Object Library”.
Mark the checkbox in front of the required entry and click “OK”.
Now you have added the Word object library reference successfully.

Referencing already opened word document in VBA

I am using Excel VBA to open a word Template and it populates the template with information from an excel spreadsheet. From there, I have a button on the spreadsheet that I want to then populate another line in the word document whenever it is clicked. The problem I am encountering is that when I run the button macro it just opens up another word document and pastes the button information instead of doing it on the already opened document. I will attach my code below and I believe it is an easy fix I just can't seem to find a way around it.
Sub RepairCal()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Open("C:\Users\z003narc\Documents\Gage Lab Form Template.docm")
objWord.Activate
With Selection
objWord.ActiveDocument.Selection.MoveDown count:=6
objWord.ActiveDocument.Selection.MoveRight count:=5
objWord.ActiveDocument.Selection.TypeText Text:="Repair and Calibration"
End With
End Sub
Try this:
With objWord
.Selection.MoveDown count:=6
.Selection.MoveRight count:=5
.Selection.TypeText Text:="Repair and Calibration"
End With
Are you saying you already have the document open when you run this every time? The way you wrote the code, it will do this:
1) Open new blank Microsoft Word process
2) In the new process, opens the workbook you have chosen
3) Makes the new process the active window
4) does stuff
If you want it to attach to the file you already have open, you would need to do GetObject instead of CreateObject. So change:
Set objWord = CreateObject("Word.Application")
To
Set objWord = GetObject(, "Word.Application")
This will attach to the currently open process, then open the workbook in that process. However, it will still open up a fresh copy of that document each time, because that's what you're telling it to do.

VBA - Opening word document to export data from excel to word doc

I have a little bit of an issue that i can't solve.
I have programmed VBA code to export cell data from excel into word textboxes.
How it works:
I have a button in the excel doc you highlight the row you want to work with you press the button it than grabs the data from all the cells i have told it to and imports them into word.
The problem i am having that is if I select another row and press the button again it tries to open that same word doc again and errors as it is already open. Is there anyway i can do and if statement to check to see if its open if its not open it and if it is use the active word doc?
here is my current code
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\swhiston\Desktop\IT Services Invoice.docx"
Thanks
GreatSc0tt
You want the Word object to by declared at Module/Class level and test whether or not it's already open before you open it
Option Explicit
Dim objWord As Object
Dim objDoc as Object
Sub OpenWord()
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
set objDoc = objWord.Documents.Open( "C:\Users\swhiston\Desktop\IT Services Invoice.docx")
End Sub
Sub MyCodeHere()
'Open Word If It's Not Already Open
If objwork Is Nothing Then OpenWord
'Your Code Here
End Sub
whenever you try to execute your code it will reopen the same file so either apply a condition that checks if file is open or not and if not then only it opens the file or every time you should close the file at the end of your code.
you can refer: Detect whether Excel workbook is already open
keep this in else part:
objWord.Documents.Open "C:\Users\swhiston\Desktop\IT Services Invoice.docx"

Check to see if word document is open before opening

I have a basic macro that opens up a word document, which works just fine. However if the document is already open then a new 'read-only' version is loaded. Is there a way to check if the document is already open, and if so switch to it rather than open a new copy.
Sub Open_Word_Document()
Dim objWord As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open Filename:=ThisWorkbook.Path & "\template.docx"
End Sub
EDIT:
This has been edited to suggest this question is already answered, but as the comments state the suggested question is referring to a different MS Application.

Word vba document.readonly status incorrectly returns false

I have an excel project that checks word documents for a changed modify date and, if changed, it opens that document and imports the text from the word form fields into excel.
The routine in excel that opens and imports the word documents is as follows:
Sub CopyFromWord(pFile as String,aFile as string)
Dim wdApp As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
Else 'word is already running
End If
On Error Goto 0
Set wdDoc = wdApp.Documents.Open(Filename:="" & pFile & "", ReadOnly:=True)
wdApp.Visible = False
For Each c In wdDoc.bookmarks
'removed code that copies values from word doc fields to excel sheet
Next c
wdApp.Activedocument.Close SaveChanges:=False
End Sub
The word documents all started out as copies of the same file. There are a few thousand copies of the file, but each located in their own folder with a unique name.
The user finds the folder they need and opens the word document within it. It bring up a userform and then populates formfields in the document with the input to the userform. A command button then saves and exits the form.
Because the welcome message/userform loads automatically upon the document opening, I added the following code into the open event for the document:
Sub Document_Open()
If ThisDocument.ReadOnly = True then Exit Sub
msgbox "Welcome " & Environ$("Username") & ". Click OK to begin."
Userform1.show
End sub
This ensures when the excel project loops through all the files, if it finds one has changed, it needs to open the file (read only) so it can import the data without being interrupted with a userform / welcome message, close it, and carry on searching looping all files checking for changed modify-dates.
It should run constantly, however, about 20% of the time, a document will be opened read only by the excel code, but the welcome messagebox in the word document will show, indicating thisdocument.readonly incorrectly returned false.
If I debug the word document in this scenario, and do
? thisdocument.readonly
I get a "false" result. However, even the title bar of the word document ends with " (Read-Only)" so it has clearly been opened read-only, thus readonly should return True.
It is not specific to any documents, if I try to repeat opening them it seems to work the next time round (in that it correctly registers a read-only and exits the sub before the messagebox code). I cant find any kind of pattern and can't find any info online, I've been searching this for weeks!
May not be considered the answer, but following Tim William's suggestion, I managed to put together this which completely solves my problem. I struggled at first because I was trying to set the property too early. Complete code is as follows:
Sub CopyFromWord(pFile as String)
Dim wdApp As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
Else 'word is already running
End If
On Error Goto 0
'save current setting
secAutomation = wrdApp.Application.AutomationSecurity
'set Word to disable macros when a document is opened via vb:
wrdApp.Application.AutomationSecurity = msoAutomationSecurityForceDisable
'(without using wrdApp prefix it would only apply to the code's App i.e. Excel)
Set wdDoc = wdApp.Documents.Open(Filename:="" & pFile & "", ReadOnly:=True)
wdApp.Visible = False
For Each c In wdDoc.bookmarks
'removed code that copies values from word doc fields to excel sheet
Next c
'restore original setting before closing
wrdApp.Application.AutomationSecurity = secAutomation
wdApp.Activedocument.Close SaveChanges:=False
End Sub
Many thanks to Tim Williams for the link, and the guy who provided the code within the content of that link. This was such a help and is most appreciated.