Alex Zel
Alex Zel

Reputation: 688

VBA script not saving first mail

first of all i'll say that i'm not an expert in coding but i do have a basic understanding. i have a script that saves all unread mails as txt and marks them as read. It works fine, but when i set up a rule with it to run every time i get a mail from a specific person it doesn't effect the first mail. Example: i get a mail, the script runs but doesn't save anything (as long as there is no other mail from the same person and isn't Unread). then i get a second mail from the same person, the script will run and save the previous mail but not the latest one.

Here a sample of the code:

Public Sub TestEnvMacro()
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objMailbox = objNamespace.Folders("your email goes here")
Set objFolder = objMailbox.Folders("Inbox")
Set colItems = objFolder.Items

Dim NewMsg
Dim dtDate As Date
Dim sName As String

Const OLTXT = 0

Pause (5)

For Each objMessage In colItems.Restrict("[Unread] = True")
      If objMessage.UnRead = True Then
         Pause (5)
         Set NewMsg = objMessage
         sName = NewMsg
         dtDate = NewMsg.ReceivedTime
         sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
         vbUseSystem) & Format(dtDate, "-hhnnss", _
         vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & ".txt"

         NewMsg.SaveAs "G:\" & sName, OLTXT
         NewMsg.UnRead = False
    End If
Next

End Sub

I didn't include the pause Sub since it's pretty self explanatory what it does, also i've had a problem with getting the script to show up in the "Rules" so I added this Sub:

Public Sub SaveAsTextMod(msg As MailItem)
Dim strID As String
Dim olNS As NameSpace
Dim olMail As MailItem
strID = msg.EntryID

Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)

Call TestEnvMacro

Set olMail = Nothing
Set olNS = Nothing

End Sub

Upvotes: 0

Views: 127

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49455

When you create a rule to apply for incoming emails, the mail item is passed as a parameter to the macro sub. There is no need to search for unread emails in Outlook. You just need to define the function with a MailItem parameter do the required actions against that objects.

Public Sub SaveAsTextMod(msg As MailItem)

    Dim dtDate As Date
    Dim sName As String

     dtDate = msg.ReceivedTime
     sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
     vbUseSystem) & Format(dtDate, "-hhnnss", _
     vbUseSystemDayOfWeek, vbUseSystem) & "-" & msg.Subject & ".txt"

     msg.SaveAs "G:\" & sName, OLTXT
     msg.UnRead = False

End Sub

You may find the Getting Started with VBA in Outlook 2010 article helpful.

Upvotes: 1

Related Questions