1

I created a custom folder on outlook with name “MyTemplate” and inside that folder an email message with subject Auto Plan ( It is a template email with oft extension) ,
and inside that email an excel workbook.
For automation purpose, I need after I open that email message, then a copy of the attached workbook will be opened automatically.
I found the below code, But I cannot utilize it to fulfil my need.
Notes: for testing purpose I set outlook and excel macro security settings to “Enable all macros”.
That is my own email meassge (I fully trust) ,I also added the a personal digital certificate to the workbook and ThisOutlookSession. I am using outlook 2016 32Bit with Windows 10 64Bit.
As always, grateful for any assistance.

Public WithEvents myItem As Outlook.MailItem
Public EventsDisable as Boolean
 
Private Sub Application_ItemLoad(ByVal Item As Object)
    If EventsDisable = True Then Exit Sub
    If Item.Class = olMail Then
        Set myItem = Item
    End If
End Sub
 
Private Sub myItem_Open(Cancel As Boolean)
    EventsDisable=True
   'Your code
    EventsDisable=False
End Sub
Waleed
  • 847
  • 1
  • 4
  • 18
  • Would this be an excellent way to get a virus? – Solar Mike Apr 15 '22 at 08:13
  • I very seldom use Outlook automation, but sometimes consider a related to Outlook question being challenging... This one looks to be of this type. From what I experimented, `ItemLoad` event is very restricted in terms of using the (mail) object properties/methods. That's why `Open` event has been 'invented'. I think, what you try is possible. But I do not think you will like the event to be triggered for all mail conversations having the template subject. So, it is necessary to differentiate somehow this one from all the others. His class (when opened) is the same as any open mail. – FaneDuru Apr 15 '22 at 11:32
  • I have in mind a specific `Category` to be allocated and based on that, to make the event working only for this specific case. I will start experimenting in this direction. I never used mail templates (until now)... Being events involved, the outlook automation form other applications would be difficult (even if not impossible). Then, even if the attachment in discussion is digital certified, this has nothing to do with Outlook security in terms of macro using. The Outlook session should be opened with macro enabled (for `ThisOutlookSession` which will contain the events code). .. – FaneDuru Apr 15 '22 at 11:34
  • @FaneDuru ,I forgot to mention that I also added the same Digital certificate to `ThisOutlookSession`, So no problem at all with security setting as no prompt to run Macro. I tried using `MailItem.Parent.Name` but it raised error. – Waleed Apr 15 '22 at 11:57
  • Even, better. In fact, I remember that the security option involves asking for enable macros in this case, too, not asking for other projects. Since `ThisOutlookSession` will be there all the time, it will ask in the same way. Of course, if I remember well this aspect. To time to check. I have something urgent to finish. Please, test the solution I posted and send some feedback. – FaneDuru Apr 15 '22 at 12:14
  • @FaneDuru ,to make it easier to fulfill , I like to reformulate the question to (Automatically open attached workbook when I open **any** message on specific outlook folder), But I am waiting ,may be your answer can be fixed. – Waleed Apr 16 '22 at 08:29

2 Answers2

3
  1. As I tried suggesting in my comments, you should modify Outlook Macro Security Settings to 'Notifications for all macros'. Then, the session must be closed and reopen choosing Macro Enabled.

  2. Copy the next code on top of the previous Sub:

Option Explicit

Public WithEvents MyItem As Outlook.MailItem
Public EventsDisable As Boolean

Private Sub Application_ItemLoad(ByVal Item As Object)
    If EventsDisable = True Then Exit Sub
    If Item.Class = olMail Then
        Set MyItem = Item
    End If
End Sub
Private Sub myItem_Open(Cancel As Boolean)
    EventsDisable = True
        If MyItem.Subject = "Auto Plan" And Application.ActiveExplorer.CurrentFolder.Name = "MyTemplate" Then
            If MyItem.Attachments.Count > 0 Then
                Dim obAttach As Attachment, strSaveMail As String, objExcel As Object
                Set obAttach = MyItem.Attachments(1)
                strSaveMail = "C:\Teste VBA Excel\outlook-attachments\"
                obAttach.SaveAsFile strSaveMail & obAttach.DisplayName
  
                Set objExcel = CreateObject("Excel.Application")
                objExcel.Workbooks.Open strSaveMail & obAttach.DisplayName
                objExcel.Visible = True: AppActivate objExcel.ActiveWindow.Caption
                Set objExcel = Nothing
            End If
        End If
    EventsDisable = False
End Sub

The Open event previously save the attachment workbook, creates an Excel session, makes it visible and open it there. It, probably, could get the existing session, but I was working there on a project and I did not dare to risk accidentally closing it...

Please, test it and send some feedback. It, probably, can be optimized, but I only tried obtaining a workable solution. It worked on my environment...

FaneDuru
  • 38,298
  • 4
  • 19
  • 27
  • I spent the last hour to find the windows location of my template message. I remember when I saved it on my desktop, then I dragged & drop into my specific outlook folder, then I deleted it from desktop. Anyhow, I created a new one and saved on windows folder `Template` then I dragged & drop into my specific outlook folder and `kept .oft file.` I created on outlook a new folder `MyTemplate`. I adjusted the paths on your code according to my profile. I am afraid to say, your code does not work (no effect) and no error raised at all. – Waleed Apr 15 '22 at 14:08
  • This is not the effect of the code I supplied, I think. Place a break point on the event first line and then run the code line by lane pressing F8, to see what happens... – FaneDuru Apr 15 '22 at 14:18
  • Do macros work? Are you asked about enabling macros? – FaneDuru Apr 15 '22 at 14:20
  • Place a break point in the first event code, please. Is the event triggered? – FaneDuru Apr 15 '22 at 14:24
  • Also, I think the `name of outlook folder` with the `subject of the email` are the keys to make the macro triggered. – Waleed Apr 15 '22 at 14:32
  • First, I changed outlook Macro Security Settings to 'Enable all macros' then I deleted all codes on ThisOutlookSession then I added only your codes, then saved and closed outlook and open again then I added a break point at this line `If EventsDisable = True Then Exit Sub` then I pressed **F5** to run the sub `ThisOutlookSession.AddCategoryToTemplate`, and pressed **F8** many times to debug the code, after finshed ,nothing happened at all (Auto Plan.oft not opened) and no error raised. – Waleed Apr 16 '22 at 07:11
  • May £ connect to your computer? – FaneDuru Apr 16 '22 at 12:04
  • At least, is the attachment saved? – FaneDuru Apr 16 '22 at 12:45
  • No,the attachment not saved. – Waleed Apr 16 '22 at 12:53
  • Maybe it is a matter of Windows security permissions. Try saving it in Documents... – FaneDuru Apr 16 '22 at 14:40
  • I put `outlook-attachments` on my desktop which I have full permission and surely updated the path to it on the code.anyhow I will set bounty for that question tomorrow (may be more persons can help).thanks for all your efforts. – Waleed Apr 16 '22 at 15:43
  • I am vacation today and I will try on my home PC.also I forgot to mention that the **format** of the email message is `Rich Text` and not `Html`,I don't know is that affects on your code or not ! – Waleed Apr 17 '22 at 22:22
  • 1
    @Waleed I don't think the format has something to do with this behavior. If you are available for a connection to your computer, please give me a sigh. I will try connecting... Only after that I will be able to better understand what's happening. I/we have the chance to know that the code **works on my computer** and must understand which of its part does not work as it should. Then trying to understand why... – FaneDuru Apr 18 '22 at 06:44
  • I tried on my home PC,but the same issue (attached file not opened automatically).kindly on your free time , I will send again – Waleed Apr 20 '22 at 10:21
  • @Waleed I cannot do it now. I will try connecting when I will be available. I do not remember why we could not use TeamViewer to the last connections... – FaneDuru Apr 20 '22 at 10:32
  • @Waleed I will try connecting in about 10 to 15 minutes. Are you available? We must test if TeamViewer works as we need. Please, also prepare a blank Notepad to communicate. I do not have too much time to spend... In fact, I will try a connection test right now. – FaneDuru Apr 20 '22 at 12:21
  • @Waleed Receiving message „Partner not connected”... – FaneDuru Apr 20 '22 at 12:35
  • I received only one single mail at 11:39 (Romanian time. Now is 16:04) – FaneDuru Apr 20 '22 at 13:04
  • @Waleed I updated the answer. I already deleted that part. In fact, I was playing with the option. Like I said before, I do not use Outlook VBA (for myself). I am only playing with issue which look challenging... :) – FaneDuru Apr 20 '22 at 14:04
  • In addition to the previous issue, the error raised by`AppActivate` because the email message must be fully loaded then the attached file can be activated, **But** I could not fulfilled that even after I used Windows API function (SetForegroundWindow function) – Waleed Apr 21 '22 at 08:44
  • The "critical issue" is relative... You asked about opening the attachment. The problem is not the one you try describing, I am afraid. The attachment it is **previously saved** locally and open from that local path. It probably be possible to remove the existing attachment then reattach the modified on, from the location where it has been saved. About `AppActivate`, it works in my installation, but not activating it on top of the opened mail. It is activated (not only blinking in taskbar) and the mail window goes on top of it. If I remember well, your mail window does not cover all the screen – FaneDuru Apr 21 '22 at 09:20
  • Sorry for using the word `Crtical` and deleted that comment – Waleed Apr 21 '22 at 09:31
  • Also this question toke more time from us , actually I tried to delete ،But ST did not allow it. – Waleed Apr 21 '22 at 09:39
  • @Waleed I must confess, I cannot understand you... Why to delete it? It may be instructive for somebody else wanting to open the attachment in its default application, just to see that it is the real (important) document version to be sent. I think I can solve the problem of making it keeping the modifications of the open document. In order to consider it being challenging, if you place a new question posting the code you have, better specifying the whole scenario about what you try doing and the problem you face, I think, it is very probable to design a piece of (adapted) code to solve it... – FaneDuru Apr 21 '22 at 10:32
  • It is strange from from MS developers, because they did not introduce `Open` method to Attachments object. Anyhow, I fulfilled the automation for my question by using `SetCursorPos and DoubleClick` ,I know it dose not consider as an answer, because it is very dedicated to my own PC. at last, I updated the title and body of my question ,so may be someone can benefit from your answer and learn how to use conditions while opening any email ,(you are right) . Accepted answer & many thanks for your dedicated efforts. – Waleed Apr 23 '22 at 08:02
  • Kindly if you can help for automation https://stackoverflow.com/questions/71979536/how-to-maximize-and-set-focus-to-foreground-for-the-opened-outlook-email-message – Waleed Apr 23 '22 at 12:18
1

The ItemLoad event is fired when the Outlook item begins to load into memory. Data for the item is not yet available, other than the values for the Class and MessageClass properties of the Outlook item, so an error occurs when calling any property other than Class or MessageClass for the Outlook item returned in Item.

Instead, I'd suggest handling 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. This event also occurs when the user (either programmatically or via the user interface) clicks or switches to a different folder that contains items, because Outlook automatically selects the first item in that folder.

Public WithEvents myOlExp As Outlook.Explorer 
 
Public Sub Initialize_handler() 
 Set myOlExp = Application.ActiveExplorer  
End Sub 
  
Private Sub myOlExp_SelectionChange()
 MsgBox myOlExp.Selection.Count & " items selected." 
End Sub

In the event handler you could check the Explorer.CurrentFolder property which returns a Folder object that represents the current folder displayed in the explorer.

If you need to handle inspector windows also you need to use the Inspectors.NewInspector event which is fired whenever a new inspector window is opened, either as a result of user action or through program code.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • Actually, I found out that using VBA with outlook is more difficult than excel. – Waleed Apr 16 '22 at 19:07
  • Yeah, no doubts! :-) – Eugene Astafiev Apr 16 '22 at 19:49
  • 1
    SO is not a service to request a fully-made solution. You may find the [Implement a wrapper for inspectors and track item-level events in each inspector](https://learn.microsoft.com/en-us/office/client-developer/outlook/pia/how-to-implement-a-wrapper-for-inspectors-and-track-item-level-events-in-each-inspector) article with a source code helpful. – Eugene Astafiev Apr 17 '22 at 17:55
  • 1
    In `myItem_Open` event which is triggered in the OP Code, 'myItem' exposes all its properties/methods. I am afraid that OP problem is not that. The opening of the item is triggered and (theoretically) he can do whatever he needs. If you do not believe me, please test the code I posted. It works very well in my installation. His problem looks to be security related. In his case his user is not able to save the attachment (even if I can) and of course, not opening it, since it is nothing to be opened. What looks strange to me, is the fact he does not receive any error on that specific code lines – FaneDuru Apr 17 '22 at 19:47