Search code examples
vbaoutlookemail-attachments

Outlook VBA macro not recognized


I'm having difficulty getting Outlook 2010 VBA to recognize a macro that I copied directly from the web. The macro is supposed to extract a copy of an attachment from an e-mail message and save it to a local folder. It worked several days ago, but now, when I try to run the code in VBA with (itm as Outlook.MailItem), Outlook doesn't recognize it as any kind of macro. When I take that out and leave just parentheses, it shows as a macro, but I get a 424 object required error and can't run the macro. It's damned if I do and damned if I don't.

Here's the original code:

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

saveFolder = "c:\temp\"
    For Each objAtt In itm.Attachments

        objAtt.SaveAsFile savefolder & "\" & objAtt.DisplayName

        Set objAtt = Nothing

    Next

End Sub

I've tried everything, and nothing seems to work. Any ideas?


Solution

  • Since the code includes a parameter, you need to pass that parameter by calling this procedure from another procedure. Ex:

    Sub CallMyProcedure()
    
    Dim itms As Outlook.Items
    Dim itm As Object
    
    ' loop through default Inbox items
    Set itms = Session.GetDefaultFolder(olFolderInbox).Items
    
    For Each itm In itms
      If TypeName(itm) = "MailItem" Then
        ' your code is called here
        saveAttachtoDisk itm
      End If
    Next itm
    
    End Sub
    

    This is the procedure you would need to call, and since it has no parameters you should be able to see it in the macros dialog.