【问题标题】:I don't understand why I can't delete Outlook messages with VBA我不明白为什么我不能用 VBA 删除 Outlook 邮件
【发布时间】:2014-11-09 12:05:05
【问题描述】:

我正在尝试使用 Outlook 规则和 VBA 将电子邮件正文复制到纯文本文件中以进行进一步处理,然后从 Outlook 中删除该邮件。

我无法使用 Outlook 规则删除邮件,因为我无法控制 Outlook 在规则中执行操作的顺序。如果我可以将“运行脚本,然后删除”作为一项操作,那么就足够了。但是,Outlook 只允许我先删除邮件,然后运行脚本,这对我来说没用。

我显然不知道从地面上的一个洞中获得的 VBA,但根据我从谷歌搜索中收集到的信息,我有以下 VBA 可以满足我的需要,除了我不知道如何删除电子邮件。

到目前为止的代码:

Public Sub SaveBody3(Item As Outlook.MailItem)
    Dim olApp As Outlook.Application
    Dim olNs As NameSpace
    Dim Fldr As MAPIFolder
    Dim olMail As MailItem
    Dim i As Integer  
    Dim fso As New FileSystemObject
    Dim ts As TextStream

    Set olApp = New Outlook.Application
    Set olNs = olApp.GetNamespace("MAPI")
    Set Fldr = olNs.GetDefaultFolder(olFolderInbox)

    i = 1

    For Each olMail In Fldr.Items
        If InStr(olMail.Subject, "my_very_specific_subject_line") Then
            Set ts = fso.OpenTextFile("\\path\to\textfile\filename_" & Format(Now, "yyyymmddhhnnss") & ".txt", ForWriting, True)
            ts.Write (olMail.Body)
            ts.Close
            olMail.Delete 'Shouldn't this delete??
            Set ts = Nothing
            Set fso = Nothing
            i = i + 1
        End If
    Next olMail

    Set Fldr = Nothing
    Set olNs = Nothing
    Set olApp = Nothing

End Sub

【问题讨论】:

  • 我会问你我问每个有类似问题的人:为什么还要尝试删除?只需在适当的时间间隔归档或自动归档您的收件箱,就可以清理旧项目。也就是说,我希望.Delete 方法应该删除味精(当我测试一个简单的案例时它会删除)。你有错误吗?

标签: vba outlook


【解决方案1】:

您的代码在我的电脑上完美运行。检查你的垃圾桶。如果您根据对具有特定主题行的所有邮件的搜索来评估被删除的电子邮件,您不会注意到被删除的电子邮件,因为它只是被移动到您的垃圾箱(但仍然存在)。清空垃圾箱,运行代码,然后查看垃圾文件夹中是否显示任何内容。

【讨论】:

    【解决方案2】:

    有时 For Each 无法按预期工作。随着索引的变化跳过项目。

    建议是向后删除。 http://msdn.microsoft.com/en-us/library/office/ff863343(v=office.15).aspx “Delete 方法删除集合中的单个项目。要删除文件夹的 Items 集合中的所有项目,您必须从文件夹中的最后一个项目开始删除每个项目。”

    如果 nothing 在当前循环中起作用,试试这个。

    Dim j As Long
    
    For j = Fldr.Items.count To 1 Step -1
    
        If TypeOf Fldr.Items(j) Is mailitem Then
    
            Set olMail = Fldr.Items(j)
    
            If InStr(olMail.subject, "my_very_specific_subject_line") Then
                Set ts = fso.OpenTextFile("\\path\to\textfile\filename_" & Format(Now, "yyyymmddhhnnss") & ".txt", ForWriting, True)
                ts.Write (olMail.body)
                ts.Close
                olMail.Delete
                Set ts = Nothing
                Set fso = Nothing
                i = i + 1
            End If
    
            Set olMail = Nothing
    
        End If
    
    Next j
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 2021-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多