Outlook 2007 - VBA macro in NormalEmail.dotm - vba

I have a Word 2007 template that I use as Normal.dotm, which has corporate theme, styles, etc., plus a tiny bit of macro code that overrides the default behaviour of the bullet & number buttons on the ribbon.
I'd now like to use this same template when creating emails in Outlook 2007. I've tried just copying my Normal.dotm to NormalEmail.dotm, and to an extent this works, but although my macro is correctly invoked when I press the bullet/number buttons in the email editor, it gives an error:
Run time error 429: ActiveX component can't create object
On further investigation, it seems that anything I do within my macro that references an object in the normal Word object model (Application, Selection, etc.) causes this error. So, even if my macro consists of the following, it still fails:
MsgBox TypeName(Application)
I have an inkling that this is because I'm running in the context of Outlook, not Word, and so perhaps there is no (Word) application, or any of the objects associated with it. I know that the email editor in Outlook is Word-but-not-as-we-know-it-Jim.
Having said that, I did discover that ThisDocument does return a valid Document object; unfortunately, it corresponds to the template itself, not the email being edited.
By trial and error, I've discovered that I can get at the Document corresponding to the email by the following circuitous route (this displays the text in the email):
MsgBox ThisDocument.MailEnvelope.Item.Application.ActiveInspector.WordEditor.Content.Text
However, this code also seems to cause Outlook to crash - not at the time, but later, when you close Outlook.
At this point, I'm just about ready to admit defeat. No doubt the "correct" way to create macros in Outlook is to create them in Outlook itself, but from my limited experience, that's just horrible. (You can create macros in VBA, but you can't deploy them; or, you can create them in VSTO, but then you need an installer rather than simply deploying a template).
So. Any ideas out there that would let me do all that I hoped to do?
Override the behaviour of the bullet/number buttons on the ribbon in the email editor.
Deploy the macros in the NormalEmail.dotm file, rather than having to "install" them.
Not crash Outlook.

Have you tried adding the reference in the VBA editor to the Microsoft Outlook Object Library?

In Outlook 2007 you might also have to add VBA references to "Microsoft Word 12.0 Object Library" and maybe "Microsoft Forms 2.0 Object Library". Different versions may apply for other version years.
In addition, in the macro/code you have to set the objects to get/use the correct methods and properties.
I'm not an OO programmer and usually copy code from elsewhere and modify for my need so I can't help much more than what I said above. (And one of my macros is also giving me the same 429 error you get.)

Related

Running functions from Excel Add-Ins in vba, is there an easier way than using Run "mySub"?

I'm trying to create my first Excel Add-In for Excel 2010. Most of it is working, it's running from the ribbon buttons, but I'm having trouble addressing the Add-In's subroutines from my workbook's VBA code.
According to this answer on SO, it should be possible to simply use the syntax:
mySub
or
Call mySub
But this causes the error "Sub or Function not defined". I've only managed to run them this way:
Run "mySub"
or
Application.Run("myAddIn.xlam!mySub")
Is there a way to include the Add-In so I can address it the easy way?
The Add-In is already checked in the Tools->Add-Ins list, and has a unique name (CalcFunctions) which is different from its file name (CalculationFunctions.xlam). The Add-In file is on a different disk and I'm working on a server, but I don't expect that that matters.
(Posted on behalf of the OP).
Turns out I'm just dumb. I only set a reference to the Add-In in the regular Excel window. I assumed that was what people meant by Tools->References->Add-Ins (I use Excel in Dutch and there's no "Tools" menu). Anyway, the solution was setting a reference in that menu in the VBA editor window.
Here's how to add a reference in VBA:
ThisWorkbook.VBProject.References.AddFromFile refPath
With refPath being the full path to the file.
To be able to add references you need to have permission to edit the VBA project. You can enable this in excel settings->trust center->macro settings. If you're on a company pc it's likely the administrator has to set these settings for you.

How to call a VBA-macro in another MS Word document?

in MS Excel I have been distributing a xls-file that contains a macro. From the users "random" current open workbook I have successfully been calling this macro by telling Word in which file to look for it. Like this, when the user clicks a button on the ribbon:
C:\\"'MyExcelFileWithTheMacro.xls'!MyMacroName"
Can I do the same in MS Word?
That is, to call a macro in a Word-file located in any given folder from an instance of Word that has not opened that file?
I have tried, of course, but Word keeps saying it can't find the macro.
The reason I want to do it this way is that it is makes for easy distribution and updating of the macro. Next up is signing the macro. I hope it can be done when doing things this way, but not sure.
No, it's not possible to call and run a macro in any Office application if the file that contains the macro is not loaded in the application interface.
That being said, if you place the macro in a *.dotm template and have the user put the template in the STARTUP folder used by the Word application, then Word will load the template as an "Add-in". And in that case you should be able to access the macro.
Or, if you don't want it in the Startup folder and you have code that automates the Word.Application, anyway, then that code can load the *.dotm as an "Addin", which should make the macro available (and remove it when you're done with it). Research Application.Addins.Load and Addin.Installed in the Word language reference as well as on-line for examples.

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.

Standalone code for Excel

Can VBA code be written to perform actions on any Excel file?
When I create a project in Visual Studio, it asks for an Excel file to be linked to it. All the code that I write is in ThisWorkbook.vb and hence acts only on the Excel file linked to the project.
Ideally, I want a script that:
When the user double-clicks, he/she should be allowed to select an Excel file of choice for the actions to be performed on that file.
If the above is not possible, I'd at least like to invoke the VBA script from within an Excel file.
Basically, the VBA code should be independent of any Excel file.
I looked at VBScript, but the syntax for it seems to differ slightly.
You've mentioned Visual Studio, VBA, and VBScript. The solution I'm outlining works directly with VBA rather than Visual Studio or VBScript. (However, you might adapt Visual Studio (C# or VB) along the lines of what I'm outlining below.) Hope it's helpful, so here goes:
Here's what I do, and, it ultimately results in an .xlam Excel AddIn as #chris above has commented.
Overview
I start with ordinary .xslx workbook, to which I add a VBA project, making it an .xlsm. Then create some VBA Subs (macros). Then create some Excel QAT (Quick Access Toolbar) buttons for the workbook, which are bound to (i.e. they invoke) the VBA subs/macros. Then convert the workbook (with VBA in it) to an .xlam, which is an Excel AddIn. When you're all done, the buttons are accessible from any workbook (and the VBA code has access to any user workbooks as well as those originally in your .xlsm). Further, the workbook associated with the .xlam is invisible. So it just looks like you've added some buttons to the QAT that appear on all users .xlsx windows. The .xlam is pretty easy for users to install (though I provide a buttons to uninstall/reinstall/check version). You can upgrade an .xlam independently of users' workbooks; users' workbooks can thus be data only (.xlsx, no VBA).
Details
Write some Excel Subs you want to use later
You need to be aware that the buttons can only invoke macros (VBA Subs) without parameters, so the macros will have to check things like ActiveSheet and ActiveWorkbook and Selection to figure on what sheet the button was pressed, hence what user data to really operate on. (If you need to refer to your workbook with the VBA code in it, use “ThisWorkbook”). You should be aware that there can be naming conflicts, so try to name the parameterless subs with rather long names, such as MySomewhatUniqueProjectName_button1, etc…
Add Buttons to your .xlsm
Using Excel 2010 (I think this works with 2007 or later), I put workbook-specific buttons on the QAT part of the ribbon, which connect to macros (VBA subs) in the VBA code.
To do this, you from the Quick Access Toolbar customization drop down (the tiny down arrow at the very top row of the Excel window, the last icon from left to right) choose "More Commands…". When the “Customize Quick Access Toolbar” dialog box comes up, from the (2nd) "Customize Quick Access Toolbar:" heading (top to the right), choose "For XYZ.xlsm" from the dropdown instead of the "For all documents (default)". And from under "Choose Commands From:", use "Macros" (instead of “Popular Commands”) from the dropdown. Once you have those two things selected, you can move VBA subs from the left box to the right box using “Add >>”. Each so moved will become buttons visible in your QAT. As you’re doing this you can also edit the icon and text for the buttons, add a separator as needed (I always end with a separator in case other .xlam’s use the QAT). (Now is a good time to save this .xlsm.)
Convert the .xlsm into a .xlam
Then I convert the .xlsm to an Excel add-in, by merely saving it as an .xlam file. This will end up (1) hiding the workbook associated with the code you have (though it is still accessible to itself.). Further, now, (2) the (invisible, as now it's an .xlam) workbook will load whenever Excel is loaded. (To keep this fast for when users use Excel but don’t run my VBA code, I don't run any code when the .xlam is loaded, I only run code when a button is pushed.)
You can manage the AddIn using Excel’s AddIn manager. To update the AddIn, you have to use some trickery. While you can copy over it when Excel is not running, on the other hand, you cannot directly uninstall the AddIn, you can only disable it from Excel. But once disabled, you can delete the .xlam, and relaunch Excel, go to the AddIn manager to try to work with the (now gone) AddIn and you’ll get Excel saying it can’t find it, so do you want to delete it. Say yes, and it will be uninstalled.
FYI, Notes
I keep the .xlsm to edit later, but you can actually debug and edit the .xlam and later convert it back to an .xlsm with a minor bit of trickery: find its "ThisWorkbook" entry in VBA, and then the "IsAddIn" property, set to false, its workbook will suddenly appear and you can save as .xlsm, or edit its workbook and set the property back to true to resave as .xlam directly.)
Answer 1
You can do that in VB.Net too. Just make a regular project. (comment by #SLaks)
This worked for me very well and was exactly what I was looking for.
Answer 2
The very descriptive answer posted by #ErikEidt
I haven't tried this, but it seems like a good and alternative way of getting macros to work.

How to determine if 'SaveChanges:=wdDoNotSaveChanges' was passed to Interop.Word.Document.Close()

I have an issue with an Office addin I'm working on, which is implemented for Office 2003 & 2007. The addin is written in VB.NET 3.5 using VSTO.
The problem comes from some external code which automates a mail merge, opening the mail merge template, merging and then closing the template document. The close is done with this code:
objWord.Documents(sDoco).Close SaveChanges:=wdDoNotSaveChanges, OriginalFormat:=wdPromptUser
Because of some logic in my addin, instigated from the Interop.Word.Application.DocumentBeforeClose event, a message box is opened which prevents the Office document from closing, which breaks the automation.
Is there a way for me to determine the SaveChanges parameter (if any) on a Close within an Office.Interop.Word.Application event, such as DocumentBeforeClose? I'm trying to capture this parameter and determine if it's set to wdDoNotSaveChanges so that I can work around this problem.
I'm pretty sure you get the DocumentSave event BEFORE the DocumentBeforeClose, so set a flag in it, and if that flag is set at close, you know the doc has been saved, but if not, it was not. I've had to do similar things to know whether a Document was SAVED-AS vs just SAVED.
I'm not aware of any way to interrogate the state of that parameter from DocumentBeforeClose.