PDA

View Full Version : Save Attachments



Snowman
03-09-2008, 12:37 PM
OK, I think I've got this worked out. All the code below goes into the ThisOutlookSession module. The rationale is, that you need to declare an object "WithEvents" - in this case an items collection. In the app_startup code, refer your chosen collection (in my example, the items in folder "Temp" in my personal folders) to this object. Now the Item_add event for this object will fire when a new mail arrives in that folder. Then you're free to do as you please with it!

Hope this helps
K :-)
'expose the items in the target folder to events
Dim WithEvents TargetFolderItems As Items

Private Sub Application_Startup()
'some startup code to set our "event-sensitive" items collection
Dim ns As Outlook.NameSpace

Set ns = Application.GetNamespace("MAPI")
Set TargetFolderItems = ns.Folders.Item( _
"Personal Folders").Folders.Item("Temp").Items

Set ns = Nothing

End Sub

Private Sub TargetFolderItems_ItemAdd(ByVal Item As Object)
'when a new item is added to our "watched folder" we can process it
Dim olAtt As Attachment

'you may want to run some tests on the item/attachment(s)
If Item.Attachments.Count = 1 Then
Set olAtt = Item.Attachments(1)
olAtt.SaveAsFile "C:\temp\" & olAtt.FileName
End If

'pass the filepath to the print routine
PrintAtt ("C:\temp\" & olAtt.FileName)

Set olAtt = Nothing

End Sub

Sub PrintAtt(file As String)

Dim xlApp As Object
Dim wb As Object

'in the background, create an instance of xl then open, print, quit
Set xlApp = CreateObject("Excel.Application")
Set wb = xlApp.Workbooks.Open(file)
wb.PrintOut
xlApp.Quit

'tidy up
Set wb = Nothing
Set xlApp = Nothing

End Sub
I'm using this and having a problem. The only way I can get it to work is manualy run the Application_Startup section. Also when I open Outlook I don't get the usual Enable Macro notice. Thanks for a reply.

Snowman
03-09-2008, 03:47 PM
Thanks for your help...I'm pretty new to this, hope you have patience. I've put the code in Module1 (the only module) but the "Dim WithEvents TargetFolderItems As Items" turns red. Is some of this code supposed to be in the screen for "ThisOutLookSession?

Zack Barresse
03-10-2008, 02:15 PM
Admin note: Split to new thread from here (http://www.vbaexpress.com/forum/showthread.php?p=135158#post135158).

joemeri
04-20-2008, 12:48 AM
put it all in ThisOutLookSession? this is where it has worked for me

Zack Barresse
04-26-2008, 06:47 PM
Yes, it goes in the ThisOutlookSession module.