Reply to last email from specific sender in Excel - excel

In Excel, I am looking up the email address of a person, and then I want to find the last email (send or received) and trigger a reply to this email. This reply is triggered by a button in Excel.
Dim a As Integer
Dim objOutlook As Object
Dim objMail As Object
Dim rngBody As Range
Dim rngAttach As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)
EmailStr = "sombody#gmail.com" (dummy replacement for my find the email adress in excel spreadsheet
then I would need to find emails to/from this address in my outlook, and then reply to the latest one.
What I did manage is start a new email to this person, but no idea how to find and reply
With objMail
.To = EmailStr
.CC = AMEmail
.Subject = TitleMail
.HTMLBody = BodyStr & Signature
.ReadReceiptRequested = True
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
Set objOutlook = Nothing
Set objMail = Nothing
Set rngBody = Nothing
Set rngAttach = Nothing
Update: still struggling, but no more crashes for now. Wher I am stuck now it here:
Private Sub CommandButton2_Click()
Dim olApp As Object
Dim olNs As Object
Dim olFldr As Object
Dim olItems As Object
Dim olItemReply As Object
Dim i As Long
Dim emailStr As String
Dim filter As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(6) ' olFolderInbox
Debug.Print "olFldr: " & olFldr
emailStr = "sombody#gmail.com" '(email address in Excel spreadsheet)
Debug.Print "emailStr: " & emailStr
Set olItems = olFldr.Items
Debug.Print olItems.Count
'finds all 19 items in my inbox with msgbox(olItems.count)
filter = "[SenderEmailAddress] = '" & emailStr & "'"
Debug.Print filter
Set olItems = olFldr.Items.Restrict(filter)
Debug.Print olItems.Count
'finds 0 items now ??? why....
End sub

This demonstrates how to create a searchfolder of items received from an email address.
Option Explicit ' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Private Sub mailFromEmailAddress()
' Early binding
' Requires reference to Microsoft Outlook XX.X Object Library
Dim objOutlook As Outlook.Application
Dim strSearch As String
Dim strDASLFilter As String
Dim strDASLFilter_option As String
Dim strScope As String
Dim strScopeEdit As String
Dim objSearch As Search
Dim fldrNm As String
strSearch = "someone#internet.com"
Set objOutlook = CreateObject("Outlook.Application")
' create a searchfolder
Debug.Print
'strScope = "'Inbox', 'Deleted'"
strScope = "'Inbox'"
Debug.Print "strSearch...........: " & strSearch
' https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2007/aa579702(v=exchg.80)
' ***** use "fromemail" for "senderemailaddress" *****
strDASLFilter_option = "fromemail"
Debug.Print "strDASLFilter_option: " & strDASLFilter_option
'fldrNm = strDASLFilter_option & " " & strSearch
fldrNm = strSearch
Debug.Print "fldrNm..............: " & fldrNm
'strDASLFilter = "urn:schemas:httpmail:" & strDASLFilter_option & " LIKE '%" & strSearch & "%'"
strDASLFilter = "urn:schemas:httpmail:" & strDASLFilter_option & " LIKE '" & strSearch & "'"
Debug.Print "strDASLFilter.......: " & strDASLFilter
Debug.Print "strScope............: " & strScope
Set objSearch = objOutlook.AdvancedSearch(scope:=strScope, filter:=strDASLFilter, SearchSubFolders:=True, Tag:="SearchFolder")
Debug.Print fldrNm
'Save the search results to a searchfolder
objSearch.Save fldrNm
Debug.Print fldrNm & " saved."
' Question 2
' Reference the saved searchfolder
' https://stackoverflow.com/questions/55363286/how-do-you-set-a-folder-variable-for-a-search-folder
' Question 3
' Sort the collection of items in the searchfolder
' Reply to most recent and appropriate item
End Sub

To reply to most recently received mailitem in known folder.
Option Explicit' Consider this mandatory
' Tools | Options | Editor tab
' Require Variable Declaration
' If desperate declare as Variant
Private Sub replyToSenderEmailAddress()
' Reply to most recently received mailitem in specified folder
' Late binding - reference to Outlook Object Library not required
Dim olApp As Object
Dim olNs As Object
Dim olFldr As Object
Dim olItems As Object
Dim olItemReply As Object
Dim i As Long
Dim emailStr As String
Dim filter As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(6) ' olFolderInbox
Debug.Print "olFldr: " & olFldr
emailStr = "sombody#gmail.com" '(email address in Excel spreadsheet)
Debug.Print "emailStr: " & emailStr
Set olItems = olFldr.Items
Debug.Print olItems.Count
filter = "[SenderEmailAddress] = '" & emailStr & "'"
Debug.Print filter
Set olItems = olFldr.Items.Restrict(filter)
Debug.Print olItems.Count
olItems.Sort "[ReceivedTime]", True
For i = 1 To olItems.Count
Debug.Print olItems(i).ReceivedTime
If olItems(i).Class = 43 Then
Set olItemReply = olItems(i).Reply
olItemReply.Display
Exit For
End If
Next
End Sub

Related

VBA to search and reply in Outlook with specific criteria

I am Using windows 10, Excel 2013 and Outlook 2013
I am new to Macro. I need macro to perform below Task:
1) From Excel I want to open Outlook if Outlook is closed and move Point.2, If outlook is already open then move to Point.2
2) Search for a specific email in outlook in all folders and sub folders with criteria “A” and “B”
a) Latest dated received or sent email.
b) With specific Subject contains “Approved”, this to be taken from active cell.
3) Open the found latest mail as per above criteria do “Reply all”.
4) Write a comment and display the mail or send.
Below code was my start, but it has the following issues:
The code search for the exact name, while i need to search for any email contain the word which in active cell.
The code search only in sent emails, while i need to search in both inbox and sent.
The code just open the email, i need to write template comment as well.
Many thanks in advance.
Sub ReplyMail_No_Movements()
' Outlook's constant
Const olFolderSentMail = 5
' Variables
Dim OutlookApp As Object
Dim IsOutlookCreated As Boolean
Dim sFilter As String, sSubject As String
' Get/create outlook object
On Error Resume Next
Set OutlookApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlookApp = CreateObject("Outlook.Application")
IsOutlookCreated = True
End If
On Error GoTo 0
' Restrict items
sSubject = ActiveCell.Value
sFilter = "[Subject] = '" & sSubject & "'"
' Main
With OutlookApp.Session.GetDefaultFolder(olFolderSentMail).Items.Restrict(sFilter)
If .Count > 0 Then
.Sort "ReceivedTime", True
With .Item(1).replyall
.Display
'.Send
End With
Else
MsgBox "No emails found with Subject:" & vbLf & "'" & sSubject & "'"
End If
End With
' Quit Outlook instance if it was created by this code
If IsOutlookCreated Then
OutlookApp.Quit
Set OutlookApp = Nothing
End If
End Sub
It seems work now:
Sub ReplyAllLastEmailFromInboxAndSent()
Dim olApp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim objMail As Object
Dim objReplyToThisMail As MailItem
Dim lngCount As Long
Dim objConversation As Conversation
Dim objTable As Table
Dim objVar As Variant
Dim strBody As String
Dim searchFolderName As String
Set olApp = Session.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderSentMail)
searchFolderName = "'" & Outlook.Session.GetDefaultFolder(olFolderInbox).FolderPath & "','" & Outlook.Session.GetDefaultFolder(olFolderSentMail).FolderPath & "'"
lngCount = 1
For Each objMail In Fldr.Items
If TypeName(objMail) = "MailItem" Then
If InStr(objMail.Subject, ActiveCell.Value) <> 0 Then
Set objConversation = objMail.GetConversation
Set objTable = objConversation.GetTable
objVar = objTable.GetArray(objTable.GetRowCount)
Set objReplyToThisMail = olApp.Session.GetItemFromID(objVar(UBound(objVar), 0))
With objReplyToThisMail.replyall
strBody = "Dear " & "<br>" & _
"<p>Following up with the below. May you please advise?" & _
"<p>Thank you," & vbCrLf
.HTMLBody = strBody & .HTMLBody
.Display
End With
Exit For
End If
End If
Next objMail
Set olApp = Nothing
Set olNs = Nothing
Set Fldr = Nothing
Set objMail = Nothing
Set objReplyToThisMail = Nothing
lngCount = Empty
Set objConversation = Nothing
Set objTable = Nothing
If IsArray(objVar) Then Erase objVar
End Sub

Return individual sender of archived mail for a shared mailbox

I have written a macro which pulls the emails from the 'Sent Items' of a particular mailbox in Outlook. I am using .SenderName property to populate senders name in Excel.
The mailbox is shared by a team, and is labeled as 'ResearchHub'.
The macro is working when I pull out mails for recent days.
When I try to draw the archived mails, the .SenderName property pulls out the sender as 'ResearchHub', not the person who sent the mail.
MailItem.SentOnBehalfOfName property is pulling Research Hub as the sender and not the individual name.
I tried unarchiving the emails by opening them and copying them in a different folder, yet was unsuccessful in fetching the particular user as sender name.
Option Explicit
Sub test()
Dim Result As Object
Dim i As Integer
Dim dstart As Date
Dim dend As Date
Dim lower As String
Dim upper As String
Dim limit As String
dstart = InputBox("Enter Start Date in dd/mmm/yyyy format")
dend = InputBox("Enter End Date in dd/mmm/yyyy format")
lower = "[ReceivedTime] > '" & Format(dstart, "ddddd") & " 12:00 AM" & "'"
upper = "[ReceivedTime] > '" & Format(dend, "ddddd") & " 12:00 AM" & "'"
limit = lower & " AND " & upper
Dim objoutlook As outlook.Application
Dim oStore As outlook.Store
Dim onjNSpace As outlook.Namespace
Dim objFolder As outlook.Folder
Dim oAccount As Account
Set objoutlook = CreateObject("Outlook.Application")
Set objNSpace = objoutlook.GetNamespace("MAPI")
For Each objFolder In objNSpace.Folders
If objFolder.Name = "Research Hub" Then
Dim myfolder As outlook.Folder
Set myfolder = objFolder.Folders("Sent Items")
Dim objitem As Object
Dim irow As Integer
irow = 2
Set Result = myfolder.Items.Restrict(limit)
If Result.Couunt > 0 Then
For i = 1 To Result.Count
Cells(irow, 1) = objitem.SenderName
Cells(irow, 2) = objitem.To
Cells(irow, 3) = objitem.Subject
irow = irow + 1
Next i
End If
End If
Next
Set objoutlook = Nothing
Set objNSpace = Nothing
Set myfolder = Nothing
End Sub
Use the MailItem.SentOnBehalfOfName property instead.

Search Excel Worksheet for text highlighted in Outlook email

Everyday I get emails with project numbers on them. I usually highlight and copy the project number from the email, click on my excel spreadsheet (WI_Design_Tracker), ctrl + F (to find) and paste the project number into the find field, then Find Next. I'm trying to create a macro that will shorten the process since I do it a hundred times a day. I found a macro that does the opposite (finds a highlighted number in Excel and searches through Outlook to find the email. I tried to amend it to fit my purposes but it's above my skill level. Any help would be greatly appreciated. Here's the code I'm trying to convert to search my Excel worksheet for the project number I have highlighted on an Outlook email.
'Code:
Option Explicit
Public Sub Search_Outlook_Emails()
Dim outApp As Outlook.Application
Dim outNs As Outlook.Namespace
Dim outStartFolder As Outlook.MAPIFolder
Dim foundEmail As Outlook.MailItem
Set outApp = New Outlook.Application
Set outNs = outApp.GetNamespace("MAPI")
'Start at Inbox's parent folder
Set outStartFolder = outNs.GetDefaultFolder(Outlook.olFolderInbox).Parent
'Or start at folder selected by user
'Set outStartFolder = outNs.PickFolder
If Not outStartFolder Is Nothing Then
Set foundEmail = Find_Email_In_Folder(outStartFolder, ActiveCell.Value)
If Not foundEmail Is Nothing Then
If MsgBox("Email subject: " & foundEmail.Subject & vbNewLine & vbNewLine & _
"Folder: " & foundEmail.Parent.FolderPath & vbNewLine & vbNewLine & _
"Open the email?", vbYesNo, "'" & ActiveCell.Value & "' found") = vbYes Then
foundEmail.Display
End If
Else
MsgBox "", vbOKOnly, "'" & ActiveCell.Value & "' not found"
End If
End If
End Sub
Private Function Find_Email_In_Folder(outFolder As Outlook.MAPIFolder, findText As String) As Outlook.MailItem
Dim outItem As Object
Dim outMail As Outlook.MailItem
Dim outSubFolder As Outlook.MAPIFolder
Dim i As Long
Debug.Print outFolder.FolderPath
Set Find_Email_In_Folder = Nothing
'Search emails in this folder
i = 1
While i <= outFolder.Items.Count And Find_Email_In_Folder Is Nothing
Set outItem = outFolder.Items(i)
If outItem.Class = Outlook.OlObjectClass.olMail Then
'Does the findText occur in this email's body text?
Set outMail = outItem
If InStr(1, outMail.Body, findText, vbTextCompare) > 0 Then Set Find_Email_In_Folder = outMail
End If
i = i + 1
Wend
DoEvents
'If not found, search emails in subfolders
i = 1
While i <= outFolder.Folders.Count And Find_Email_In_Folder Is Nothing
Set outSubFolder = outFolder.Folders(i)
'Only check mail item folders
If outSubFolder.DefaultItemType = Outlook.olMailItem Then Set Find_Email_In_Folder = Find_Email_In_Folder(outSubFolder, findText)
i = i + 1
Wend
End Function
Thanks for the link Tim. That was much simpler. I'd had seen that code before but wasn't able to make it work so I tried again. Here's what I ended up with. It could still use some tweaking and error handling, but this is what's working for now:
Sub FindOutlookValue()
Dim OutApp As Object
Dim OutMail As Object
Dim olInsp As Object
Dim WdDoc As Object
Dim strText As String
On Error Resume Next
'Get Outlook if it's running
Set OutApp = GetObject(, "Outlook.Application")
Set OutMail = OutApp.ActiveExplorer.Selection.Item(1)
With OutMail
Set olInsp = .GetInspector
Set wdDoc = olInsp.WordEditor
strText = WdDoc.Application.Selection.Range.Text
End With
'Find strText in Excel
Dim cl As Range
With Worksheets("MyWorksheet").Cells
Set cl = .Find(strText, After:=.Range(A1), LookIn:=xlValues)
If Not cl Is Nothing Then
cl.Select
End If
End With
End Sub

Get the date of the oldest mail per category

I have a macro to get the count of mails category-wise in Outlook.
Along with that I want the oldest mail date in a particular category. e.g. in the Red category there are 20 mails, so what is the date of the oldest mail in the Red category?
Sub CategoriesEmails()
Dim oFolder As MAPIFolder
Dim oDict As Object
Dim sStartDate As String
Dim sEndDate As String
Dim oItems As Outlook.Items
Dim sStr As String
Dim sMsg As String
Dim strFldr As String
Dim OutMail As Object
Dim xlApp As Object
On Error Resume Next
Set oFolder = Application.ActiveExplorer.CurrentFolder
Set oDict = CreateObject("Scripting.Dictionary")
sStartDate = Date - 365
sEndDate = Date
Set oItems = oFolder.Items.Restrict("[Received] >= '" & sStartDate & "' And [Received] <= '" & sEndDate & "'")
oItems.SetColumns ("Categories")
For Each aItem In oItems
sStr = aItem.Categories
If Not oDict.Exists(sStr) Then
oDict(sStr) = 0
End If
oDict(sStr) = CLng(oDict(sStr)) + 1
Next aItem
sMsg = ""
i = 0
strFldr = "C:\Users\singhab\Desktop\Macro\"
Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
xlApp.Workbooks.Open strFldr & "Test.xlsx"
xlApp.Sheets("Sheet1").Select
For Each aKey In oDict.Keys
xlApp.Range("a1").Offset(i, 0).Value = sMsg & aKey
xlApp.Range("B1").Offset(i, 0).Value = oDict(aKey) & vbCrLf
i = i + 1
Next
xlApp.Save
Set oFolder = Nothing
End Sub
I get the output
What I want is
Work with Items.GetFirst Method (Outlook) which Returns An Object value that represents the first object contained by the collection
Code Example
Option Explicit
Public Sub Example()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Dim Items As Outlook.Items
Set Items = Inbox.Items.Restrict("[Categories] = 'Red Category'")
Dim Item As Object
Set Item = Items.GetFirst
Debug.Print Item.Subject & " " & Item.ReceivedTime
End Sub

how to save the outlook instant search result emails in hard drive folder

I am trying to save all the emails, resulting out of instant text search into the hard drive folder. the below code is able to perform the search but giving me an error at selectallitems line while selecting each mail and saving them in HD. code is in excel vba;
Dim OlApp As Outlook.Application
Set OlApp = CreateObject("Outlook.Application")
Dim fldrpath As String
fldrpath = "\\mydata\EMAILS\
Check subfolder for messages and exit of none found
txtsearch = "abc#xyz.com, received:4/1/2017..4/30/2017"
OlApp.ActiveExplorer.Search txtsearch, olSearchScopeAllFolders
Dim myitem As Outlook.MailItem
Dim objitem As Object
Set myitem = OlApp.ActiveExplorer.SelectAllItems
Set objitem = myitem
objitem.SaveAs fldrpath & "test" & ".msg", olMSG
Any other alternative code to get the emails saved will also be appreciated.
Thanks in advance !! looking for a quick solution
Saving search results appears to be more easily achieved a different way.
From Outlook, not Excel.
Sub SearchForStr_Save()
Dim strSearch As String
Dim strDASLFilter As String
Dim strScope As String
Dim objItem As Object
Dim objSearch As search
Dim srchFolder As folder
Dim fldrpath As String
strSearch = "abc#xyz.com"
strDASLFilter = "urn:schemas:httpmail:textdescription LIKE '%" & strSearch & "%'"
strScope = "'Inbox'"
Set objSearch = AdvancedSearch(Scope:=strScope, filter:=strDASLFilter, SearchSubFolders:=True, Tag:="SearchFolder")
Set srchFolder = objSearch.Save(strSearch)
'fldrpath = "\\mydata\EMAILS\"
fldrpath = "h:\test\"
For Each objItem In srchFolder.Items
'Debug.Print objItem.subject
If objItem.Class = olMail Then
objItem.SaveAs fldrpath & "test" & ".msg", olMsg
End If
Next
ExitRoutine:
Set objSearch = Nothing
Set srchFolder = Nothing
End Sub

Resources