【问题标题】:Extracting Attachments from *.msg files stored in many subfolders从存储在许多子文件夹中的 *.msg 文件中提取附件
【发布时间】:2020-06-23 15:42:38
【问题描述】:

以下代码从存储在一个文件夹中的 *.msg 文件中提取附件。

我正在寻求从存储在文件夹内许多子文件夹中的 *.msg 文件中提取附件。

主文件夹的路径是:
U:\XXXXX\XXXXX\主文件夹

子文件夹的路径是:
U:\XXXXX\XXXXX\主文件夹\Folder1
U:\XXXXX\XXXXX\主文件夹\Folder2
U:\XXXXX\XXXXX\主文件夹\Folder3
等等

Sub SaveOlAttachments()

Dim msg As Outlook.MailItem
Dim att As Outlook.Attachment
Dim strFilePath As String
Dim strAttPath As String

    'path for msgs
strFilePath = "U:\XXXXX\XXXXX\Main Folder\"
    'path for saving attachments
strAttPath = "D\Attachments\"

strFile = Dir(strFilePath & "*.msg")
Do While Len(strFile) > 0
    Set msg = Application.CreateItemFromTemplate(strFilePath & strFile)
    If msg.Attachments.Count > 0 Then
         For Each att In msg.Attachments
             att.SaveAsFile strAttPath & att.FileName
         Next
    End If
    strFile = Dir
Loop

End Sub

【问题讨论】:

标签: vba outlook subdirectory email-attachments msg


【解决方案1】:

使用我来自VBA macro that search for file in multiple subfolders的回答

Sub SaveOlAttachments()

    Dim msg As Outlook.MailItem
    Dim att As Outlook.Attachment
    Dim strFilePath As String
    Dim strAttPath As String
    Dim colFiles As New Collection, f

    'path for msgs
    strFilePath = "U:\XXXXX\XXXXX\Main Folder\"

    GetFiles strFilePath , "*.msg", True, colFiles

    'path for saving attachments
    strAttPath = "D\Attachments\"

    For Each f in colFiles
        Set msg = Application.CreateItemFromTemplate(f)
        If msg.Attachments.Count > 0 Then
             For Each att In msg.Attachments
                 att.SaveAsFile strAttPath & att.FileName
             Next
        End If
    Next

End Sub

执行搜索的子:

Sub GetFiles(StartFolder As String, Pattern As String, _
             DoSubfolders As Boolean, ByRef colFiles As Collection)

    Dim f As String, sf As String, subF As New Collection, s

    If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"

    f = Dir(StartFolder & Pattern)
    Do While Len(f) > 0
        colFiles.Add StartFolder & f
        f = Dir()
    Loop

    sf = Dir(StartFolder, vbDirectory)
    Do While Len(sf) > 0
        If sf <> "." And sf <> ".." Then
            If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
                    subF.Add StartFolder & sf
            End If
        End If
        sf = Dir()
    Loop

    For Each s In subF
        GetFiles CStr(s), Pattern, True, colFiles
    Next s

End Sub

【讨论】:

  • 非常感谢蒂姆的努力。我尝试了代码,但出现编译错误,未定义子或函数。你有什么想法吗?
  • 您是否从链接的问题中复制了GetFiles 子?我已经在上面添加了。
  • 效果惊人!非常感谢蒂姆。祝你在你的生活和事业中一切顺利。祝您有美好的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多