![]() |
|
|
|
#1
|
||||
|
||||
|
Are you running this code from Word or from some other application such as Excel? You have used an application.ontime version from Word VBA, but also used Set wdApp = GetObject(, "Word.Application") which suggests another application. This is unnecessary when you are already working in Word. If you are running the code in Excel, you need to change the line to Code:
Application.OnTime EarliestTime:=Now + TimeValue("00:00:30"), Procedure:="CloseDoc"
Code:
Sub CloseDoc()
Dim oDoc As Object
Dim wdApp As Object
Set wdApp = GetObject(, "Word.Application")
For Each oDoc In wdApp.Documents
If LCase(oDoc.Name) = "file.docm" Then
oDoc.Close -1
Exit For
End If
Next oDoc
End Sub
If you are running the code from Word (not the document with the code) then you only need Code:
Sub CloseDoc()
Dim oDoc As Word.Document
For Each oDoc In Documents
If LCase(oDoc.Name) = "file.docm" Then
oDoc.Close -1
Exit For
End If
Next oDoc
End Sub
__________________
Graham Mayor - MS MVP (Word) (2002-2019) Visit my web site for more programming tips and ready made processes www.gmayor.com |
|
#2
|
|||
|
|||
|
Hi,
first thank you guys for replying to my post. Yes Im runnig the code from Word. I tried: Sub CloseADoc() Dim aDoc As Document For Each aDoc In Application.Documents Debug.Print aDoc.Name If aDoc.Name = "Document2" And ActiveWindow.Document.Name <> "Document2" Then aDoc.Close SaveChanges:=False Exit For End If Next aDoc End Sub This works only when the document is the document in foreground. When i debug the proper document/documentname is saved in aDoc. I also tried this: Sub CloseDoc() Dim oDoc As Word.Document For Each oDoc In Documents If LCase(oDoc.Name) = "file.docm" Then oDoc.Close -1 Exit For End If Next oDoc End Sub Same as with the first code. Only works if document is in foreground / has focus. I additionally tried: Documents("C:\Path\to\file.docm").Close SaveChanges:=wdDoNotSaveChanges Same as above. Cant find anything that would close the document if two (or more) documents are opened und the doc i want to close is somewhere in the background / has not focus. Greetings fops Edit: I forgot to say its only related to Word. When i open the document and unfocus with e.g. win-explorer everything works like it should. Only with two or more word documents/windows it cant be closed when its unfocused or another document is the active one. |
|
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| How to dectect if close document and now no document open | skarden | Word VBA | 2 | 10-24-2022 07:03 AM |
Close Document Without Saving Prompt
|
Joe528 | Word | 3 | 10-08-2021 06:12 PM |
| Document close if/then/else error | eduzs | Word VBA | 1 | 01-02-2021 05:56 AM |
| Save and Close powerpoint if it is inactive | MetteGaga | PowerPoint | 0 | 04-16-2015 05:14 AM |
| Prompt when close the document | ubns | Word | 15 | 04-29-2012 10:07 PM |