【问题标题】:Save Outlook attachments after creating folder in local directory在本地目录中创建文件夹后保存 Outlook 附件
【发布时间】:2019-05-25 15:08:28
【问题描述】:

我正在尝试在收件箱中按名称“MacroEnabled”访问子文件夹,找到其中的所有附件并将它们保存到本地驱动器。

我使用此代码创建一个名为“文档”的文件夹并保存附件。但是,在进行第二次迭代时,它说文件已经存在错误“58”。

    Dim ns As NameSpace
    Dim olFolder_Inbox As Folder
    Dim olMail As MailItem
    Dim olAttachment As Attachment
    Dim FolderPath As String
    Dim fso As Object
    Dim File_Saved As String
    
    'email service type
    Set ns = GetNamespace("MAPI")
    Set olFolder_Inbox = ns.GetDefaultFolder(olFolderInbox).Folders("MacroEnabled")

    Set fso = CreateObject("Scripting.FileSystemObject")
    FolderPath = "Documents"
    For Each olMail In olFolder_Inbox.Items

        If TypeName(olMail) = "MailItem" And olMail.Attachments.Count > 0 Then
            fso.CreateFolder ("Documents")
            
            For Each olAttachment In olMail.Attachments
            
                olAttachment.SaveAsFile fso.BuildPath(FolderPath, olAttachment.FileName)
                
            Next olAttachment

        End If
    
    Next olMail

    Set ns = Nothing
    Set fso = Nothing

End Sub

【问题讨论】:

  • 看起来您的代码不断尝试重新创建Documents 文件夹?所以你可能需要先检查它是否存在,至少假设它在你第一次创建它之后就存在。
  • 您可以使用FolderExists method 进行检查。
  • 如果两个附件名称相同,则同样适用于附件。

标签: vba outlook


【解决方案1】:

首先FolderPath 应该显示整个路径,例如。 FolderPath = "C:\Documents" 如果需要,可以使用相对路径,例如 FolderPath = CurrentProject.Path & "\Documents" 然后您可以通过添加以下指令在循环中使用 FolderExisits 方法:

If Not fso.FolderExists(FolderPath) Then fso.CreateFolder (FolderPath )

【讨论】:

    【解决方案2】:

    For Each olMail In olFolder_Inbox.Items fso.CreateFolder ("Documents_path")

    查看这个并尝试在创建另一个文件夹之前检查文件夹 Documents 是否存在

    【讨论】:

    • 你有编写代码的知识,却不知道为什么它会创建许多处于循环中的文件夹,这很奇怪:) 添加:If(Not System.IO.Directory.Exists([the_documents_path])) Then
    • 我有其他编程语言的经验,但从来没有足够的机会接触 vb。但仍在努力做我能做的:-)
    • 祝你好运:)
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多