我是 VB 新手,一直在努力尝试创建一个 VBA 宏,该宏将在收到电子邮件时自动执行以下任务:
1) 检查电子邮件是来自内部还是外部。(如果外部忽略)
2) 检查电子邮件是否有附件。(如果没有附件,则忽略)
3)检查附件名称,应如“report”(全名一般为“Report 12198 blah blah.pdf”)。(如果附件名称不是“report”则忽略)
4) 将附件保存在 G:\Test
5) 将电子邮件移动到名为“Completed”的 Outlook 文件夹
我见过很多网站都有保存附件、将电子邮件移动到文件夹的代码,但似乎没有其他人遇到与我相同的问题;将这两者结合起来。
我最初认为我可以使用 Outlook 规则来帮助完成其中的一些工作,但我目前拥有的代码(用于保存附件)并未显示为脚本。
此外,我在一个网站(不记得是哪一个)上读到,在尝试执行“移动”或“删除”等操作时,您不能使用“For Each”循环,所以我不是太确定下面的代码是否应该可用。
任何帮助将不胜感激。这是我目前的代码:
Sub GetAttachments()
On Error GoTo GetAttachments_err
Dim ns As NameSpace
Dim Inbox As MAPIFolder
Dim Item As Object
Dim Atmt As Attachment
Dim StringLength As Long
Dim FileName As String
Dim i As Integer
Set ns = GetNamespace("MAPI")
Set Inbox = ns.GetDefaultFolder(olFolderInbox)
i = 0
If Inbox.Items.Count = 0 Then
MsgBox "There are no messages in the Inbox.", vbInformation, _
"Nothing Found"
Exit Sub
End If
For Each Item In Inbox.Items
For Each Atmt In Item.Attachments
If Left(Atmt.FileName, 6) Like "*REPORT*" Then
StringLength = Len(Atmt.FileName)
FileName = "G:\Test\" & Left(Atmt.FileName, (StringLength - 13)) & Format(Item.CreationTime, "ddmmmyyyy") & ".pdf"
Atmt.SaveAsFile FileName
i = i + 1
End If
Next Atmt
Next Item
If i > 0 Then
MsgBox "I found " & i & " attached files." _
& vbCrLf & "I have saved them into the Test Folder." _
& vbCrLf & vbCrLf & "Have a nice day.", vbInformation, "Finished!"
Else
MsgBox "I didn't find any attached files in your mail.", vbInformation, _
"Finished!"
End If
GetAttachments_exit:
Set Atmt = Nothing
Set Item = Nothing
Set ns = Nothing
Exit Sub
GetAttachments_err:
MsgBox "An unexpected error has occurred." _
& vbCrLf & "Please note and report the following information." _
& vbCrLf & "Macro Name: GetAttachments" _
& vbCrLf & "Error Number: " & Err.Number _
& vbCrLf & "Error Description: " & Err.Description _
, vbCritical, "Error!"
Resume GetAttachments_exit
Exit Sub
End Sub