1

我正在尝试为 Outlook 编写一个小宏程序。该程序应自动将传入电子邮件的文本保存为文本文件。

我找到了大段代码并试图让它工作,但它仍然无法工作。

Option Explicit

Public Enum olSaveAsTypeEnum
    olSaveAsTxt = 0
    olSaveAsRTF = 1
    olSaveAsMsg = 3
End Enum

Private WithEvents Items As Outlook.Items


Private Const MAIL_PATH As String = "C:\mails\"
'Private Const MAIL_PATH As String = "C:\Users\dirk\AppData\Local\Microsoft\Outlook\"


Private Sub Application_Startup()
    Dim Ns As Outlook.NameSpace

    Set Ns = Application.GetNamespace("MAPI")
    Set Items = Ns.GetDefaultFolder(olFolderInbox).Items

End Sub

Private Sub ItemsItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
    SaveMailAsFile Item, olSaveAsTxt, MAIL_PATH
    End If
End Sub

Private Sub SaveMailAsFile(oMail As Outlook.MailItem, eType As olSaveAsTypeEnum, sPath As String)
    Dim dtDate As Date
    Dim sName As String
    Dim sFile As String
    Dim sExt As String

    Select Case eType
        Case olSaveAsTxt = sExt = ".txt"
        Case olSaveAsMsg = sExt = ".msg"
        Case olSaveAsRTF = sExt = ".rtf"
        Case Else: Exit Sub
    End Select
    sName = oMail.Subject
    RecplaceCharsForFileName sName, "_"

    dtDate = oMail.RecievedTime
    sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, vbUseSystem) & Format(dtDate, "-hhnnss", vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & sExt

    oMail.SaveAs sPath & sName, eType


End Sub

Private Sub RecplaceCharsForFileName(sName As String, sChr As String)
    sName = Replace(sName, "/", sChr)
    sName = Replace(sName, "\", sChr)
    sName = Replace(sName, ";", sChr)
    sName = Replace(sName, "?", sChr)
    sName = Replace(sName, "<", sChr)
    sName = Replace(sName, ">", sChr)
    sName = Replace(sName, "|", sChr)
    sName = Replace(sName, "Chr(34)", sChr)

End Sub

我不是在单独的模块中而是在已经存在的ThisOutlookSession模块中编写此代码。

谁能告诉我我做错了什么?

4

1 回答 1

0

另外,关于 ItemAdd 事件(不确定您是否正确使用它):https ://msdn.microsoft.com/en-us/library/office/bb220152(v=office.12) .aspx – dnLL

Private Sub Items_ItemAdd(ByVal Item As Object)
    If TypeOf Item Is Outlook.MailItem Then
    SaveMailAsFile Item, olSaveAsTxt, MAIL_PATH
    End If
End Sub
于 2015-03-03T22:10:57.713 回答