How to script Outlok text editor using Visual Basic? - vba

I want to perform some text replacements that are just too complicated for Automatic replacement feature of Microsoft outlook. Microsoft has rather extensive documentation on Microsoft Outlook VBA scripting hosted on GitHub.
I started by pressing Alt+F11 which opened Visual Basic Editor. This is what I see in the project explorer:
Please note that I am not VBA programmer, so what I did afterwards probably looks stupid. I figured out that OutlookOutlook namespace represents all Outlook classes, so I just picked one of the classes that sounds like a text field:
Dim WithEvents textField As Outlook.OlkTextBox
And I created a dummy event that should fire before change in text field:
Private Sub textField_BeforeUpdate(Cancel As Boolean)
MsgBox "Nope!"
Cancel = True
End Sub
Of course, when start outlook and edit message, the script doesn't get executed. So I suppose that for starter, I need to get a refference to actual text editor. How do I do that?
My question basically is, how to get this code execute when I try to edit any outlook message:
MsgBox "Nope!"
Cancel = True

Try the write event.
Private WithEvents myItem As MailItem
Private Sub Application_Startup()
Set myItem = ActiveInspector.CurrentItem
End Sub
Private Sub myItem_Write(Cancel As Boolean)
MsgBox "Nope!"
Cancel = True
End Sub

Related

How can I catch the Print option being selected in the File menu/tab in Word 2016 (backstage view)?

The following code opens the screen I want to detect being opened:
Sub Test()
Application.CommandBars.ExecuteMso ("PrintPreviewAndPrint")
End Sub
It does not seem to activate a CommandBarButton object I can create an event handler for. Any thoughts on how to do this without having to change the structure of the File Tab because this is only relevant for one document. The goal is to be able to set duplex printing before the document is printed while the standard File->Print option can still be used.
You can go old school. Before there were events to trap it was common to intercept commands simply by creating a routine with the same name.
For example:
Public Sub PrintPreviewAndPrint()
MsgBox "Hello!"
End Sub
Alternatively, you can trap the DocumentBeforePrint event, though this will only fire after the dialog has been executed.
There is no way to repurpose backstage UI controls, but you can create your own UI instead. So, a better solution would be to consider hiding the built-in UI and rebuilding it fully with custom commands. The Introduction to the Office 2010 Backstage View for Developers article explains the basics of building a custom backstage UI.
The Application.DocumentBeforePrint event allows canceling the default action, so you can programmatically print the document in the way you want by using the PrintOut method.
Public WithEvents appWord as Word.Application
Private Sub appWord_DocumentBeforePrint _
(ByVal Doc As Document, _
Cancel As Boolean)
Dim intResponse As Integer
intResponse = MsgBox("Have you checked the " _
& "printer for letterhead?", _
vbYesNo)
If intResponse = vbNo Then Cancel = True
End Sub

Stop save capability in a word doc

I’m wondering if there is a way to block the “save as” function (I.e. being able to change the name) of a word doc through VBA. The user should only be able to save as if they’ve filled in certain mandatory fields. I’m not sure if this is even possible as I have really found nothing on the topic.
A decent answer on how to subscribe to events can be found in this question: How to run a macro in Word before save?
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)
Cancel = True
MsgBox ("Cancelled")
End Sub
This will run after you open the document

How to detect if user tried to click on save/save as option or pressed ctrl-S in Microsoft word using VBA code?

I want to detect when user press ctrl-S or click on Save option of Microsoft word using VBA excel macro code.
I found related links about Save changes while closing and Detecting if a document is getting close but I not able to find some example code for detecting saving of word document.
Any help would greatly appreciated.
Thanks
Unfortunately (or fortunately) Word does not work like excel and there the keybinding follows different logic. Thus, in Word, you should try something like this, to bind Ctrl + S. The idea is that on openning of the file you tell the application to bind Ctrl + S to the SaveMe Sub.
Option Explicit
Private Sub Document_Open()
With Application
.CustomizationContext = ThisDocument
.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeyS), KeyCategory:=wdKeyCategoryCommand, Command:="SaveMe"
End With
End Sub
Public Sub SaveMe()
MsgBox "User Saved"
End Sub
Put the code in ThisDocument:
Until now, it works this way only for Ctrl+S. If you go for the Save through the menu, it will not follow this logic. This is what you should do then:
For the general solution, follow these instructions:
I. Create a clsWord and put the following code inside:
Option Explicit
Public WithEvents appWord As Word.Application
Private Sub appWord_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
Call SaveMe
End Sub
II. Change the code in ThisDocument to this:
Option Explicit
Dim myWord As New clsWord
Private Sub Document_Open()
With Application
.CustomizationContext = ThisDocument
.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeyS), _
KeyCategory:=wdKeyCategoryCommand, Command:="SaveMe"
End With
Set myWord.appWord = Word.Application
End Sub
III. In a module:
Option Explicit
Public Sub SaveMe()
MsgBox "User Saved"
End Sub
Parts of the ideas are taken from the MSDN here - https://msdn.microsoft.com/en-us/library/office/ff838299.aspx But the code there was not complete :)

How to call the quit/close event in outlook 2007 VBA

The question is simple, yet hard to achieve for me for some reason. How can I get to fire the quit/close event when outlook 2007 is being closed?
I want do display a Yes/No msgbox in VBA which executes code depending on the option chosen when outlook is being closed.
I thought I had the solution using:
Dim WithEvents myOlApp As Outlook.Application
Sub Initialize_handler()
Set myOlApp = CreateObject("Outlook.application")
End Sub
Private Sub myOlApp_Quit()
MsgBox "TEST"
End Sub
First I tried to insert it into my Module but this gave me the Only valid in object modules error. So then I created a new class module and pasted the code in here (which gave no errors) but still the event wont fire. What is going wrong and how to fix it?
Set myOlApp = CreateObject("Outlook.application")
There is no need to create a new Outlook instance. You should use the Application property availble in Outlook VBA.
Private Sub Application_Quit()
MsgBox "Goodbye, " & Application.GetNamespace("MAPI").CurrentUser
End Sub
Take a look at the Getting Started with VBA in Outlook 2010 article in MSDN.

Document_New event on launching Word

I have a VBA addin which I want to run every time someone opens a document. It's working fine for opening existing documents (AutoOpen) and creating new documents from the File > New menu (AutoNew) but when I just open Word up for the first time, neither of these events are firing. The only event I can seem to hook into is the AutoExec event and this is not great as the document doesn't exist yet so ActiveWindow is null.
Can anyone help?
Sub AutoNew
MsgBox "New"
End Sub
Sub AutoOpen
MsgBox "Open"
End Sub
Sub AutoExec
MsgBox "Exec"
End Sub
I would start with DocumentOpen and NewDocument. An additional level of complexity exists if you need to support ProtectedView documents; Word triggers a different event. I've found that if I try to check for that event (and it doesn't occur) it raises an error. I didn't had much luck and eventually it wasn't worth the time I was spending. I've posted an example below of some code that opens the Style Pane when a document is opened or a new one created (assuming the add-in is loading) and expands the style margin in draft view if not already expanded.
In my UI module:
Dim X As New clsAppEvent 'This is in the declarations
Public Sub OnRibbonLoad(objRibbon As IRibbonUI)
Do While Documents.Count = 0
DoEvents
Loop ' I find this useful as sometimes it seems my ribbon loads before the document.
Call Register_Event_Handler
' Other stuff
End Sub
Private Sub Register_Event_Handler()
Set X.App = Word.Application
End Sub
Then, in a class module I call clsAppEvent:
Option Explicit
Public WithEvents App As Word.Application
Private Sub App_DocumentOpen(ByVal Doc As Document)
App.TaskPanes(wdTaskPaneFormatting).visible = True
End Sub
Private Sub App_NewDocument(ByVal Doc As Document)
App.TaskPanes(wdTaskPaneFormatting).visible = True
End Sub
Private Sub App_WindowActivate(ByVal Doc As Document, ByVal Wn As Window)
If Wn.StyleAreaWidth <= 0 Then
Wn.StyleAreaWidth = 60
End If
End Sub
Other than the caveats I've noted above, the one problem I've had is if a user has Auto code in their Normal template as well. This has only come up once so I haven't investigated it.
I wish I could find the site where I learned about this (and from which the Register_Event_Handler was derived. If I find it I'll add a comment.