vbaoutlookattachment

Set the position of an attachment in a TaskItem


I am trying to create a task with an attachment from a MailItem using VBA in Outlook 2019.

According to the documentation for Attachments.Add:

Position Optional Long: This parameter applies only to email messages using the Rich Text format: it is the position where the attachment should be placed within the body text of the message. A value of 1 for the Position parameter specifies that the attachment should be positioned at the beginning of the message body. A value 'n' greater than the number of characters in the body of the email item specifies that the attachment should be placed at the end. A value of 0 makes the attachment hidden.

If I use position 1, the icon with the link to the original mail will still be at the end of the body instead of the beginning.

Sub CreateTask()
    Set olApp = Outlook.Application
    Set Msg = olApp.ActiveExplorer.Selection.Item(1)
    Dim olTask As TaskItem
    Set olTask = olApp.CreateItem(olTaskItem)
    With olTask
        .Subject = Msg.Subject
        .RTFBody = Msg.RTFBody
        .Attachments.Add Msg, , 1  ' For some reasone position argument not working :(
        '.Save
        .Display
    End With
End If

Solution

  • There is an Outlook quirk, .Display before editing.

    Appears it applies in this situation too.

    Option Explicit
    
    Sub CreateTask()
    
        Dim itm As Object
        Dim msg As MailItem
        
        Dim olTask As TaskItem
        
        Set itm = ActiveExplorer.Selection.Item(1)
        
        If itm.Class = olMail Then
        
            Set msg = itm
            Set olTask = CreateItem(olTaskItem)
        
            With olTask
    
                .subject = msg.subject
                .RTFBody = msg.RTFBody
                
                .Display    ' <--- Earlier rather than later
                
                .Attachments.Add msg, , 1
                
            End With
    
        End If
        
    End Sub