需要帮助创建一个 VBA 代码来提取每封电子邮件的子文件夹附件

Need help creating a VBA code that extracts attachments with subfolders per email

我正在尝试创建执行此操作的代码:

Public Sub saveAttachment(item As Outlook.MailItem)
Dim attachment As Outlook.Attachment
Dim defaultPath As String
defaultPath = "c:\Email Exports"
     For Each attachment In itm.Attachments
          attachment.SaveAsFile defaultPath & "\" & attachment.DisplayName
          Set attachment = Nothing
     Next
End Sub

...同时还能够为从中提取的每封电子邮件创建子文件夹

例如。 John Doe - 重要文件有 2 个附件。 VBA 代码将创建一个 John Doe - Important files 文件夹并在其中添加 2 个附件。

默认行为是将它们保存为单独的文件,但我希望它们按电子邮件进行组织。我偶然发现了创建部分的方法,但它总是为每个附件而不是每个电子邮件创建一个文件夹。我不确定在哪里或如何添加 createFolder 以使其对我有利。

这可以在 VBA 中完成吗?

您似乎需要在创建文件夹和遍历所有附件之前检查附件数量。

Public Sub saveAttachment(item As Outlook.MailItem)
Dim attachment As Outlook.Attachment
Dim defaultPath As String
defaultPath = "c:\Email Exports"

  If itm.Attachments.Count > 0 Then
     Dim yourPath as String = MkDir "Ex. John Doe - Important files", defaultPath
     For Each attachment In itm.Attachments
          attachment.SaveAsFile yourPath "\" & attachment.DisplayName
          Set attachment = Nothing
     Next
  End If 
End Sub

您需要检查文件夹是否存在。如果没有,那就去做吧。这个函数可以完成工作。

'requires reference to Microsoft Scripting Runtime
Function MkDir(strDir As String, strPath As String) as String

Dim fso As New FileSystemObject
Dim path As String

'examples for what are the input arguments
'strDir = "Folder"
'strPath = "C:\"

path = strPath & strDir

If Not fso.FolderExists(path) Then

' doesn't exist, so create the folder
          fso.CreateFolder path

End If

Return path

End Function

有关详细信息,请参阅 How do I use FileSystemObject in VBA?