如何保存附件并重命名

时间:2015-08-04 22:30:59

标签: vba outlook outlook-vba

我遇到了使代码生效的问题。这是我第一次运行VBA脚本。我从传真机收到大量电子邮件,我希望能够下载附件,将文件重命名为主题行,然后将其存储在我的计算机上。

我的第一次尝试,我试着写一个宏,以便我可以手动完成它,但经过一些研究后,我的印象是我想让规则起作用。

这是我在VBA的第一次尝试,所以我甚至不确定我是否正确运行宏或规则脚本,但我有一种感觉,我只是在代码中遗漏了一些东西。有什么想法吗?

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 个答案:

答案 0 :(得分:1)

这是简单的规则脚本

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

Environ功能可让您获取当前运行代码的计算机的Windows环境变量,例如user nametemporary folder的名称

实施例

用户的个人资料文件夹示例是

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

“所有用户”或“常用”个人资料文件夹

Environ("ALLUSERSPROFILE")

临时文件夹示例是

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