Set custom value when item moved to folder in outlook - vba

I'm looking to set a Date on a field anytime an email is moved into a specific folder.
the field is custom called "Completed Date".
Could I get a little help on VBA code to set a custom field (date) when an item is moved into a folder (folder name is "Completed").
I'm ultimately looking to report on the time an item (custom form email) was received to the time it was completed (as per the action of moving the email to a completed folder.
Very rudimentary ticketing system, I'm very aware :) .
thanks,
A

Use ItemAdd http://www.outlookcode.com/article.aspx?id=62 where you reference the "Completed" folder.
Combine it with code like this http://www.vbaexpress.com/forum/showthread.php?5738-Need-to-Add-a-Userdefined-Property-to-Mail-Items
SAMPLE CODE
Change it so you do not update all items in the folder just the one item that triggered ItemAdd.
Option Explicit
Sub AddAUserDefinedProperty()
Dim olApplication As Outlook.Application
Dim olNameSpace As Outlook.NameSpace
Dim olFolder As Outlook.MAPIFolder
Dim olItem As Object
Dim strDomain As String
Dim olProperty As Outlook.UserProperty
Set olApplication = New Outlook.Application
Set olNameSpace = olApplication.GetNamespace("Mapi")
Set olFolder = olNameSpace.GetDefaultFolder(olFolderJunk)
For Each olItem In olFolder.Items
strDomain = Mid(olItem.SenderEmailAddress, _
InStr(1, olItem.SenderEmailAddress, "#") + 1)
Set olProperty = olItem.UserProperties.Add("Domain", olText)
olProperty.Value = strDomain
Debug.Print olItem.SenderEmailAddress, olProperty.Value
olItem.Save
Next olItem
Set olApplication = Nothing
Set olNameSpace = Nothing
Set olFolder = Nothing
Set olProperty = Nothing
End Sub
Even more reference material here http://www.codeproject.com/Articles/427913/Using-User-Defined-Fields-in-Outlook

Related

Macro to export excel email IDs to outlook distribution list

Is there a way to write a macro that exports the email ID column from excel sheet to outlook distribution list?
I would ideally want to replace the old one with new distribution list every time, the macro is run.
The following is what I have been trying,
Public Sub DistributionList()
Dim objOutlook As New Outlook.Application
Dim objNameSpace As Outlook.Namespace
Dim objDistList As Outlook.DistListItem
Dim objMail As Outlook.MailItem
Dim objRecipients As Outlook.Recipients
Set objNameSpace = objOutlook.GetNamespace("MAPI")
Set objDistList = objOutlook.CreateItem(olDistributionListItem)
Set objMail = objOutlook.CreateItem(olMailItem)
Set objRecipients = objMail.Recipients
objDistList.DLName = InputBox("Enter name of Distribution List")
For i = 1 To Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
objRecipients.Add (Range("C" & i).Value)
Next i
objDistList.AddMembers objRecipients
objDistList.Display
objRecipients.ResolveAll
Set objOutlook = Nothing
Set objNameSpace = Nothing
Set objDistList = Nothing
Set objMail = Nothing
Set objRecipients = Nothing
End Sub
But while running this, I am getting an error, user defined type not defined.
Can this be corrected or is there a better way to do this?
Can anybody help me in doing this? Thanks
The user defined type not defined error almost always means that you've forgotten to add a reference. Go under tools>> references to add it. In your case you need the Outlook library.
To change which column it's finding the names, change
Range("C"
To refer to the column containing the names.

Getting an EntryID after an object is moved

Summary
I'm trying to add hyperlinks to tasks created from emails that I have moved to another folder.
The goal is to have the task contain a hyperlink to the Outlook item that was moved to a "Processed Email" folder".
Problem
I don't understand how to move a MailItem and then get its new EntryID after it moves.
The "naive" way doesn't work. After using the Move method to move a MailItem object, the EntryID property does not reflect a change in ID.
Details
Creating a hyperlink to an Outlook item using the format outlook:<EntryID> is easy enough if the Outlook item remains in the Inbox, since I can just get the EntryID of the object that I am linking to. However, Outlook changes the EntryID when an object is moved.
I want to understand how to get the updated ID so that I can construct an accurate link.
Example
The message boxes show the EntryID property of objMail returns the same value despite the fact that the object has moved. However, running a separate macro on the mail in the destination folder confirms that the EntryID has changed with the move.
Sub MoveObject(objItem As Object)
Select Case objItem.Class
Case olMail
Dim objMail As MailItem
Set objMail = objItem
MsgBox (objMail.EntryID)
Dim inBox As Outlook.MAPIFolder
Set inBox = Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)
Dim destFolder As Outlook.MAPIFolder
Set destFolder = inBox.Folders("Processed Email")
If (Application.ActiveExplorer().CurrentFolder.Name <> destFolder.Name) Then
objMail.Move destFolder
End If
MsgBox (objMail.EntryID)
End Select
End Sub
The Move method of the MailItem class returns an object that represents the item which has been moved to the designated folder. You need to check out the EntryID value of the returned object, not the source one.
Anyway, you may consider handling the ItemAdd event of the target folder to make sure that an updated entry ID value is used all the time.
Sub MoveItems()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Personal Mail")
Set myItem = myItems.Find("[SenderName] = 'Eugene Astafiev'")
While TypeName(myItem) <> "Nothing"
myItem.Move myDestFolder
Set myItem = myItems.FindNext
Wend
End Sub
Hello can you please elaborate your answer I am not able to understand it.
Anyway, you may consider handling the ItemAdd event of the target folder to make sure that an updated entry ID value is used all the time.
Here is my code and I need EntryID after moving.
Sub Movetest1()
Dim olApp As Outlook.Application
Dim olns As Outlook.NameSpace
Dim Fld As Folder
Dim ofSubO As Outlook.MAPIFolder
Dim myDestFolder As Outlook.Folder
Dim ofolders As Outlook.Folders
Dim objItems As Outlook.Items
Dim myRestrictItems As Outlook.Items
Dim i As Long
Dim myitem As Object
' Dim MailItem As Microsoft.Office.Interop.Outlook.MailItem
Dim MailItem, moveditem As Outlook.MailItem
Dim eid As String
Dim sid As Variant
Dim newEID As String
'---------------------------------------------------------------------------------------------------------
Set olApp = New Outlook.Application
Set olns = olApp.GetNamespace("MAPI")
For Each Fld In olns.Folders
If Fld.Name = "GSS Payables" Then
'
' MsgBox Fld.Name
' Debug.Print " - "; Fld.EntryID
Set Fld = olns.GetFolderFromID("000000009DA6D76FBE7A58489450CDF6094F592A0100A2457DC435B22448A832DB721D8185B1000000B6207D0000").Folders("Inbox")
Exit For
End If
Next
Set objItems = Fld.Items
eid = "000000009DA6D76FBE7A58489450CDF6094F592A0700A2457DC435B22448A832DB721D8185B1000000B620800000A2457DC435B22448A832DB721D8185B100007FF773270000"
sid = "000000009DA6D76FBE7A58489450CDF6094F592A0100A2457DC435B22448A832DB721D8185B1000000B6207D0000"
Set myDestFolder = Fld.Folders("Bhagyashri")
'Set myitem = objItems.Find("[SenderName]='Microsoft Outlook '")
Set MailItem = olns.GetItemFromID(eid)
Set moveditem = MailItem.Move(myDestFolder)
"giving error here
newID = moveditem.entryid
Debug.Print "newID -"; newID
' get mailitem.parent.storeid
MsgBox "done"
End
Use the following syntax:
Dim MoveToFolder As outlook.MAPIFolder
Dim MyItem As outlook.MailItem
Dim NewEntryID As String
NewEntryID = MyItem.Move(MoveToFolder).ENTRYID
After MyItem.Move is executed the new ENTRYID will be returned to the NewEntryID variable.

Scope using AdvancedSearch method for entire mailbox

I am trying to look through all Outlook folders for mail items matching certain parameters to save the attachment, from Excel.
I don't know how to reference scope to go through all folders, even custom folders.
I can't find the resources that answer my question.
Sub testing()
Dim myOlApp As New Outlook.Application
Dim scope As String
Dim filter As String
Dim rsts As Results
Dim AdvancedSearch As Outlook.Search
blnSearchComp = False
'I want it to search the entire mail account including normal folders like inbox and sent as well as custom folders.
'but this doesn't work. Any ideas?
scope = "'Fakeexample123#outlook.com'"
'filter assignment statement has been excluded
Set AdvancedSearch = myOlApp.AdvancedSearch(scope, filter, True, "test")
While blnSearchComp <> True
If AdvancedSearch.Results.Count > 0 Then
blnSearchComp = True
End If
Wend
Set rsts = AdvancedSearch.Results
For x = rsts.Count To 1 Step -1
rsts.Attachment.Item(x).SaveAsFile Project
Next
End Sub
Scope should be
'\\Fakeexample123#outlook.com'
Sub Demo_scopeformat()
Dim myOlApp As New outlook.Application
Dim scope As String
' Mailbox
scope = "'" & myOlApp.Session.GetDefaultFolder(olFolderInbox).Parent.folderPath & "'"
' Expected format
Debug.Print scope
End Sub
Well, I know it isn't the best solution, but I have come up with the following code to make a list of all of the parent folders, so that a for loop can be used with advanced search method to iterate the list. This will not be the fastest possible code, but should not be too slow.
Sub main()
'establishes connections
Dim myOlApp As New Outlook.Application
Dim objNS As Outlook.Namespace
Dim myFolder As Outlook.MAPIFolder
Set objNS = myOlApp.GetNamespace("MAPI")
'pick highest folder level as original my folder
Set myFolder = objNS.Folders("faxe.example123#outlook.com")
Call ProcessFolders(myFolder)
End Sub
Sub ProcessFolders(myFolder)
're establish connections
Dim myOlApp As New Outlook.Application
Dim objNS As Outlook.Namespace
Dim objFolder As Outlook.MAPIFolder
Set objNS = myOlApp.GetNamespace("MAPI")
'set up collection
Set x = New Collection
For Each objFolder In myFolder.Folders
'add all parent folder names to collection
'advanced search method will handle subfolders
'can use a recursive call here also to get subfolders though
x.Add objFolder.Name
Next
Set objNS = Nothing
Set myFolder = Nothing
Set myOlApp = Nothing
End Sub

Error trying to save email attachment

I try to write some VBA to save the attachment files from some email to a folder
But I get the error
Run Time Error '424'
Object Required
This is the code I am trying to use
Sub test_extraer()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
If (Msg.SenderName = "sender#email.com") And _
(Msg.Subject = "subject of the email") And _
(Msg.Attachments.Count >= 1) Then
'Set folder to save in.
Dim olDestFldr As Outlook.MAPIFolder
Dim myAttachments As Outlook.Attachments
Dim Att As String
Const attPath As String = "C:\temp\"
Set myAttachments = item.Attachments
Att = myAttachments.item(1).DisplayName
myAttachments.item(1).SaveAsFile attPath & Att
End If
End Sub
The error is triggered when the script enter to this if
If (Msg.SenderName = "sender#email.com") And _
(Msg.Subject = "subject of the email") And _
(Msg.Attachments.Count >= 1) Then
Any advice
Thanks in advance
Ok... where to start.
You definitely have some basic issues you need to work out here. You have a couple of variables that are not declared. The first of which is the cause of your title. msg in context is most likely supposed to be an Outlook.MailItem. Just declaring that variable is not the sole source of your problems. Next you have item which much like msg in context should be an Outlook.MailItem. You are missing a loop that would navigate through all the items in the Inbox as well.
So you are just trying to navigate the Inbox looking for a particular item correct? Just adding the loop would create another issue. Some of the items in the inbox are not mail items. To address this we navigate every object in the inbox and examine every mailitem we come across. If that matches the criteria of sender,subject and number of items we proceed to .SaveAsFile to the destination directory.
Sub Test_ExtraER()
Const strAttachmentPath As String = "C:\temp\"
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim objFolder As Outlook.MAPIFolder
Dim objItem As Object
Dim strFileName As String
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set objFolder = objNS.GetDefaultFolder(olFolderInbox)
For Each objItem In objFolder.Items
If TypeName(objItem) = "MailItem" Then
If (objItem.Attachments.Count >= 1) And (objItem.Subject = "Some Subject") And (objItem.SenderName = "sender#email.com") Then
With objItem.Attachments.Item(1)
strFileName = strAttachmentPath & .DisplayName
Debug.Print strFileName
.SaveAsFile strFileName
End With
End If
End If
Next
End Sub
This is mostly preference but, as you can see, I made some other coding changes. I renamed some of the other variables to be a little more descriptive of the object it was. Also moved all the Dims and Const together for better readability.
One last thing. It would seem you are navigating you entire inbox looking for a small subset of mails. You could create a rule that would process these mails as they come into your mailbox. An example of this would be: Save Outlook attachment to disk
Sub test_extraer()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim MailItems As Outlook.MAPIFolder 'Add this one
Dim Msg As Outlook.MailItem 'Add this one
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
Set MailItems = objNS.GetDefaultFolder(olFolderInbox)
For Each Msg In MailItems.Items 'loop thru the inbox folder to match the exact sender name and subject
If (Msg.SenderName = "Sender Name Here") And _
(Msg.Subject = "Subject Here") And _
(Msg.Attachments.Count >= 1) Then
'Set folder to save in.
Dim olDestFldr As Outlook.MAPIFolder
Dim myAttachments As Outlook.Attachments
Dim Att As String
Const attPath As String = "C:\temp\"
Set myAttachments = Msg.Attachments
Att = myAttachments.Item(1).DisplayName
myAttachments.Item(1).SaveAsFile attPath & Att
End If
Next
End Sub

Loop Through PSTs in Outlook 2003 with VBA

In Outlook 2007, I am able to loop through mails stores, including PSTs, using code like this:
Dim stores As Outlook.stores
Set stores = objNamespace.stores
Dim store As Outlook.store
For Each store In stores
MsgBox store.FilePath
Next
However, in Outlook 2003, the Outlook.store and Outlook.stores objects do not exist.
Are there equivalent objects in Outlook 2003?
What other method might I use to loop through mail stores?
Thank you.
This sample code for Outlook 2003 will loop through the high level mailboxes and print certain properties to the Immediate Window. I chose the properties that looked most useful based on your request.
Sub LoopThruMailboxes()
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim mailboxCount As Long
Dim i As Long
Dim folder As Outlook.MAPIFolder
' get local namespace
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
mailboxCount = olNS.Folders.count
For i = 1 To mailboxCount
Set folder = olNS.Folders(i)
Debug.Print folder.EntryID
Debug.Print folder.StoreID
Debug.Print folder.Name
Debug.Print folder.FolderPath
Next i
End Sub
folder.Name is the name of the mailbox, folder.StoreID is the store ID (I'm not sure what you meant by "store file path", I didn't see anything that looked relevant anyway).
Here's a functionized version that returns folder name and store ID as an array, which you could assign directly to a listbox:
Function GetMailBoxInfo() As String()
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim mailboxCount As Long
Dim i As Long
Dim folder As Outlook.MAPIFolder
Dim tempString() As String
' get local namespace
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
mailboxCount = olNS.Folders.count
' size array accordingly
ReDim tempString(1 To mailboxCount, 1 To 2)
For i = 1 To mailboxCount
Set folder = olNS.Folders(i)
tempString(i, 1) = folder.Name
tempString(i, 2) = folder.StoreID
Next i
GetMailBoxInfo = tempString
End Function
ex:
ListBox1.List = GetMailBoxInfo