The following code creates and sends a simple email. After the email is sent it replaces a string in the email body.
My code works when I use the debugger’s single-step feature to execute the code. It also works when I add a MsgBox instruction with a “click to continue” button after the objMsg.Send
instruction. It does not work when I execute the macro without interruption, but tells me that Outlook cannot save an email to the folder when a macro is running.
Sub CreateNewMessage()
objMsg As MailItem
Set objMsg = Application.CreateItem(olMailItem)
With objMsg
.To = "mblasberg@inoxel.com"
.subject = "This is the subject"
.BodyFormat = olFormatHTML
.Body = "How are you doing?"
End With
objMsg.Send
' The following code replaces in the email body the string "you" with "they"
' Because I could not find how to open the "last sent" email,
' I used the "Sent Items" folder email count as as the pointer
' to the last email.
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = _
myNameSpace.GetDefaultFolder(olFolderSentMail)
Dim EmailCount As Integer
EmailCount = myFolder.Items.Count
Set myItem = myFolder.Items(EmailCount)
myItem.HTMLBody = replace(myItem.HTMLBody, "you", "they")
myItem.Save
End Sub