我不知道到底你的代码有什么问题。但是,首先,你并没有确认一个新的,可编辑的电子邮件甚至是开放的。下面的概念证明完全符合我认为你想要做的事情:在正在编写的活动电子邮件中插入一些文本。如果这是不可能的,它会显示一个消息框来解释原因。
该插入如果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