【问题标题】:Writing email messages to flat files in Outlook with VBA使用 VBA 在 Outlook 中将电子邮件消息写入平面文件
【发布时间】:2010-09-28 21:26:47
【问题描述】:

我编写了一个 VBA 应用程序,它在 Outlook 中打开一个文件夹,然后遍历消息。我需要将消息正文(经过一些调整)写入单个平面文件。我的代码如下...

Private Sub btnGo_Click()
    Dim objOutlook As New Outlook.Application
    Dim objNameSpace As Outlook.NameSpace
    Dim objInbox As MAPIFolder
    Dim objMail As mailItem
    Dim count As Integer

    Set objNameSpace = objOutlook.GetNamespace("MAPI")
    Set objInbox = objNameSpace.GetDefaultFolder(olFolderInbox)
    count = 0

    For Each objMail In objInbox.Items
       lblStatus.Caption = "Count: " + CStr(count)
       ProcessMailItem (objMail)
       count = count + 1
    Next objMail

  End If
End Sub

有问题的部分是“ProcessMailItem”。由于我并不太关心现阶段的性能,因此非常低效的“打开、追加、关闭”文件方法适用于本示例。

我知道我可以花一些时间在谷歌上查找答案,但我先在这里查了一下,没有很好的答案。作为 Stackoverflow 的粉丝,我希望把它放在这里可以帮助未来的开发人员寻找答案。感谢您的耐心等待。

【问题讨论】:

    标签: vba email outlook flat-file


    【解决方案1】:

    您还必须注意Outlook "Object Model Guard" Security Issues for Developers 中介绍的“尝试访问电子邮件地址”的安全弹出窗口

    Public Sub ProcessMailItem(objMail As MailItem)
    Dim FSO As New FileSystemObject
    Dim ts As TextStream
    Dim loc As String
    Dim subject As String
    Dim strID As String
    ' per http://www.outlookcode.com/article.aspx?ID=52
    Dim olNS As Outlook.NameSpace
    Dim oMail As Outlook.MailItem
    
    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set oMail = olNS.GetItemFromID(strID)
    subject = oMail.subject
    Set ts = FSO.OpenTextFile("C:\Documents and Settings\tempuser\My Documents\EMAILS\" + subject, ForAppending, True)
    ts.Write (oMail.Body)
    ts.Close
    Set ts = Nothing
    Set FSO = Nothing
    Set oMail = Nothing
    Set olNS = Nothing
    

    结束子

    【讨论】:

    • OpenTextFile 中的路径仍然存在一些问题。与没有空格的较短路径相比,我没有得到与该路径一致的结果。
    【解决方案2】:

    您可以在不使用任何对象的情况下写入文件,只需使用内置的 VBA 文件工具:

    Open "C:\file.txt" for append as 1
    Print #1, SomeStringVar
    Close #1
    

    【讨论】:

    • 我选择了这个答案,因为它非常以 VBA 为中心。 Eric Ness 的回答也是有效的!!
    【解决方案3】:

    如果您不介意每次附加一些文本时都重新打开输出文件,那么这应该可以。

    Private Sub ProcessMailItem(objMail As MailItem)
    
        Dim fso As New FileSystemObject
        Dim ts As TextStream
    
        Set ts = fso.OpenTextFile("C:\Outputfile.txt", ForAppending, True)
    
        ts.Write(objMail.Body)
    
        ts.Close()
        Set ts = Nothing
        Set fso = Nothing
    
    End Sub
    

    您还需要添加对 Microsoft 脚本运行时库的引用。这里面有 FileSystemObject。

    【讨论】:

      猜你喜欢
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2019-12-24
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多