Automatically Closing Outlook Windows via Script/Macro - vba

I'm hoping someone on here can point me in the right direction with some expertise. I have a situation with a client's outlook where we need to close any open draft windows after a new message/draft is opened. Ideally after the 4th new window has opened.
Any "new message" window that opens after this we need the script to close 1st window that opened. Either killing the process, or something similar.
Recently have been looking into Outlook macros, but am unsure if they will help in this instance. (Maybe they are?). Being more familiar with Powershell, figured we could start there.
Looking to get help writing a powershell script, macro, etc to do this on the backend.

The Outlook object model provides all the required events, methods and properties for that. So, VBA macros is the right choice if you don't need to distribute the solution on multiple machines. Otherwise, you need to consider developing a COM add-in instead (for example, a VSTO based one should work for you). See Walkthrough: Create your first VSTO Add-in for Outlook for more information.
You can handle the NewInspector event which is fired whenever a new inspector window is opened, either as a result of user action or through program code. The event occurs after the new Inspector object is created but before the inspector window appears.
You can also check the number of opened inspector windows in Outlook by using the Inspectors.Count property which returns a long indicating the count of objects in the specified collection.
Finally, the Inspector.Close method closes the Inspector and optionally saves changes to the displayed Outlook item. For example, a VBA sample which closes the active inspector instance:
Sub CloseItem()
Dim myinspector As Outlook.Inspector
Dim myItem As Outlook.MailItem
Set myinspector = Application.ActiveInspector
Set myItem = myinspector.CurrentItem
myItem.Close olSave
End Sub

Related

Slow opening of any email after set value for an object on Application_ItemLoad

Basically I am using below code to run macro after I manually open a specific email.
The code and macro works ,but I noticed there is a slowness while opening of any email on outlook.
After many tests, I find out this line is the cause of issue:
Set MyItem = Item
And this the full code:
Option Explicit
Option Compare Text
Public WithEvents MyItem As Outlook.MailItem
Private Sub Application_ItemLoad(ByVal Item As Object)
If Item.Class = olMail Then
Set MyItem = Item 'This line cause slow opening of any email
End If
End Sub
Private Sub myItem_Open(Cancel As Boolean)
If MyItem.Subject = "Test Email" Then
'Code
End If
End Sub
Kindly How to fix this issue?
Basically I am using below code to run macro after I manually open a specific email.
You may consider using other event handlers in Outlook - for selecting in the Explorer window you may try to handle the SelectionChange event of the Explorer class which is fired when the user selects a different or additional Microsoft Outlook item programmatically or by interacting with the user interface. For opening in the separate window you can handle the NewInspector event which is fired whenever a new inspector window is opened, either as a result of user action or through program code. The event occurs after the new Inspector object is created but before the inspector window appears. Also you may handle the Inspector.Activate event which is fired when an inspector becomes the active window, either as a result of user action or through program code.
If there is a specific reason to use the ItemLoad event handler in the code you may continue using the late-binding technology and keep the item defined as object.
Also don't forget to release corresponding objects in the Unload event of the Item-level events.

How to manage application options/advanced options?

I need to quickly toggle File > Options > Advanced > Reminders > Play reminder sound setting.
In certain meetings I need to keep Outlook running to get reminders, but don't want the reminder sound.
Currently, I manually toggle the File > Options > Advanced > Reminders > Play reminder sound checkmark.
This needs to be an effective single-click.
I don't want to restart Outlook as there are usually many things open.
I cannot add it to the Quick Access Toolbar.
On the left the option is present in the list of QAT commands, but not in the list of Ribbon commands, otherwise we could access it with ExecuteMso.
Three reasons:
The button is disabled when not in the Calendar window. That's just inelegant.
When I click the button, Outlook crashes and I lose everything that wasn't saved. (Autosave isn't sufficient or functioning. That's a different problem.)
Understanding how to access Outlook settings with VBA opens a whole new world of possibilities.
This Microsoft article series starting at https://learn.microsoft.com/en-us/office/vba/outlook/concepts/getting-started/automating-outlook-from-a-visual-basic-application is about automating Outlook user tasks, like making a calendar appointment. That's not what I want, I want to manage Outlook's options.
There are some discussions about COM add-ins as one method, but that appears beyond me. The effort to learn COM add-ins is out of line with manual effort to achieve the desired goal.
I have some limited Outlook VBA experience but am reasonably comfortable with VBA in Word, Excel.
To disable reminder sound you need to set the below registry key to 0.
Registry key: PlaySound (REG_DWORD) to be set to 0.
Path: HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\options\Reminder
where 16.0 indicates the Outlook version.
Don't forget to restart Outlook to apply changes.
These settings can be overridden on the per appointment basis - you can simply set AppointmentItem.ReminderPlaySound property to false using VBA.
Simulate a button press with ExecuteMso.
https://learn.microsoft.com/en-us/office/vba/api/Office.CommandBars.ExecuteMso
Hover over the button where you would add it to the ribbon/QAT. See text in brackets at the end.
Are the command codes for ExecuteMso documented?
Private Sub ExecuteMso_TextInBrackets()
' https://learn.microsoft.com/en-us/office/vba/api/Office.CommandBars.ExecuteMso
' https://stackoverflow.com/questions/25610998/are-the-command-codes-for-executemso-documented
Dim oAppt As Object
Set oAppt = ActiveInspector.CurrentItem
Debug.Print oAppt.subject
ActiveInspector.CommandBars.ExecuteMso ("TextInBrackets")
End Sub
As with most things in life, the answer is a workaround. In this case, it's AutoHotkey to press the keys for me (ALT F, T, down x 9, ALT P, Enter):
;WIN-O toggles the Outlook alarm sound setting
#o::
SetTitleMatchMode,2 ;inexact match
WinGetActiveTitle, MyWindowTitle
If WinActive(" - email#company.com") ;Poor way to "prove" we're in Outlook
{
;MsgBox, We're in Outlook
Send !ft{Down 9}
Send !p{Enter}
}
Return

outlook mailitem in explorer mode is old

I have an intermittent updating problem with an outlook mailitem in the explorer mode on a public folder of an exchange server. The subject (or perhaps any other part as well) of a mailitem does not seem to update itself at times.
Specifically, the subject of the mailitem shown in the explorer mode is dissimilar to that shown in the inspector mode. In other words, the explorer mode is old, therefore needs updating or synchronization.
Hitting F9 (send/receive) to update the public folder does not seem to help.
I would like to know if this anomaly can be detected (and perhaps perform manual updates/synchronization) using an outlook macro.
Any ideas are welcome.
Some properties, factors unknown, update on saving only.
The subject of the mail in the explorer view should change when you manually close the item, if you agree to save changes. Should be the same if you manually saved regularly.
If you want more than a simple save:
Option Explicit
Sub MarkInUseSaveCurrentItem()
Dim currItem As Object
Set currItem = ActiveInspector.currentItem
If InStr(LCase(currItem.subject), LCase("Barok is working on this")) = 0 Then
currItem.subject = "Barok is working on this. To avoid conflicts do not open. " & currItem.subject
End If
currItem.Save
End Sub

The RPC server is unavailable (outlook in vb.net)

I am developing little application. It's purpose is on button click generate some email and open outlook "new email" window with this template. I am using Outlook interop 14. On application start I create New Outlook.Application() instance. This creates outlook.exe process.
My method for generating and open email:
Private Sub GenerateEmail(...)
...
'this line throws RPC exception when no outlook.exe process exists
Dim OutlookEmail As Outlook.MailItem = CType(OutlApp.CreateItem(Outlook.OlItemType.olMailItem), Outlook.MailItem)
...
OutlookEmail.Display()
...
End Sub
When I run an application, outlook.exe process starts. I click generate email, outlook opens window BUT when I close this "new email" window it also terminates outlook.exe process. And this is problem becasue second time I want to generate an email I am getting an error "The RPC server is unavailable". The question is how to close the window but not terminate outlook process. Btw I am getting the same error also when I am try to second time create a new instance of Outlook.Application (after terminating a previous one).
Outlook quits (which can take some time) when its last visible window closes. To prevent that from happening, retrieve a MAPIFolder object (e.g. using Application.Session.GetDefaultFolderFolder(olFolderInbox)) and store the Explorer object returned by calling MAPIFolder.GetExplorer() in a global/class variable. The Explorer object does not have to be made visible.

Outlook MailItem cache issue when saving in vb.net

I have a small WinForms program that allows my users to create email blasts for our clients. The app has two options: one is an HTML editor to design the email (works great) and the second is to import .msg or .oft template.
Once the email is complete it is moved to a shared outlook mailing folder for a nightly macro send job.
Pretty simple stuff!
The problem: Once the template is open in the application outlook seems cache that version. If the user decided to get out make a change in the template Outlook doesn't pick up the update.
Note: If the users clicks on the "Preview" button they received the correct UPDATED version in their inbox. But when they submit the MailItem it picks up the old version.
Dim newItem as Outlook.MailItem = gobjOutlook.CreateItemFromTemplate(fileEmailTemplate.FileName)
The send command works fine newItem.Send()
But when I move it to the shared folder it gets the original version from somewhere.
Dim addFldr As Outlook.MAPIFolder
addFldr = StoreFLDR.Folders.Add(gobjNamespace.CurrentUser.Name & ": " & DateTime.Now.ToString())
newItem.Save()
newItem.Move(addFldr )
I have tried forcing the GC and SaveAs to another location and reload the template, no luck.
I'd suggest starting from releasing underlying COM objects instantly. Use System.Runtime.InteropServices.Marshal.ReleaseComObject to release an Outlook object when you have finished using it. Then set a variable to Nothing in Visual Basic (null in C#) to release the reference to the object.
You may find the How To: Create a new Outlook message based on a template article helpful. Anyway, it would be great to see your full source code related to Outlook.