从Outlook获取附件并在格式化后放入新电子邮件的正文

时间:2015-09-08 17:47:43

标签: vba outlook attachment

这基本上就是我想做的......

  1. 按主题名称搜索特定电子邮件

  2. 获取该电子邮件的附件(附件是原始数据的Excel表格)

  3. 从Excel附件中的另一个模块运行格式化子例程

  4. 将新格式化的附件放入新电子邮件正文

  5. 将新电子邮件发送给客户

  6. 我需要第3步和第3步的帮助4。

    Option Explicit
    Sub sendEmail()
    
    Dim olApp As Outlook.Application
    Dim olEmail As Outlook.MailItem
    Dim olNs As Namespace
    Dim Fldr As MAPIFolder
    Dim olMi As MailItem
    Dim olAtt As Attachment
    Dim MyPath As String
    Dim i As Long
    
    Set olApp = New Outlook.Application
    Set olEmail = olApp.CreateItem(olMailItem)
    Set olNs = olApp.GetNamespace("MAPI")
    Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
    MyPath = "C:\Users\(Me)\Desktop\"
    
    For i = Fldr.Items.count To 1 Step -1
        Set olMi = Fldr.Items(i)
        If InStr(1, olMi.Subject, "[The email I'm looking for by subject]") > 0 Then
             For Each olAtt In olMi.Attachments
                    olAtt.Module2.Format   '<--- this is where i try to do step 3
                    olAtt.SaveAsFile MyPath & "NewSheet" & ".xls"             
            With olEmail
                .BodyFormat = olFormatHTML
                .Body = olAtt.Range   '<----this is where i try to do step 4
                .To = "someone@something.com"
                .Subject = "Tester"
                .send
            End With
    
            Next olAtt
            olMi.Save
        End If
    Next i
    
    Set olAtt = Nothing
    Set olMi = Nothing
    Set Fldr = Nothing
    Set MoveToFldr = Nothing
    Set olNs = Nothing
    Set olApp = Nothing
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

请参阅Getting Started with VBA in Outlook 2010

我注意到以下代码:

For i = Fldr.Items.count To 1 Step -1
 Set olMi = Fldr.Items(i)
  If InStr(1, olMi.Subject, "[The email I'm looking for by subject]") > 0 Then

不要迭代文件夹中的所有项目。相反,您需要使用Items类的Find / FindNextRestrict方法来获取与您的条件相对应的项目。您可以在MSDN的以下文章中阅读有关它们的更多信息。您还可以找到以下文章:

  

.Body = olAtt.Range'&lt; ----这是我尝试做第4步的地方

Outlook对象模型提供了三种使用项主体的主要方法:

  1. Body
  2. HTMLBody
  3. Word编辑器。 Inspector类的WordEditor属性返回表示邮件正文的Word文档实例。因此,您可以使用Word对象模型对邮件正文执行任何操作
  4. 有关详细信息,请参阅Chapter 17: Working with Item Bodies