VBA从邮件正文中选择文本

时间:2015-01-06 20:19:47

标签: vba email outlook copy outlook-vba

我想要复制整个电子邮件的正文。 我使用了这个代码(我找到了某个地方并修改了自己)并且它不时起作用。 问题是每次都没有激活邮件窗口=>代码从活动的winwow中选择其他东西。 我怎样才能做到对不对?

我尝试了AppActivate ("Microsoft Outlook"),但它不起作用。

Private Sub copymail()

    Dim objOutlook As Outlook.Application
    Dim objInspector As Outlook.Inspector

    Dim strDateTime As String

    ' Instantiate an Outlook Application object.
    Set objOutlook = CreateObject("Outlook.Application")

    ' The ActiveInspector is the currently open item.
    Set objExplorer = objOutlook.ActiveExplorer

    ' Check and see if anything is open.
    If Not objExplorer Is Nothing Then
        ' Get the current item.
        Dim arySelection As Object
        Set arySelection = objExplorer.Selection

        For x = 1 To arySelection.Count
            Dim m As MailItem
            Set m = arySelection.Item(x)
            m.Display
            'DoEvents
            'DoEvents
            Application.Wait (Now + #12:00:02 AM#)
            'AppActivate ("Microsoft Outlook")
            SendKeys ("^a^c")
            DoEvents
            Application.Wait (Now + #12:00:01 AM#)

        Next x

    Else
        ' Show error message with only the OK button.
        MsgBox "No explorer is open", vbOKOnly
    End If

    ' Set all objects equal to Nothing to destroy them and
    ' release the memory and resources they take.
    Set objOutlook = Nothing
    Set objExplorer = Nothing
End Sub

2 个答案:

答案 0 :(得分:2)

您可以通过MailItem.Body(纯文本)或MailItem.HTMLBody(HTML)属性访问邮件正文。无需使用SendKeys:

Sub getMailtext()

    Dim objOutlook As Outlook.Application
    Dim objInspector As Outlook.Inspector

    Dim strDateTime As String

    ' Instantiate an Outlook Application object.
    Set objOutlook = CreateObject("Outlook.Application")

    ' The ActiveInspector is the currently open item.
    Set objExplorer = objOutlook.ActiveExplorer

    ' Check and see if anything is open.
    If Not objExplorer Is Nothing Then
        ' Get the current item.
        Dim arySelection As Object
        Set arySelection = objExplorer.Selection

        For x = 1 To arySelection.Count
            Dim m As MailItem
            Set m = arySelection.Item(x)

            Debug.Print m.Body
            Debug.Print m.HTMLBody

        Next x

    Else
        ' Show error message with only the OK button.
        MsgBox "No explorer is open", vbOKOnly
    End If

    ' Set all objects equal to Nothing to destroy them and
    ' release the memory and resources they take.
    Set objOutlook = Nothing
    Set objExplorer = Nothing
End Sub

答案 1 :(得分:0)

Outlook使用Word作为电子邮件编辑器。您可以使用Word对象模型在邮件正文上进行操作。 Inspector类的WordEditor属性返回表示正文的Document类(来自Word对象模型)的实例。您可以在Chapter 17: Working with Item Bodies中详细了解该方式和所有可能的方法。