Tuesday, December 7, 2021

Create Related Task in Outlook from email with attachment

Hello Guys, 

Sometimes, we receive an email and wants to keep a track of the actions to be performed on the email.

This can be done by creating a task manually in outlook and then, track the actions of the task. 

But, have you wonder, if the task gets created from the email itself with the attachment of the email in the task, on  click of a button.

Today, I will show you, the outlook vba code, which will create the required task, copy the email content in the task and will also attach the copy of the email in the task body, so that we can open the email from the task itself. By this we will not require to search the email again.

Here is the vba code for creating the task and attaching the current email in it:
Sub CreateTask()
    Dim oItem As MailItem
    Dim oTask As TaskItem
    Dim sBody As String
    Dim sTempPath As String, sSender As String
    
    If Outlook.ActiveExplorer.Selection.count > 1 Then
        MsgBox "You have selected more than One item. Please select a single item and run the macro again."
    End If
    
    Set oItem = Outlook.ActiveExplorer.Selection(1)
    sBody = oItem.Body
    sTempPath = Environ("temp")
    oItem.SaveAs sTempPath & "\1.msg", olMSG
    Set oTask = Outlook.CreateItem(olTaskItem)
    
    With oTask
        'include time and from in subject of task
        sSender = oItem.SenderName
        sSender = VBA.Replace(sSender, ",", " ")
        sSub = sSender
        sSub = sSub & " - " & oItem.Subject
        sSub = sSub & " - " & Format(oItem.ReceivedTime, "mm/DD/YYYY")
        .Subject = sSub
        
        'include attachment
        .Attachments.Add sTempPath & "\1.msg"
        If oItem.SenderEmailType = "EX" Then
            sSenderMail = oItem.Sender.GetExchangeUser.PrimarySmtpAddress
        Else
            sSenderMail = oItem.SenderEmailAddress
        End If
        
        sBody = "From:     " & sSenderMail & vbCr & "Sent:     " & oItem.ReceivedTime & vbCr & "Subject: " & oItem.Subject & "  " & vbCr & sBody & "   " & vbCr & vbCr
        .Body = sBody
        .StartDate = Date
        .Display
    End With
End Sub

How to Install and Use the Macro:
In order to use the macro, Open Outlook and Press Alt +F11 key. This will open the VBA editor in outlook.

Go to Insert menu and insert a module and paste the above code and Press save button and close the window.

Now Go to the Outlook and select a email for which you want to create a related task and Press Alt+F8. 

You will see a macro named Create Task. Press the Run button. This should now create the related task with attachment of the email for you.

If you like this article or have any query/suggestions, please share your feedback in the comments section below..

Thanks,
Ashwani

 

If you want to develop macro for any Microsoft office product
or
automate your task in excel please reach out to my Fiverr account, mentioned below:


0 comments: