How to save attachments and rename it

感情迁移 提交于 2020-01-16 02:52:47

问题


I am having an issue getting my code to work. This is my first time running a VBA script. I have a large amount of emails coming in from a fax machine and I want to be able to download the attachments, rename the file to the subject line and then store them on my computer.

My first attempt, I tried to just write a macro so that I could manually do it but after doing some research, I was under the impression that I wanted to make rules work.

This is my first attempt at VBA so I'm not even sure I am running the macro or rule script correctly but I have a feeling I am just missing something in the code. Any thoughts?

Public Sub saveAttachtoDiskRule(itm As Outlook.MailItem)

    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    Dim fso As Object
    Dim oldName

    Dim file As String
    Dim DateFormat As String
    Dim newName As String

    Dim enviro As String
    enviro = CStr(Environ("USERPROFILE"))
    saveFolder = enviro & "\" & "\destinationfolder\"

    Set fso = CreateObject("Scripting.FileSystemObject")

     For Each objAtt In itm.Attachments
     file = saveFolder & objAtt.DisplayName
     objAtt.SaveAsFile file

     Set oldName = fso.GetFile(file)
     newName = itm.Subject
     oldName.Name = newName

     Set objAtt = Nothing
     Next

     Set fso = Nothing
End Sub

回答1:


Here is simple rule script

Public Sub saveAttachtoDisk(olItem As Outlook.MailItem)
    Dim olAttachment As Outlook.Attachment
    Dim SaveFolder As String

    SaveFolder = "c:\temp\"

    For Each olAttachment In olItem.Attachments
        olAttachment.SaveAsFile SaveFolder & "\" & olAttachment.DisplayName
        Set olAttachment = Nothing
    Next
End Sub

Environ Function

The Environ function lets you get the Windows environment variables for the computer your code is currently running on, Like user name or the name of the temporary folder

Examples

user's profile folder example is

Environ("USERPROFILE") & "\Documents\Temp\"
result
Windows Vista/7/8:  C:\Users\Omar\
Windows XP:         C:\Documents and Settings\Omar\

"All Users" or "Common" profile folder

Environ("ALLUSERSPROFILE")

Temporary folder example is

Environ("TEMP") (or Environ("TMP") - is the same)
result: C:\Users\omar\AppData\Local\Temp


来源:https://stackoverflow.com/questions/31820485/how-to-save-attachments-and-rename-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!