Load macros from dotm - vba

The scenario:
When word starts, it connects via vba to a Service, which returns a list of paths. Each of These paths points to a .dotm file. These files contain information about various controls (inside the ribbon, for example a butto which adds a specific footer).
What I want: I need a possibility to load several .dotm files, but without copying or moving them to a specific location.
Basically that's it. I've searched wide and far and I have the fear, that this Approach is actually not possible, and that I have to copy all dotm files inside the startup-folder and let word do the rest
Is there any way how I can load several dotm files into a single word-file, so that the ribbon gets extended depending on the dotm's
Best regards, please and thanks :)

From word documentation:
This example attaches the template "Letter.dot" to the active document.
ActiveDocument.AttachedTemplate = "C:\Templates\Letter.dot"
You can use this to attach all your templates to the document.
See also the Templates collection.
you can add a template to the Templates collection by using the Add method with the Addins collection to load a global template
Sub AddTemplate()
' For this example to work correctly, verify that the
' path is correct and the file exists.
AddIns.Add FileName:="C:\Program Files\Microsoft Office" _
& "\Templates\Letters & Faxes\MyFax.dot", Install:=True
End Sub

It's not possible to load multiple templates to a single Word file. Only one template can be attached to a document.
It is possible to load multiple templates as add-ins in the Word environment. These will be available then to all documents opened in the Word application. Use the Addins-Add method to add a template to the list in Document/Document Template, the "Global templates and add-ins" list. (This is the equivalent of the "Add" button in the dialog box.)
Dim bInstalled as Boolean
Dim Path as String
Dim fileName as String
'Populate the variables, then...
Application.Addins.Add Filename:=Path & fileName, Install:=bInstalled
Set bInstalled to false if you want the template in the list, but not loaded (Ribbon isn't displayed, for example); set it to true to also load it. Once a template is in the list, whether loaded or unloaded, it will generally remain in the list unless Word is reset in some manner. The code for managing template add-ins would be more efficient if it first checks whether an Add-in is already in the list before adding it again.
Templates that are in the list can be loaded/unloaded using the Addins.Installed property. If the tools in a template should be available only to certain documents then they can be loaded/unloaded dynamically by using events, such as DocumentChange.
The code to load the add-ins and manage them (events) should probably be in a central template in Word's Startup folder or in the template attached directly to the document.

Related

Prevent Word macro in Normal.dotm for some templates

I have a Normal.dotm file that contains an AutoNew macro.
This macro is automatically executed each time a new document is created using any other template.
Is there any way I can prevent this automatic behavior for a specific template?
I have a Word VSTO add-in running, so I can hook into Word's events, but so far I havn't found a way to prevent this.
I do know that I can prevent macro execution when using templates programmatically, for example like this:
' Disable auto-macros before opening document
wordApplication.WordBasic.DisableAutoMacros(1)
' Open document
newWordDocument = wordApplication.Documents.Open(template.FullName, ConfirmConversions:=False, [ReadOnly]:=True, AddToRecentFiles:=False, Revert:=True)
' Re-enable auto-macros
wordApplication.WordBasic.DisableAutoMacros(0)
But this solution doesn't work when the user uses a Word template from Windows explorer or the Open-dialog in Word, since in those cases I can't execute code before it's too late already.
Or can I?
I hope someone has a trick for me :-)
-
Edit: While trying different solutions, I discovered something that might help others in similar situations, though unfortunately it doesn't help me.
It seems that if a template contains a module containing an AutoNew (or AutoOpen for that matter), that local macro is executed instead of the one in Normal.dotm.
Example:
Normal.dotm contains the following macro:
Sub AutoNew()
MsgBox "Normal.dotm"
End Sub
Test.dotm contains the following macro:
Sub AutoNew()
MsgBox "Test.dotm"
End Sub
When executing Test.dotm the message "Test.dotm" is displayed, while the message "Normal.dotm" is not displayed.
If the AutoNew macro is removed from the Test.dotm template, the message "Normal.dotm" is indeed displayed.
So it is possible to easily override the auto-macros.
The local versions of AutoNew and AutoOpen can even be empty subs that do nothing. It still works.
This is not possible in my case though, since the template I use is generated by code, and cannot contain macros (because adding macros to templates programmatically requires the user to manually activate the option "Trust access to the VBA project object model", and that's something I cannot ask my customers to do for all users. It's also a security risk.)
Based on the workaround described in the "Edit" part of the question - providing a template with "empty" Auto-macros - it's possible to use the Open XML SDK to create a template and add the VBA project to it in order to provide this functionality. This approach avoids the user needing to allow access to the VBA project on his installation. The only "macro security" that could be triggered is that for not allowing macros to run. But since the client uses macros, anyway, this should not be a major obstacle.
The simplest method is to create as much of the basic template as possible in the Word UI and use this as a starting point.
Since you're unfamiliar with the Open XML SDK, the next step would be to create one (or more) templates in the Word UI using the basic template as the starting point, saving under a different file name.
You can then use Open XML SDK Productivity Tool to see the code required to generate any one of these files, as well as, using the Compare tool, the code for converting the basic template to the derived version. This should give you a decent start with the SDK and it's object model. Once you get a feel for how the Open XML SDK works, if you're familiar with Word's object model, using that provided by the SDK is relatively straight-forward as an effort was made to make it correspond as closely as possible to the "COM" object model.
The VBA project can be added later, but you can also include it in the basic template. That would be the simplest approach.
Include this "starting point" basic template as part of your solution, installing it as part of the solution.
Within the AutoNew macro you can check the AttachedTemplate property. Only if it is a template where you want to apply the cleaning you can execute the respective macros.
Sub AutoNew()
If ActiveDocument.AttachedTemplate <> "Normal.dotm" Then
Exit Sub
End If
' rest of the macro
End Sub
If you don't control the Normal.dotm you can put an empty AutoNew macro in your own templates. As Word only executes the auto macro in the closest context, the macro in the Normal.dotm file would not be executed.
If you don't control the other templates either, you can tell your users to hold down the SHIFT key while creating a document. This prevents the execution of the auto macro.
Probably it is best, however, if you ask the owner of the other system to find another solution that does not rely on polluting the Normal.dotm file.

No Access to Template's Document

I have an existing Macro Enabled Template which I would like to add Content Control to, to be available on the screen when the Template is accessed.
I know how to add the Content to a Word Document and then save it as a Template. The problem is that I cannot view the Exisiting Template's Word Document due to the view Object being greyed out. See below:
I really do not want to copy all my Macros and my quick texts over to a new document just to add one line of text and a button.
I can easily add the required text and CommandButton by having a script run in a Document_New Sub under the ThisDocument. The problem is that this Sub bombs out due to Macros not being enabled. I intend to have the Template distributed to numerous colleagues, therefore having the Text and button on the document will avoid any confusion as to what to do with the template.
You need to open the Template via File - Open
Opening the Template this way will display give you access to the Template.
For info: The name of the Template will appear in the Center of the Word Application.

Centralized VBA code for multiple Word files

I have multiple files with the same VBA code in them, which will most likely have to be changed over time. I don't want to go one by one and c/p the code, so one obvious idea that came to mind is to have one centralized document with the code (template?) that all files refer to.
I found a few topics here at stackoverflow, but none of them work for me or are inconclusive:
Run external vba-code in MS Word
Centralized VBA code (one file) for multiple workbooks
Calling an External VBA from VBScript
Any ideas?
Yes, your idea of centralizing the code in a template and attaching that template to the various Word docs will work. These pics are using Word 2007 but I think it's pretty similar for newer versions. First create a new document and put the code in a Module (named "CommonFunctions" in the picture):
Save the doc as a macro-enabled template:
Now make a new document, save it as a *.docm (necessary for it to run code because a *.docx is macro-free), and attach the document template as shown below. (An alternative is to put the *.dotm file in the startup directory C:\Users\<username>\AppData\Roaming\Microsoft\Word\STARTUP, which loads it automatically.) If you don't put it in the Startup, you'll see the name but it won't be loaded (ie, checked), but you can load it in code, as I'll show.
Make a user form in this document:
Put this code for the button's click event:
If AddIns("c:\_b\MasterDocWithFunctions.dotm").Installed = False Then
AddIns("c:\_b\MasterDocWithFunctions.dotm").Installed = True
End If
Application.Run "CommonFunctions.Test1"
Application.Run "CommonFunctions.Test2"
Notice how the code can load the AddIn for you, because it won't be automatically loaded unless you put it in the Startup directory. This pic shows how the AddIn is referenced but not loaded. You need the checkbox to be able to call code in it. If you don't load it using code and don't put it in the Startup, then the user will have to manually put a checkmark everytime the document opens.
Now the form should work when you click the button. Notice how it can call both public and private functions. The Private keyword definitely shields one module from another, but it seems like modules that are called from an AddIn are considered to be part of the same module, not sure why? Also if you don't put Public or Private at all then VBA considers it Public, I'm pretty sure.

Using Word automation, is it possible to find out if the active document contains VBA code?

Using Word Automation, I want to save the active document programmatically. In Office 2007/2010, the document needs to be saved explicitly as "macro enabled" to preserve any VBA code in that document.
Rather than asking the user to choose, I would like my application to be able to determine if there is VBA code in the active document. Is that possible?
Yes this can be determined via the HasVBProject property. For example:
If ActiveDocument.HasVBProject = True Then
'Code to save as .dotm
Else
'Code to save as .dotx
End If
For those who might stumble upon this post later, it is worth noting that this code should be placed outside the document being tested for the presence of macros (otherwise it would detect itself). Two often-used options would be to access the code from an external application or from a template stored in Word's Startup folder.

Documents.Add results in template being locked

I have a macro that creates a new document based on a template stored on a network share. This macro is stored in each user's Word\STARTUP folder as the file "macros.dotm" and is executed by a button added to a toolbar.
The template file gets locked as soon as the macro code is executed and stays locked so long as the derivative document is still open by another user.
It has no impact on their ability to open new documents based on the macro, but if I want to edit the template, I have to ask them to close Word (and hope nobody else goes into it).
Macro code:
Documents.Add Template:="F:\templates\letterhead.dotm", NewTemplate:=False, DocumentType:=0`
One way around this is detaching the document from the template after it is generated:
Dim doc As Document
Set doc = Documents.Add(Template:="F:\templates\letterhead.dotm", NewTemplate:=False, DocumentType:=0)
Set doc.AttachedTemplate = Nothing
Alternatively, change the filesystem permissions on the template so only you have write access.
The issue is that the template is on a network drive - this is a pretty common issue. One way to get around it is to have your calling template copy over that template locally first and then create a new doc based off of that (and then delete the template when done).