Check to see if word document is open before opening - vba

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.

Related

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"

MS Word does not unlink fields for one document but does for another

I have some VBA code (In Excel) that will open a Word document, break the links, and save that Word document elsewhere.
All automated and transport to the user, all they will see is a file appear in a folder.
My problem is it works for the below:
Private Sub Button1_Click()
Dim objWord As Object
Dim docWord As Object
Const wdDoNotSaveChanges As Long = 0
Set objWord = CreateObject("Word.Application")
Set docWord = objWord.Documents.Open(ThisWorkbook.Path & "\A folder\Myfile.doc")
objWord.ActiveDocument.Fields.Unlink
objWord.ActiveDocument.SaveAs ThisWorkbook.Path & "\" + Cells(1, 7) + "myfile.doc"
objWord.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
objWord.Quit
End Sub
but not for the below which is supposed to perform the same function on a different Word document:
Private Sub Button2_Click()
Dim objWord As Object
Dim docWord As Object
Const wdDoNotSaveChanges As Long = 0
Set objWord = CreateObject("Word.Application")
Set docWord = objWord.Documents.Open(ThisWorkbook.Path & "\A Folder\Myfile2.doc")
objWord.ActiveDocument.Fields.Unlink
objWord.ActiveDocument.SaveAs ThisWorkbook.Path & "\" + Cells(1, 7) + "MyFile2.doc"
objWord.ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
objWord.Quit
End Sub
When I open the first document generated (outcome of the first code), it doesn't ask me to update the links and the links are broken, as intended.
When I open the second document generated (Outcome of the second code), it asks me to update the links.
EDIT:
Both sections of code above have been merged and put into a single sub that has variables forwarded to it - Still same outcome of one document updating and unlinking as intended, the other document asking the user on opening if they want to update links.
So now most likely a problem with the Word documents.
Both Word documents are linked to Excel via Paste Special > Paste Link.
Both only linked to the one Excel document.
The only difference I can see is one document has quite a few more links than the other, but surely quantity of links shouldn't matter?
Upon further investigation, the problem is confined to the header of the document. My code will unlink all fields in the body of the document, but will not do this for the header. As a result, the header remains linked and it asks the user if they would like to update.
I eventually found my solution here:
VBA Excel - Unlink headers & footers in Word

Close/Release Word object in 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

Opening word doc from VBA

I have a subroutine in MS Access that opens a specific word doc file. The gist of the code is
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim filepath as String
'Open Word
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
filepath = CurrentProject.Path & "\Prospect Profiles\Account Profile Form.doc"
'Open the file
Set wrdDoc = wrdApp.Documents.Open(filepath)
So here's the kicker - The subroutine works for all but one of our employees. We're all on the same Citrix environment, and we all have the same version of Access and Word. For this user, the subroutine does not give an error - it smiply opens a blank instance of ms word but it never opens the word doc file. What gives?
Aha! It turns out that this user had made a copy of an older version of our database front end and he wasn't accessing our current, updated version. Thanks for all the help y'all!