如何确认我的宏工作?

时间:2017-03-09 08:56:35

标签: vba outlook-vba

我想让下面的脚本正常工作。我粘贴到ThisOutlookSession并创建了所需的适当路径(c:\mails)。我也打开并关闭了展望。

我将其粘贴如下,我错过了什么?当我用Alt + F8调用它时它应该出现吗?

谢谢,

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
  Dim Ns As Outlook.NameSpace
  Set Ns = Application.GetNamespace("MAPI")
  Set Items = Ns.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)
  If TypeOf Item Is Outlook.MailItem Then
    SaveMailAsFile Item
  End If
End Sub

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

  sPath = "c:\mails"
  sExt = ".msg"
  sName = oMail.Subject
  ReplaceCharsForFileName sName, "_"
  dtDate = oMail.ReceivedTime
  sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
    vbUseSystem) & Format(dtDate, "-hhnnss", _
    vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & sExt

  oMail.SaveAs sPath & sName, olSaveAsMsg
End Sub

Private Sub ReplaceCharsForFileName(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, Chr(34), sChr)
  sName = Replace(sName, "<", sChr)
  sName = Replace(sName, ">", sChr)
  sName = Replace(sName, "|", sChr)
End Sub

2 个答案:

答案 0 :(得分:0)

代码并非设计为手动运行 - 它应该在您收到电子邮件时自动运行 - 它不会显示在宏名称 ALT F8

如果所有代码都在同一个模块下,那么使用private sub是没有错的 -

现在修复您缺少的文件夹路径 sPath = "c:\mails\" \

答案 1 :(得分:0)

带有一个或多个参数的代码,任何类似于(ByVal Item As Object)的东西都需要输入。

有多种方法可以测试您的代码。

Sub Items_ItemAdd_Test
    ' with an open item
    '  a mailitem if you want to get to SaveMailAsFile
    Items_ItemAdd ActiveInspector.CurrentItem
    ' or with anything selected
    '  a mailitem if you want to get to SaveMailAsFile
    'Items_ItemAdd ActiveExplorer.Selection(1)
End Sub


Sub SaveMailAsFile_Test
    ' with an open MailItem
    SaveMailAsFile ActiveInspector.CurrentItem
    ' or with a MailItem selected
    'Items_ItemAdd ActiveExplorer.Selection(1)
End Sub

您可以找到手动或以编程方式将项目移动或复制到文件夹中的用法。