Document_open macro in Word isn't triggered until VBA-code is changed (insignificantly) - vba

I have a .docm file with a Document_Open-sub, which calls another sub to open a small userform - or it's supposed to trigger and open - but it doesn't...
If I make changes to the document and save it - it still doesn't work.
If I make insignificant changes to the VBA-code in the same document (like adding a space character outside a sub) and save it - it suddenly works.
Why does it not work all the time? - and what can I change to make it work?
Additional info (I have no idea if some of it might be relevant)
In most cases the document is downloaded from an internal website and saved locally.
The document we've tested with is saved locally in a location which is trusted in Word.
In cases - where the sub isn't triggered automatically - the sub can be run with ALT+F8 (but that's not what I want).
The functionality works for some user - and not for others.
The functionality in the Document_Open-sub depends on a value read in CustomDocumentProperties.
System: Win10 - Word MSO365 build 2110
Edit - code added:
Public Sub Subrutine1()
ThisDocument.CustomDocumentProperties("prop1").Value = " " 'resetting prop1
UserForm1.Show 'prop1 is set from the userform
End Sub
Private Sub Document_Open()
If ThisDocument.CustomDocumentProperties("prop1").Value = " " Then
Call Subrutine1
End If
End Sub

You could rename your Sub "Subrutine1" to "AutoOpen."
I would recommend the following code.
Private Sub AutoOpen()
Dim myForm As UserForm1
Set myForm = New UserForm1
myForm.Show
Unload myForm
Set myForm = Nothing
End Sub
I would suggest resetting the document property as part of your userform initialization unless you sometimes use it without resetting that.
I would suggest using a document variable rather than a document property.
I suspect you would be better served with a document template rather than a document. In that case, the macro would be named "AutoNew."

Related

Make a copy of the printed Word document and save it in a folder

I need a to create a macro on my Word which would save the printed document automatically to another location on my computer. I have looked through hundreds of options online and here also but couldn't exactly what I was looking for. Saving it to another location is easy but it should make a copy only when the the document is in the print queue. Can anyone help me out here? Need it for my employee monitoring.
Use the Application.DocumentBeforePrint event which is triggered everytime before the opened document is printed.
The following code needs to be placed in a class module, and an instance of the class must be correctly initialized.
Option Explicit
Public WithEvents App as Word.Application
Private Sub App_DocumentBeforePrint(ByVal Doc As Document, ByRef Cancel As Boolean)
Doc.SaveAs2 FileName:="your path"
End Sub
Code 1: Put this code into a class module called "EventClassModule".
According to Using events with the Application object you need to register the event handler before it will work.
Option Explicit
Dim ThisWordApp As New EventClassModule
Public Sub RegisterEventHandler()
Set ThisWordApp.App = Word.Application
End Sub
Code 2: Put this code into a normal module (not a class module).
The event DocumentBeforePrint will work after you registered the event handler by running RegisterEventHandler, this is recommended to run whenever the document is opened. Therefore we use the Document.Open event in ThisDocument:
Option Explicit
Private Sub Document_Open()
RegisterEventHandler
End Sub
Code 3: Put this code into "ThisDocument".
Then save, close and re-open your document. If you print it now, the event DocumentBeforePrint will execute right before printing.
Edit according comment:
Image 1: Make sure your class module is named correctly.

How to ask for confirmation before allowing a Word document to close?

I work with 2 different keyboard layouts (qwerty and azerty), and am constantly switching between the two using Alt-Shift. Sometimes when I reach for Ctrl-Z to undo, I get instead Ctrl-W which closes the document. Generally speaking I would in these situations get a Save Prompt, which would alert me to my mistake. However, I am now using OneDrive, with Autosave on the documents I'm working on. As a result, there is never this save prompt. The document is instantly closed and, worse, the undo that I was trying to effect is no longer present when the document is re-opened.
I would like to use VBA attached to the Normal Template, such that, on closing any document created with the VBA template, I will check to see if Autosave is turned on, and if it is, confirm before closing with a messagebox.
Obviously if the user doesn't confirm (e.g. chooses Cancel) then the document should not be closed.
Initially I put my code on Document_Close, but soon realised that here it's too late to Cancel the close. This is no good to me.
Then, based on some online code, I put my code in a class module (EventClassModule). In the ThisDocument module, I initiate the class, and activate the event handler.
My code doesn't ever seem to run, or in anycase, breakpoints don't kick in.
I'm a little unsure of where Normal stops and my normal document begins...
In ThisDocument of Normal Template, I have this VBA
Dim X As New EventClassModule
Sub Register_Event_Handler()
Set X.App = Word.Application
End Sub
Private Sub Document_Open()
Register_Event_Handler
End Sub
And I have a class module called EventClassModule with the following
Public WithEvents App As Word.Application
Private Sub App_DocumentBeforeClose(ByVal Doc As Document, Cancel As Boolean)
Dim res As VbMsgBoxResult
If Me.AutoSaveOn Then
res = MsgBox("OK to Confirm", vbOKCancel, "Closing Document")
If res = vbCancel Then
Cancel = True
End If
End If
End Sub
I would like a prompt to confirm saving, any time a document is closed and the autosave option is turned off.
The Document_Open event handler will only fire if the Normal template is opened via File | Open. To get code to respond when starting Word you need to use an AutoExec routine. Simply rename your routine as below. You can find further info on Auto macros here
Public Sub AutoExec()
Register_Event_Handler
End Sub
Here is an easy way, include a method like this:
Public Sub DocClose()
' Disables Ctrl + W (but not other close methods, e.g. Alt + F4, menus, [X])
' Your code here:
ActiveDocument.Close
End Sub
Basically there are some method names that are used internally by MS-Word, and if you include them in your code they will prevent the default action. If you leave the sub empty it will effectively disable Ctrl + W.
See here for more information: Reserved method names in MS Word VBA
Advantage 1 of this technique
If you use Public WithEvents App As Word.Application and your project gets reset for any reason, and fails to restart... App will be Nothing and none of the events will fire.
Advantage 2 of this technique
On the occasions that you actually want to close a document... with this technique you wont get bugged by a (soon to become) annoying confirmation message - just sayin ;-)

Word Userform Hotkey

I currently use word templates in my business to help create customer mailings. There's a existing userform coding on our templates that insert the proper return address, phone number, legal entity, etc... onto the letter. Lately we've been having issues with a subset of users (seemingly random, we've been through exhaustive testing and cant find rhyme/reason) who do not receive the popup to choose whatever items they need when they enable macros. In testing we've found that the users have been able to go into vbasic and run the userform manually. I'd like to build in a hotkey option to initialize the userform, please help! Currently, the ThisDocument object has this code to run the userform:
Private Sub Document_New()
Channel_Select.Show
End Sub
From what I've been able to find online, something like the OnKey Command from excel could be used, but I cant find the Word version. Does anyone have experience in this?
I found the answer on a thread about keybinding, but I can't refind that thread. I added 2 new modules to my document, module1 has:
Option Explicit
Sub AddKeyBinding()
With Application
' \\ Do customization in THIS document
.CustomizationContext = ThisDocument
' \\ Add keybinding to this document Shorcut: Alt+r
.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyR), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="TestKeybinding"
End With
End Sub
Module 2
Option Explicit
' \\ Test sub for keybinding
Sub TestKeybinding()
Channel_Select.Show
End Sub
Run the AddKeyBinding macro, then alt+r will launch the userform on the document

How to set the View at Word startup using VBA

I want to set the ActiveDocument.ActiveWindow.ActivePane.View properties for the blank document MS Word displays on startup. At the Application.Initialise event there is no active document, and the Document_New event doesn't occur. Does anyone know how to address that first document or otherwise get a hold on it?
You can get it using the DocumentChange event. You will need to set a flag to indicate that you are at startup before you initialise your event handler so that it only responds the once.
Private Sub AppWord_DocumentChange()
If Documents.Count > 0 Then
If InStartup Then
InStartup = False
If Left(ActiveDocument.AttachedTemplate, 10) = "Normal.dot" Then
ActiveDocument.ActiveWindow.ActivePane.View = wdNormalView
End If
End If
End If
End Sub
Edit:
My guess is that you have added your code into Normal.dotm. If that is the case it would explain why you can't trap the events at startup.
The default blank document that Word creates is based on Normal.dotm. As a result any code it contains only gets loaded after that document has been created, ergo after the events have fired. This makes Normal.dotm a very poor host for an event handler. Personally I avoid using Normal.dotm for anything other than sketching out code for answers to questions!
A better home for code in Word is its equivalent of the add-ins that can be created for Excel and PowerPoint, a template that is loaded at startup. This is placed in the folder defined in Word as the Startup folder (File | Options | Advanced | General | File Locations). By default it is %APPDATA%\Microsoft\Word\STARTUP for Windows. Place the template containing your code in that folder and it will be loaded before the blank document gets created and will enable you to respond to the events.
This is the solution I implemented.
Private Sub App_DocumentChange()
' 27 May 2017
Static Done As Boolean
If Not Done Then
On Error Resume Next
If ActiveDocument.Path = "" Then SetView ActiveDocument
Done = True
End If
End Sub

Document_Open() event does not fire on every computer

I have a Word which is used for form filling. The users are filling what is asked and some macros runs depending on what they chose or where they click. This works fine.
I recently decided to make a newer version which countains some ComboBox that are filled when the document is opened. To do that, I used the Document_Open() event.
Now here is the part I don't get : On my side, every time I do open the document, the event is triggered and the ComboBox that should get filled are filled. The problem is, so far I asked some people to test it on their own computer with their Word. Both of them came back to me saying that the ComboBox weren't filled when the document was openned.
To be more specific let's go in the code itself :
In ThisDocument, I have multiple subs that works perfectly fine and this Document_Open() event which gives me trouble.
Private Sub Document_Open()
Application.Run ("Fill.ComboBox")
End Sub
Here, Fill is the name of the Module which contains :
Sub ComboBox()
'Calling another Sub in this Module which adds the Items in the ComboBoxes
'from what parameters it is given
End Sub
Now that this has been stated, why would it work on my side but not work when another user tries it from their computer ?
Miscorsoft Word Versions :
I myself use Microsoft Office Profesionnal 2013 and so are the two users that tested it. That being said, this is intended to be working on any Word liscense from 2007 up to the current versions.
You can try in a module in your document:
Public Sub AutoOpen()
ComboBox
End Sub
I just used this in a Word 2016 document to automagically run a macro.
For documentation: https://support.microsoft.com/en-us/help/286310/description-of-behaviors-of-autoexec-and-autoopen-macros-in-word