Прескочи на основното съдържание

Как да запазя всички прикачени файлове от множество имейли в папка в Outlook?

Автор: Силувия Последна промяна: 2022-06-16

Лесно е да запазите всички прикачени файлове от имейл с вградената функция за запазване на всички прикачени файлове в Outlook. Ако обаче искате да запазите всички прикачени файлове от няколко имейла наведнъж, няма директна функция, която да ви помогне. Трябва многократно да прилагате функцията Запазване на всички прикачени файлове във всеки имейл, докато всички прикачени файлове бъдат запазени от тези имейли. Това отнема много време. В тази статия представяме два метода за масово запазване на всички прикачени файлове от множество имейли в конкретна папка лесно в Outlook.

Запазете всички прикачени файлове от множество имейли в папка с VBA код
Няколко кликвания за запазване на всички прикачени файлове от множество имейли в папка с невероятен инструмент


Запазете всички прикачени файлове от множество имейли в папка с VBA код

Този раздел демонстрира VBA код в ръководство стъпка по стъпка, за да ви помогне бързо да запазите всички прикачени файлове от множество имейли в конкретна папка наведнъж. Моля, направете следното.

1. Първо, трябва да създадете папка за запазване на прикачените файлове във вашия компютър.

Влезте в Документи папка и създайте папка с име „Прикачени файлове“. Вижте екранна снимка:

2. Изберете имейлите, чиито прикачени файлове ще запазите, и след това натиснете Друг + F11 за да отворите Microsoft Visual Basic за приложения прозорец.

3. кликване Поставете > Модули за да отворите Модули прозорец и след това копирайте един от следните VBA кодове в прозореца.

VBA код 1: Групово запазване на прикачени файлове от множество имейли (директно запазване на прикачени файлове със същото име)

Съвети: Този код ще запази точно същите имена на прикачени файлове чрез добавяне на цифри 1, 2, 3...след имена на файлове.

Dim GCount As Integer
Dim GFilepath As String
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
    VBA.MkDir xFolderPath
End If
GFilepath = ""
For Each xMailItem In xSelection
    Set xAttachments = xMailItem.Attachments
    xAttCount = xAttachments.Count
    xSaveFiles = ""
    If xAttCount > 0 Then
        For i = xAttCount To 1 Step -1
            GCount = 0
            xFilePath = xFolderPath & xAttachments.Item(i).FileName
            GFilepath = xFilePath
            xFilePath = FileRename(xFilePath)
            If IsEmbeddedAttachment(xAttachments.Item(i)) = False Then
                xAttachments.Item(i).SaveAsFile xFilePath
                If xMailItem.BodyFormat <> olFormatHTML Then
                    xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
                Else
                    xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
                End If
            End If
        Next i
    End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
End Sub

Function FileRename(FilePath As String) As String
Dim xPath As String
Dim xFso As FileSystemObject
On Error Resume Next
Set xFso = CreateObject("Scripting.FileSystemObject")
xPath = FilePath
FileRename = xPath
If xFso.FileExists(xPath) Then
    GCount = GCount + 1
    xPath = xFso.GetParentFolderName(GFilepath) & "\" & xFso.GetBaseName(GFilepath) & " " & GCount & "." + xFso.GetExtensionName(GFilepath)
    FileRename = FileRename(xPath)
End If
xFso = Nothing
End Function

Function IsEmbeddedAttachment(Attach As Attachment)
Dim xItem As MailItem
Dim xCid As String
Dim xID As String
Dim xHtml As String
On Error Resume Next
IsEmbeddedAttachment = False
Set xItem = Attach.Parent
If xItem.BodyFormat <> olFormatHTML Then Exit Function
xCid = ""
xCid = Attach.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F")
If xCid <> "" Then
    xHtml = xItem.HTMLBody
    xID = "cid:" & xCid
    If InStr(xHtml, xID) > 0 Then
        IsEmbeddedAttachment = True
    End If
End If
End Function
VBA код 2: Групово запазване на прикачени файлове от множество имейли (проверете за дубликати)
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String
Dim xYesNo As Integer
Dim xFlag As Boolean
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
    VBA.MkDir xFolderPath
End If
For Each xMailItem In xSelection
    Set xAttachments = xMailItem.Attachments
    xAttCount = xAttachments.Count
    xSaveFiles = ""
    If xAttCount > 0 Then
        For i = xAttCount To 1 Step -1
            xFilePath = xFolderPath & xAttachments.Item(i).FileName
            xFlag = True
            If VBA.Dir(xFilePath, 16) <> Empty Then
                xYesNo = MsgBox("The file is exists, do you want to replace it", vbYesNo + vbInformation, "Kutools for Outlook")
                If xYesNo = vbNo Then xFlag = False
            End If
            If xFlag = True Then
                xAttachments.Item(i).SaveAsFile xFilePath
                If xMailItem.BodyFormat <> olFormatHTML Then
                    xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
                Else
                    xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
                End If
            End If
        Next i
    End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
End Sub

бележки:

1) Ако искате да запазите всички прикачени файлове с едно и също име в папка, моля, приложете горното VBA код 1. Преди да стартирате този код, моля, щракнете Инструменти > Препраткии след това проверете Microsoft Scripting Runtime в полето Референции – Проект диалогов прозорец;

doc запазване на прикачени файлове07

2) Ако искате да проверите за дублиращи се имена на прикачени файлове, моля, приложете кода на VBA 2. След изпълнение на кода ще се появи диалогов прозорец, който да ви напомни дали да замените дублиращите се прикачени файлове, изберете Да or Не въз основа на вашите нужди.

5. Натисни F5 ключ за изпълнение на кода.

След това всички прикачени файлове в избрани имейли се записват в папката, която сте създали в стъпка 1. 

Забележки: Може да има Microsoft Outlook изскачащо поле за подкана, моля, щракнете върху Позволете бутон, за да продължите напред.


Запазете всички прикачени файлове от множество имейли в папка с невероятен инструмент

Ако сте начинаещ във VBA, тук силно препоръчваме Запазване на всички прикачени файлове полезност на Kutools за Outook за теб. С тази помощна програма можете бързо да запазите всички прикачени файлове от множество имейли наведнъж с няколко кликвания само в Outlook.
Преди да приложите функцията, моля първо изтеглете и инсталирайте Kutools за Outlook.

1. Изберете имейлите, съдържащи прикачените файлове, които искате да запазите.

Съвет: Можете да изберете множество несъседни имейли, като задържите Ctrl клавиш и ги изберете един по един;
Или изберете няколко съседни имейла, като задържите Превключване и изберете първия имейл и последния.

2. кликване Kutools >Инструменти за прикачванеЗапазване на всички. Вижте екранна снимка:

3. В Запазване на настройките диалогов прозорец, щракнете върху за да изберете папка за запазване на прикачените файлове и след това щракнете върху OK бутон.

3. кликване OK два пъти в следващия изскачащ диалогов прозорец, след което всички прикачени файлове в избраните имейли се записват в определена папка наведнъж.

Забележки:

  • 1. Ако искате да запазвате прикачени файлове в различни папки въз основа на имейли, моля, проверете Създайте подпапки в следния стил и изберете стил на папка от падащото меню.
  • 2. Освен запазване на всички прикачени файлове, можете да запазвате прикачени файлове по определени условия. Например, искате да запазите само прикачените файлове в pdf файл, чието име съдържа думата „Фактура“, моля, щракнете върху Разширени опции бутон, за да разширите условията, и след това конфигурирайте, както е показано на екранната снимка по-долу.
  • 3. Ако искате автоматично да запазвате прикачени файлове при получаване на имейл, Автоматично запазване на прикачени файлове функция може да помогне.
  • 4. За отделяне на прикачените файлове директно от избрани имейли, Откачете всички прикачени файлове функция на Kutools за Outlook може да ви направи услуга.

  Ако искате да имате безплатен пробен период (60 дни) на тази помощна програма, моля, щракнете, за да го изтеглитеи след това преминете към прилагане на операцията съгласно горните стъпки.


Свързани статии

Вмъкнете прикачени файлове в тялото на имейл съобщението в Outlook
Обикновено прикачените файлове се показват в полето Прикачено в съставяне на имейл. Тук този урок предоставя методи, които да ви помогнат лесно да вмъкнете прикачени файлове в тялото на имейла в Outlook.

Автоматично изтегляне/запазване на прикачени файлове от Outlook в определена папка
Най-общо казано, можете да запазите всички прикачени файлове на един имейл, като щракнете върху Прикачени файлове > Запазване на всички прикачени файлове в Outlook. Но ако трябва да запазите всички прикачени файлове от всички получени имейли и получаващи имейли, идеално ли е? Тази статия ще представи две решения за автоматично изтегляне на прикачени файлове от Outlook в определена папка.

Отпечатайте всички прикачени файлове в един/няколко имейла в Outlook
Както знаете, той ще отпечата само съдържанието на имейла, като заглавка, тяло, когато щракнете върху Файл > Печат в Microsoft Outlook, но не и прикачените файлове. Тук ще ви покажем как лесно да отпечатате всички прикачени файлове в избран имейл в Microsoft Outlook.

Търсете думи в прикачен файл (съдържание) в Outlook
Когато въвеждаме ключова дума в полето за незабавно търсене в Outlook, тя ще търси ключовата дума в темите, телата, прикачените файлове и т.н. на имейлите. Но сега просто трябва да търся ключовата дума в съдържанието на прикачения файл само в Outlook, някаква идея? Тази статия ви показва подробните стъпки за лесно търсене на думи в съдържанието на прикачени файлове в Outlook.

Съхранявайте прикачени файлове, когато отговаряте в Outlook
Когато препращаме имейл съобщение в Microsoft Outlook, оригиналните прикачени файлове в това имейл съобщение остават в препратеното съобщение. Въпреки това, когато отговорим на имейл съобщение, оригиналните прикачени файлове няма да бъдат прикачени в новото съобщение за отговор. Тук ще представим няколко трика за запазване на оригиналните прикачени файлове, когато отговаряте в Microsoft Outlook.


Най-добрите инструменти за продуктивност в офиса

Kutools за Outlook - Над 100 мощни функции, за да заредите вашия Outlook

🤖 AI Mail Assistant: Незабавни професионални имейли с AI магия - с едно щракване до гениални отговори, перфектен тон, многоезично владеене. Трансформирайте имейла без усилие! ...

📧 Автоматизиране на имейли: Извън офиса (налично за POP и IMAP)  /  График за изпращане на имейли  /  Автоматично CC/BCC по правила при изпращане на имейл  /  Автоматично пренасочване (разширени правила)   /  Автоматично добавяне на поздрав   /  Автоматично разделяне на имейлите с множество получатели на отделни съобщения ...

📨 Управление на Email: Лесно извикване на имейли  /  Блокиране на измамни имейли по теми и други  /  Изтриване на дублирани имейли  /  подробно търсене  /  Консолидиране на папки ...

📁 Прикачени файлове ProПакетно запазване  /  Партидно отделяне  /  Партиден компрес  /  Автоматично запазване   /  Автоматично отделяне  /  Автоматично компресиране ...

🌟 Магия на интерфейса: 😊 Още красиви и готини емотикони   /  Увеличете продуктивността на Outlook с изгледи с раздели  /  Минимизирайте Outlook, вместо да затваряте ...

???? Чудеса с едно кликване: Отговорете на всички с входящи прикачени файлове  /   Антифишинг имейли  /  🕘Показване на часовата зона на подателя ...

👩🏼‍🤝‍👩🏻 Контакти и календар: Групово добавяне на контакти от избрани имейли  /  Разделете група контакти на отделни групи  /  Премахнете напомнянията за рожден ден ...

Над 100 Характеристики Очаквайте вашето проучване! Щракнете тук, за да откриете повече.

 

 

Comments (81)
Rated 3.5 out of 5 · 3 ratings
This comment was minimized by the moderator on the site
Thank you for sharing the code. Unfortunately, I tried both with failure. This is what I got - The macros in this project are disabled. Please refer to the online help or documentation of the host application to determine how to enable macros. Thank you.
This comment was minimized by the moderator on the site
Hi,
Please follow the instructions in the screenshot below to check if macros are enabled in the macro settings in your Outlook. After enabling both options, re-run the VBA code.

https://www.extendoffice.com/images/stories/comments/comment-picture-zxm/macro-enabled.png
This comment was minimized by the moderator on the site
Thank you so much.
Rated 5 out of 5
This comment was minimized by the moderator on the site
Thank you for sharing VBA code. This work like magic and is going to save it lots of time!
This comment was minimized by the moderator on the site
Hello friends!

Thanks for sharing this VBA code.

Is there any way to change the location of the save folder?

I share the pc with some colleagues and in this case I need the files to be saved in a password protected folder which is not located in the documents folder.

How can I make this change?

Thank you in advance
This comment was minimized by the moderator on the site
Hi Fabiana,
Change the line 14
xFolderPath = xFolderPath & "\Attachments\"

to
xFolderPath = "C:\Users\Win10x64Test\Desktop\save attachments\1\"

Here "C:\Users\Win10x64Test\Desktop\save attachments\1\" is the folder path in my case.
Don't forget to end the folder path with a slash "\"
This comment was minimized by the moderator on the site
Hello friends!

Thank you for sharing that VBA code.

Is there any way to change the location of the save folder?

I share the pc with some colleagues and in this case I need the files to be saved in a password protected folder which is not located in the documents folder.

How can I make this change?

Thank you in advance
This comment was minimized by the moderator on the site
If you are trying to run the Code that renames duplicate files and keep getting a "User Type Not Defined" error message here is the code fixed. Instead of the "Dim xFso As FileSystemObject" on line 47 it should be "Dim xFso As Variant"
Also added a Message Box to appear at the end of data transfer.

Dim GCount As Integer
Dim GFilepath As String
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
VBA.MkDir xFolderPath
End If
GFilepath = ""
For Each xMailItem In xSelection
Set xAttachments = xMailItem.Attachments
xAttCount = xAttachments.Count
xSaveFiles = ""
If xAttCount > 0 Then
For i = xAttCount To 1 Step -1
GCount = 0
xFilePath = xFolderPath & xAttachments.Item(i).FileName
GFilepath = xFilePath
xFilePath = FileRename(xFilePath)
If IsEmbeddedAttachment(xAttachments.Item(i)) = False Then
xAttachments.Item(i).SaveAsFile xFilePath
If xMailItem.BodyFormat <> olFormatHTML Then
xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
Else
xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
End If
End If
Next i
End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
MsgBoX prompt:="File Transfer Complete", Title:="Sweatyjalapenos tha Goat"
End Sub

Function FileRename(FilePath As String) As String
Dim xPath As String
Dim xFso As Variant
On Error Resume Next
Set xFso = CreateObject("Scripting.FileSystemObject")
xPath = FilePath
FileRename = xPath
If xFso.FileExists(xPath) Then
GCount = GCount + 1
xPath = xFso.GetParentFolderName(GFilepath) & "\" & xFso.GetBaseName(GFilepath) & " " & GCount & "." + xFso.GetExtensionName(GFilepath)
FileRename = FileRename(xPath)
End If
xFso = Nothing
End Function

Function IsEmbeddedAttachment(Attach As Attachment)
Dim xItem As MailItem
Dim xCid As String
Dim xID As String
Dim xHtml As String
On Error Resume Next
IsEmbeddedAttachment = False
Set xItem = Attach.Parent
If xItem.BodyFormat <> olFormatHTML Then Exit Function
xCid = ""
xCid = Attach.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F")
If xCid <> "" Then
xHtml = xItem.HTMLBody
xID = "cid:" & xCid
If InStr(xHtml, xID) > 0 Then
IsEmbeddedAttachment = True

End If
End If
End Function
This comment was minimized by the moderator on the site
Very nice script as of 2022-10-19 works great, for me doesn't seem to change original message by adding text. The only thing I changed is I added message received date time to each file name with the following format so it would nicely sort by date time in Windows folder: "yyyy-mm-dd HH-mm-ss ".

Code:

Dim GCount As Integer
Dim GFilepath As String
Public Sub SaveAttachments()
'Update 20200821
Dim xMailItem As Outlook.MailItem
Dim xAttachments As Outlook.Attachments
Dim xSelection As Outlook.Selection
Dim i As Long
Dim xAttCount As Long
Dim xFilePath As String, xFolderPath As String, xSaveFiles As String, xDateFormat As String
On Error Resume Next
xFolderPath = CreateObject("WScript.Shell").SpecialFolders(16)
Set xSelection = Outlook.Application.ActiveExplorer.Selection
xFolderPath = xFolderPath & "\Attachments\"
If VBA.Dir(xFolderPath, vbDirectory) = vbNullString Then
VBA.MkDir xFolderPath
End If
GFilepath = ""
For Each xMailItem In xSelection
Set xAttachments = xMailItem.Attachments
xAttCount = xAttachments.Count
xSaveFiles = ""
If xAttCount > 0 Then
For i = xAttCount To 1 Step -1
GCount = 0
xDateFormat = Format(xMailItem.ReceivedTime, "yyyy-mm-dd HH-mm-ss ")
xFilePath = xFolderPath & xDateFormat & xAttachments.Item(i).FileName
GFilepath = xFilePath
xFilePath = FileRename(xFilePath)
If IsEmbeddedAttachment(xAttachments.Item(i)) = False Then
xAttachments.Item(i).SaveAsFile xFilePath
If xMailItem.BodyFormat <> olFormatHTML Then
xSaveFiles = xSaveFiles & vbCrLf & "<Error! Hyperlink reference not valid.>"
Else
xSaveFiles = xSaveFiles & "<br>" & "<a href='file://" & xFilePath & "'>" & xFilePath & "</a>"
End If
End If
Next i
End If
Next
Set xAttachments = Nothing
Set xMailItem = Nothing
Set xSelection = Nothing
End Sub

Function FileRename(FilePath As String) As String
Dim xPath As String
Dim xFso As FileSystemObject
On Error Resume Next
Set xFso = CreateObject("Scripting.FileSystemObject")
xPath = FilePath
FileRename = xPath
If xFso.FileExists(xPath) Then
GCount = GCount + 1
xPath = xFso.GetParentFolderName(GFilepath) & "\" & xFso.GetBaseName(GFilepath) & " " & GCount & "." + xFso.GetExtensionName(GFilepath)
FileRename = FileRename(xPath)
End If
xFso = Nothing
End Function

Function IsEmbeddedAttachment(Attach As Attachment)
Dim xItem As MailItem
Dim xCid As String
Dim xID As String
Dim xHtml As String
On Error Resume Next
IsEmbeddedAttachment = False
Set xItem = Attach.Parent
If xItem.BodyFormat <> olFormatHTML Then Exit Function
xCid = ""
xCid = Attach.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F")
If xCid <> "" Then
xHtml = xItem.HTMLBody
xID = "cid:" & xCid
If InStr(xHtml, xID) > 0 Then
IsEmbeddedAttachment = True
End If
End If
End Function
This comment was minimized by the moderator on the site
Hi Oigo,
This is a very useful VBA script. Thank you for sharing it.
This comment was minimized by the moderator on the site
Hi crystal,

sorry for not being clear.

I was trying to use the code above mentioned. However, apparently I was doing something wrong. I was thinking that I might need to amend some parts in the code shown. For instance the path where to save the attachments and maybe some other parts. Therefore I was asking if you could share the code highlighting the parts which needs tailoring and how to tailor them.

Many thanks,
BR
This comment was minimized by the moderator on the site
Hi Rokkie,
Did you get any error prompt when the code runs? Or which line in your code is highlighted? I need more details so I can see where you can modify the code.
This comment was minimized by the moderator on the site
Hey crystal,

completeley new to this VBA. Can you share a code to use which shows where I have to amend with an example? As a Rookie it is a bit difficult to figure it out.

I am working via a Ctrix connection. Could this be a blocker for the macro?

Much appreaciate the help.
This comment was minimized by the moderator on the site
Hi Rookie,
Sorry I don't understand what you mean: "Can you share a code to use which shows where I have to amend with an example?"
And the code operates on selected emails in Outlook, Ctrix Connection does not block the macro.
This comment was minimized by the moderator on the site
Hi, I am running this Code 1 to extract .txt files from separate sub-folders of an inbox. It works great out of one sub-folder but not at all out of another sub-folder. I have tried forwarding the relevant email and attachment into other inboxes but no luck. The files are automatically generated and sent to the different sub-folders and only vary by a single letter in their title

Any help much is appreciated
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations