Word VBA Application.Quit issue - vba

If (Documents.count = 1) And (ActiveDocument.Name = ThisDocument.Name) Then
Application.DisplayAlerts = False
Application.Quit (wdDoNotSaveChanges)
Else
Application.DisplayAlerts = False
ActiveDocument.Close (wdDoNotSaveChanges)
End If
I'm having issues with the above code, in that when the code clears that first If statement (meaning it is the only document open and the name of the document is as expected), it still won't close out of the Word Application completely. It instead will only close the document and then leave a "blank" Word window open.
I know it is clearing the first If statement because I wrote a quick check of each element to a debug file, and everything shows up as expected. Additionally, if I step through the code it indeed moves along as it should.
Interestingly/Frustratingly if I step through the code in debug mode and get to the section in the code for Application.Quit, it does indeed quit the entire program! So I'm really not sure why it doesn't work when I just run the code as opposed to stepping through it.
Have tried:
1 - Adding an 'Exit Sub' line after Application.Quit
2 - Setting the Word Application as an object explicitly:
Dim wObj As Object
Set wObj = CreateObject("word.Application")
'Application.Quit (wdDoNotSaveChanges) '
wObj.Quit (wdDoNotSaveChanges)
Set wObj = Nothing
3 - Adding a before close event:
Sub DocumentBeforeClose()
ActiveDocument.Saved = True
End Sub
Any help would be much appreciated!

When having this issue in Excel, I found I had to tell Excel to close all documents after calling Application.Quit.
Because Excel can retain a reference to any workbook after the workbook's window closes (workbook still present in VBA Editor, unreleased object references)…
Because I can't always know that my document is the first document that has been opened by this instance of Excel…
Because I must accept the presence of an Excel add-in that can cause workbooks to appear modified immediately after a save (due to changes to invisible worbook properties)…
Because my usecase requires Excel to quit…
Adapted for Microsoft Word:
'Actual handling of unsaved documents omitted from this answer
If savedAllDocuments Or UserDoesNotCare Then
Application.Quit wdDoNotSaveChanges
Dim doc As Document
For Each doc in Application.Documents
doc.Close SaveChanges:=False
Next doc
End If

I had a simular issue with Application.Quit (quitting Word from within an Excel macro). It turned out, that it was related to the status of Application.ScreenUpdating.
The macro hung when in Excel ScreenUpdating was set to false, but continued correctly with:
Application.ScreenUpdating = True

Related

compile error: end sub expected on ActiveDocument.Close after .VBComponents("thisDocument").CodeModule.AddFromFile

Even after looking through all of similar phrased questions and several search engine results I did not find any answer.
I copy the current word document and change the codebase by removing former modules and rewrite the ThisDocument-component by adding from file. For the context, but most probably skippable:
Public Sub DOCMPublish()
'...msoFileDialogSaveAs...and then...'
Application.Documents.Add ThisDocument.FullName
On Error Resume Next
' unlink fields and finalize content to avoid updates within the archived documents
Dim oFld As field
For Each oFld In ActiveDocument.Fields
oFld.Unlink
Next
' rewrite macros and unload modules
On Error Resume Next
Dim Element As Object
For Each Element In ActiveDocument.VBProject.VBComponents
ActiveDocument.VBProject.VBComponents.Remove Element
Next
rewriteMain ActiveDocument, "ThisDocument", ThisDocument.path & "\Document_Public_DOCM.vba"
' protect content
ActiveDocument.Protect wdAllowOnlyFormFields, Password:="LoremIpsum"
' msoFileDialogSaveAs does not support filetypes, hence forcing extension
DOCMFile = fileSaveName.SelectedItems(1)
DOCMFile = Replace(DOCMFile, ".doc", ".docm")
DOCMFile = Replace(DOCMFile, ".docmx", ".docm")
' the next line saves the copy to your location and name
ActiveDocument.SaveAs2 filename:=DOCMFile, FileFormat:=wdFormatXMLDocumentMacroEnabled
' next line closes the copy leaving you with the original document
ActiveDocument.Close
End Sub
This sub worked properly for that over the last years:
Sub rewriteMain(ByRef Workument, ByVal Module, ByVal Source)
'delete code from ThisDocument/ThisWorkbook
Workument.VBProject.VBComponents.Item(1).CodeModule.DeleteLines 1, Workument.VBProject.VBComponents.Item(1).CodeModule.CountOfLines
'rewrite from file
With Workument.VBProject
.VBComponents(Module).CodeModule.AddFromFile Source
End With
'delete module
Workument.VBProject.VBComponents.Remove Workument.VBProject.VBComponents("Rewrite")
End Sub
The content of Document_Public_DOCM.vba to be imported is
Option Explicit
Private Sub Document_Close()
ThisDocument.Saved = True
End Sub
Private Sub Document_ContentControlOnExit(ByVal ContentControl As ContentControl, Cancel As Boolean)
Dim cc As ContentControl
For Each cc In ThisDocument.ContentControls
'checkboxes have no type attribute to check against, therefore the need of _
error handling on checked-property that is checkbox-only in this usecase
On Error Resume Next
ThisDocument.Bookmarks("text" & cc.Tag).Range.Font.Hidden = Not cc.Checked
ThisDocument.Bookmarks("notext" & cc.Tag).Range.Font.Hidden = cc.Checked
Next
End Sub
I can see no problem here, and the modified and saved file doesn't complain later on. But in the meantime i get the compiling error on closing the ActiveDocument after the import and ActiveDocument.SaveAs2. I get no error without closing the file though, but this is not nice for the work environment, messing up the screen.
Often word crashes, sometimes it just results in a state loss. I also tried encoding as utf-8 and iso 8859-1, disabled screen updating but that does not seem to be the solution as well. What am I missing?
Edit:
What I tried further without success:
disabling syntax checking in the editor
On Error Resume Next
Err.Clear
newDoc.EnableEvents = False (after implementing #Алексей-Р suggestion)
excluding deletion of .VBProject.VBComponents names "ThisDocument"
Also explicitly compiling the modified files code expectedly does not raise any errors. Are there any editor settings I am unaware of?
I try to answer it myself, at least this solved the issue in this case:
I open the file with
Set newDOC = Documents.Add(ThisDocument.FullName, True, wdNewBlankDocument, False)
I can only assume that opening the file in a new blank document and not displaying it might prevent the code executing and therefore having issues being replaced at runtime.
Edit:
it worked at first, then it didn't. Still don't know why. The following now seems to be failproof:
Set newDOC = Documents.Add("", True, wdNewBlankDocument, False)
ThisDocument.Content.Copy
dim rng
Set rng = newDoc.Content
rng.Collapse Direction:=wdCollapseEnd
rng.Paste
'clear clipboard, otherwise an annoying msg popy up everytime because huge content is left there from copying
Dim clscb As New DataObject 'object to use the clipboard
clscb.SetText text:=Empty
clscb.PutInClipboard 'put void into clipboard
This solution opens a new blank document and copypasts the content without having macros in the first place. Afterwards I proceed to rewrite the modules as in the initial snippet from the question
Not sure why it worked for #АлексейР with my provided code though. Thanks for caring anyway!

Check if Clipboard Open

I have used the code Application.ShowClipboard to open the clipboard on opening Word. However, this code also closes the clipboard if it is already open.
Therefore, I need to know how to check if the clipboard is already open to know whether to execute the code.
If Clipboard is open
Then Application.ShowClipboard
Else
Any ideas?
All you really need is:
Application.CommandBars("Office Clipboard").Visible = True
It seems the Clipboard is part of the Applciation.Commandbars collection.
Check to see if Application.CommandBars("ClipBoard").Visible = False and then ShowClipboard else, do nothing.
Note: This was tested on Word in Office 365.
Sub CheckForClipboard()
If Application.CommandBars("Office Clipboard").Visible = False Then
Application.ShowClipboard
Else
'Do nothing
End If
End Sub

Reset formfields corrupts Word document

I have a large, dynamic Word macro with lots of formfields on it. It takes a long time to run, and by far the most time consuming part is clearing all the formfields before mapping them. Right now I'm looping through them and setting them individually = "". I found a quicker way to do it, but it always corrupts the document.
1) Current:
For Each fld In doc.FormFields
If fld.Type = wdFieldFormTextInput And fld.Result <> "" Then
fld.Result = ""
ElseIf fld.Type = wdFieldFormCheckBox Then
fld.CheckBox.Value = False
End If
Next
2) Tried:
ActiveDocument.ResetFormFields
and 3)
Unload Me
in a command button click event
1) Takes at least a minute every time
2) is almost instant but corrupts the document (error saying "Word has encountered a problem. You will not be able to undo this action...")
3) Throws an error- "361: Can't load or unload this object"
I either want 2) to work, or to find any faster way to clear the formfields.
Thanks for your time.
Referring to (2): this is not so much an error message as a warning, and there's no document corruption. Word always loses the Undo list when a document is unprotected, which is what happens behind the scenes with this method.
Two approaches occur to me. One would be to disable alerts, which should suppress the warning. The other would be to emulate the user action of unprotecting, then re-protecting without saving the current form field entries.
To suppress the warning (this won't affect true error messages):
Application.DisplayAlerts = wdAlertsNone
To unprotect then reprotect the document without saving user input:
Sub UnprotectReprotectToResetFields()
Dim doc As Word.Document
Set doc = ActiveDocument
If doc.ProtectionType <> wdNoProtection Then
doc.Unprotect
End If
doc.Protect wdAllowOnlyFormFields, False
End Sub

VBA Excel: Application.DisplayAlerts not working if called from another macro

I've got a macro opening another workbook that can be readonly. To avoid readonly alerts I switch Application.DisplayAlerts propery to False, like this
Sub tmp()
Application.DisplayAlerts = False
Debug.Print Application.DisplayAlerts
Workbooks.Open "\\Co-file01\FileName.xlsx"
End Sub
And it works fine, but if I call it from another macro, like this
Sub tmp1()
Application.Run "tmp"
End Sub
I still get the alert, and the code stops working, waiting for response. The line
Debug.Print Application.DisplayAlerts
returns False, so it seems the property is really switched, but for some reason it does'not apply.
Can anyone explain the reasons it works this way and suggest any workaround?
I'm working with Excel 2016 64bit, Windows 7 if matters
jkpieterse suggested the answer
You should call the macro directly by its name: simply type tmp1 on a
new line, rather than using application.run

excel macro calling another excel macro in vba

I have made a macro that calls another macro saved on my shared drive. I have taken the help from the suggestions given in the previous question I asked. It is working on the files that are on my local drive, but as soon as I open it from a file from the shared drive it stops working.
The macro name is mymacro.xla
These are the codes:
Dim i As AddIn
Set i = Application.AddIns.Add("M:\nit\USER\nitin kumar\NQK\macro\run1.2.xla", True)
i.Installed = True
I have created a button whose codes is given below:
Dim CoBa As CommandBar
Dim Ctlconst As CommandBarControl
On Error Resume Next
Set CoBa = Application.CommandBars.Add(Name:="Quote Daily Report", temporary:=True)
With CoBa
Set Ctlconst = .Controls.Add(Type:=msoControlButton)
With Ctlconst
.Caption = "Lexington Macro"
.Style = msoButtonIconAndCaptionBelow
.OnAction = "Accounts_Summary"
.FaceId = 483
.TooltipText = "NITIN"
End With
.Visible = True
.Position = msoBarBottom
End With
It's not working any suggestions would be of great help.
The least effort solution would be to copy the XLA locally before adding it.
The root cause could be one a number of things, locking, a read-only folder or security restrictions. It's better not to mess about with that and also that gets you around a bunch of potential problems such as:- what happens if you update the xla while someone is using it?