【问题标题】:VBA - Moving Email Based on Attachment FilenameVBA - 基于附件文件名移动电子邮件
【发布时间】:2020-06-23 07:52:01
【问题描述】:

如果附件文件名与字符串匹配(例如,“asdfqwerty”),我正在尝试编写一个宏来移动电子邮件。电子邮件将从我的收件箱移动到我的收件箱下的文件夹“测试”。

很遗憾,不能选择使用兑换。

感谢任何帮助!

编辑 这是我根据 Dmitry 的提示更新的代码。我现在在最后一个 Next 上收到“类型不匹配”错误,不知道为什么:

Sub SaveOlAttachments()
Dim olFolder As MAPIFolder
Dim olFolder2 As MAPIFolder
Dim msg As mailItem

Set olFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set olFolder2 = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Folders("Test")

For Each msg In olFolder.Items
    If msg.Class = 43 Then
        If msg.Attachments.Count > 0 Then
            If Left$(msg.Attachments(1).FileName, 10) = "asdfqwerty" Then
            msg.Move (oldFolder2)
            End If
        End If
    End If
Next
End Sub

【问题讨论】:

  • 在操作(item.Move)组集合时要小心For Each,因为这会导致错误。使用For n = olFolder.Items.Count -1 to 0 Step -1 并反向迭代以保留Items 索引。否则,如果您移动第一个元素,则前第二个元素将首先获得。

标签: vba outlook


【解决方案1】:

您是否尝试运行该代码?它会在msg.Attachments > 0 行出错。你需要msg.Attachments.Count > 0

下一行也不会运行 - 您需要遍历 msg.Attachments 集合中的所有附件:

for each attach in msg.Attachments
  if InStr(attach.FileName, "asdfqwerty") Then
     msg.Move (olFolder2)
     Exit for
  End If
next

在发布之前,请至少努力确保您的代码可以编译,甚至可以运行。不要指望其他人会为你这样做。

【讨论】:

  • 嗨,我是 VBA 新手,当我运行它时,它在 msg.Attachments > 0 行上出现错误,但我不知道我需要 Count。这很有意义。谢谢!将研究循环遍历所有附件。
  • 我已经更新了上面的代码,但似乎无法找出最后一个 Next 语句中类型不匹配错误的原因。会不会是我没有正确循环浏览电子邮件?
  • 尝试“next msg”。
  • @zxcvb 搜索对应的站点stackoverflow.com/questions/13617305/…
【解决方案2】:

带有附件的电子邮件进来,规则执行以下 VBA 脚本:

Sub Test() 

'Declaration 
Dim myItems, myItem, myAttachments, myAttachment As Object 
Dim myOrt As String 
Dim myFin As String 
Dim myOlApp As New Outlook.Application 
Dim myOlExp As Outlook.Explorer 
Dim myOlSel As Outlook.Selection 

'Ask for destination folder 
myOrt = "W:\" 

On Error Resume Next 

'work on selected items 
Set myOlExp = myOlApp.ActiveExplorer 
Set myOlSel = myOlExp.Selection 

'for all items do... 
For Each myItem In myOlSel 

'point on attachments 
Set myAttachments = myItem.Attachments 

'if there are some... 
If myAttachments.Count > 0 Then 


'for all attachments do... 
For i = 1 To myAttachments.Count 

'Ask for destination folder 
myFin = InputBox("Please type a filename below:", "Saving 
recording...", "") 

'save them to destination 
myAttachments(i).SaveAsFile myOrt & _ 
myFin 

Next i 
End If 
Next 
End Sub 

【讨论】:

    猜你喜欢
    • 2011-12-22
    • 2015-05-28
    • 1970-01-01
    • 2017-05-20
    • 2013-03-18
    • 2013-08-10
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多