1
votes

I have a VBA code in word document. The code runs each time the user clicks on save. The code works fine when the document type is Word Macro-Enabled Document but when I convert the document to Word Macro-Enabled Template the code stop working, any advise on how to fix this? Note: code is in the document itself

Private WithEvents App As Word.Application
Private Sub Document_Open()
Set App = Word.Application
End Sub
Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
do stuff....
1

1 Answers

1
votes

Your class is initialised when the docm document is opened. After converting to dotm it is still the opening of the document which triggers the On_Open event, meaning you have to open the template. Of course, the whole point of having a template is that you don't want to open it. Therefore the App class never gets initialised and therefore the App events never fire. You may like to initialise the App class on the New event.

Having said this, I suspect that your code is still working as it should but you may have been testing the wrong way. When you create a new document the App class will not be initialised and nothing will happen when you save the new document. However, after you close the new document and then open it again the On_Open event will fire and the App events will fire after that. As I said, if you initialise the App class both On_New and On_Open it should do as you wish when you wish.