How to edit existing MailItem using WordEditor in Outlook VBA?

你离开我真会死。 提交于 2019-12-02 03:50:59

问题


So I want to edit my received mails afterwards to add links. If the emails have been received as plain text or HTML I have just edited the appropriate msg.Body or msg.HTMLBody. However, for Rich Text, editing RTFBody directly seems both rather complicated and keeps crashing my Outlook.

I can edit the HTMLBody of Rich Text mails, but it then converts the whole mail to HTML which makes it change appearance and can't handle embedded attachments well.

MSDN talks about MailItem.GetInspector, which returns WordEditor and allows a much easier way of editing documents. Problem is, all examples I've found are of new mails being created, not existing being edited. The following code:

        Set objInsp = itm.GetInspector
        Set objDoc = objInsp.WordEditor
        objDoc.Characters(1).InsertBefore "string"

Generates the following error: Run-time error '4605', This method or property is not available because the document is locked for editing.

Does anyone know a way to unlock the mailitem to allow for editing, alternatively, a way to edit RTFBody that doesn't go belly up? I've tried to set the objDoc.ProtectionType to something that allows writing, but it also says I cannot change the document.


回答1:


I was facing exactly the same issue (Outlook VBA: Replace inline object with text). As posted in my comment (soon to be edited to a more polished version, after further testing), you have to use objDoc.UnProtect prior to modifying contents. I have actually used

'On Error Resume Next   ' This will prevent the error message... risky!
Dim odProt As Integer
odProt = objDoc.ProtectionType
If (odProt <> wdNoProtection) Then
    Debug.Print "Document is protected with type " & odProt & ", unprotecting temporarily"
    objDoc.UnProtect
End If
' ... Write your code
If (odProt <> wdNoProtection) Then
    Debug.Print "Restoring protection"
    objDoc.Protect (odProt)
End If
objMsg.Display
objMsg.Save

I am not sure if the last two lines are the best, but it worked for me.

Note that having On Error Resume Next will prevent the error message, and you may see that none of your editions has any effect without apparent reason.



来源:https://stackoverflow.com/questions/19510335/how-to-edit-existing-mailitem-using-wordeditor-in-outlook-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!