我不知道到底你的代碼有什麼問題。但是,首先,你並沒有確認一個新的,可編輯的電子郵件甚至是開放的。下面的概念證明完全符合我認爲你想要做的事情:在正在編寫的活動電子郵件中插入一些文本。如果這是不可能的,它會顯示一個消息框來解釋原因。
該插入如果Word被用作電子郵件編輯器(其將ALWAYS be the case in Outlook 2010+)文本只會工作的部分。如果不是,您將不得不直接解析和更新Body或HTMLBody文本。
Sub InsertText()
Dim myText As String
myText = "Hello world"
Dim NewMail As MailItem, oInspector As Inspector
Set oInspector = Application.ActiveInspector
If oInspector Is Nothing Then
MsgBox "No active inspector"
Else
Set NewMail = oInspector.CurrentItem
If NewMail.Sent Then
MsgBox "This is not an editable email"
Else
If oInspector.IsWordMail Then
' Hurray. We can use the rich Word object model, with access
' the caret and everything.
Dim oDoc As Object, oWrdApp As Object, oSelection As Object
Set oDoc = oInspector.WordEditor
Set oWrdApp = oDoc.Application
Set oSelection = oWrdApp.Selection
oSelection.InsertAfter myText
oSelection.Collapse 0
Set oSelection = Nothing
Set oWrdApp = Nothing
Set oDoc = Nothing
Else
' No object model to work with. Must manipulate raw text.
Select Case NewMail.BodyFormat
Case olFormatPlain, olFormatRichText, olFormatUnspecified
NewMail.Body = NewMail.Body & myText
Case olFormatHTML
NewMail.HTMLBody = NewMail.HTMLBody & "<p>" & myText & "</p>"
End Select
End If
End If
End If
End Sub
如果沒有選擇任何內容,那麼確實'ActiveInspector'將是'Nothing'。不過,我不知道'ActiveWindow'怎麼可能是'Nothing'。你把這個代碼放在哪裏,你怎麼調用它? – 2013-03-18 12:48:33
代碼位於模塊中,當用戶手動運行宏或單擊運行宏的菜單按鈕時,會調用該過程。 – dnLL 2013-03-18 13:09:14
你可以發佈整個方法的代碼嗎? – 2013-03-18 14:29:20