Code to download attachment from Outlook, save it on desktop and open it

*爱你&永不变心* 提交于 2019-12-23 04:45:54

问题


This is the code in Outlook that sets the rules in Outlook automatically to save the attachment (Excel) with date stamp:

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
Dim dateFormat

    dateFormat = Format(Now, "yyyy-mm-dd H-mm")
    saveFolder = "c:\Users\abc1\Desktop\"
   For Each objAtt In itm.Attachments
      objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
      Set objAtt = Nothing
 Next

End Sub

Next step I want is to open the attachment once it's saved. Is that possible?

How about this one?

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
  Dim objAtt As Outlook.Attachment
  Dim saveFolder As String
  Dim dateFormat

      dateFormat = Format(Now, "yyyy-mm-dd H-mm")
      saveFolder = "c:\Users\abc1\Desktop\"
     For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
        Set objAtt = Nothing
   Next


Dim Shex As Object
   Set Shex = CreateObject("Shell.Application")
   tgtfile = "objatt"
   Shex.Open (tgtfile)

End Sub


回答1:


Yes, it is possible. If you know exactly that you need to open Excel files you may use the Excel object model to get the job done. See How to automate Microsoft Excel from Visual Basic for more information. The Open method of the Workbooks class opens a workbook.




回答2:


Try this:

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)

    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    Dim dateFormat, FilePath As String

    dateFormat = Format(Now, "yyyy-mm-dd H-mm")
    saveFolder = "c:\Users\abc1\Desktop" '<<EDIT removed trailing \
    For Each objAtt In itm.Attachments
      FilePath = saveFolder & "\" & dateFormat & _
                  " " & objAtt.DisplayName
      objAtt.SaveAsFile FilePath
      runit FilePath
    Next

End Sub

Sub runit(FilePath as String)
   Dim Shex As Object
   Set Shex = CreateObject("Shell.Application")
   Shex.Open (FilePath)
End Sub

'Edit: I used this to test the code, since I'm not running
'      it from a rule
Sub Tester()

    Dim Msg As MailItem

    Set Msg = Application.ActiveInspector.CurrentItem

    saveAttachtoDisk Msg

End Sub


来源:https://stackoverflow.com/questions/29926201/code-to-download-attachment-from-outlook-save-it-on-desktop-and-open-it

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