Extracting the info from Outlook to Excel - vba

I have the code below which gives me the Sender line, Subject line and date information, however is there a way to also get the information from the To line (Name and Email Address).
Sub GetFromOutlook()
Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim I As Integer
Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Mail").Folders("Test")
I = 1
For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range("From_date").Value Then
Range("eMail_subject").Offset(I, 0).Value = OutlookMail.Subject
Range("eMail_date").Offset(I, 0).Value = OutlookMail.ReceivedTime
Range("eMail_sender").Offset(I, 0).Value = OutlookMail.SenderName
Range("eMail_text").Offset(I, 0).Value = OutlookMail.Body
I = I + 1
End If
Next OutlookMail
Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing
End Sub

Loop through all recipients in the MailItem.Recipients collection. If you only need To recipients, check the Recipient.Type property - it ca be olTo, olCC, olBCC
for each recip in OutlookMail .Recipients
if recip.Type = olTo Then
MsgBox recip.Name & ": " & recip.Address
End If
next
As a sidenote, the condition If OutlookMail.ReceivedTime >= Range("From_date").Value will never be satisfied - you cannot use equality comparison for the datetime values, you only only use a range: (value < const1) and (value > const2)

Related

How to get Alias from contact properties

I am trying to get the Alias ID of every received email from the sender's email address.
To get Alias you can right click on the received email, select open Outlook Properties.
I built a code that extracts email received in my inbox from a particular date specified in cell B.
I am trying to add the Alias ID in D4 onwards.
Sub GetFromOutlook()
Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer
Dim olExchgnUser As ExchangeUser
Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set Folder = OutlookNamespace.Folders("insert your own email address").Folders("inbox")
i = 1
For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range("email_Receipt_Date").Value Then
Range("email_Subject").Offset(i, 0).Value = OutlookMail.Subject
''Alias this is where i'm attempting to get Alias as part of the loop from every Item
Dim olNameSpace As Namespace
Dim olAddrList As AddressList
Set olAddrList = OutlookNamespace.AddressLists("Global Address List")
Set olExchgnUser = olAddrEntry.GetExchangeUser
With olExchgnUser
Range("Alias_name").Offset(i, 0) = .Alias
End With
''''ENd Alias
Range("email_Subject").Offset(i, 0).Columns.AutoFit
Range("email_Subject").Offset(i, 0).VerticalAlignment = xlTop
Range("email_Date").Offset(i, 0).Value = OutlookMail.ReceivedTime
Range("email_Date").Offset(i, 0).Columns.AutoFit
Range("email_Date").Offset(i, 0).VerticalAlignment = xlTop
Range("email_Sender").Offset(i, 0).Value = OutlookMail.SenderName
Range("email_Sender").Offset(i, 0).Columns.AutoFit
Range("email_Sender").Offset(i, 0).VerticalAlignment = xlTop
Range("email_Body").Offset(i, 0).Value = OutlookMail.Body
Range("email_Body").Offset(i, 0).Columns.AutoFit
Range("email_Body").Offset(i, 0).VerticalAlignment = xlTop
i = i + 1
End If
Next OutlookMail
Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing
MsgBox "operation Complete"
End Sub
Replace the lines
Set olAddrList = OutlookNamespace.AddressLists("Global Address List")
Set olExchgnUser = olAddrEntry.GetExchangeUser
with
Set olExchgnUser = OutlookMail.Sender.GetExchangeUser
(null and error handling omitted).
You really should not be looping through all messages in a folder - use Items.Find/FindNext or Items.Restrict.

Extract email address instead of email name of the CC using vbscript?

I am writing a VBScript to extract CC from the email. When I extract the cc, instead of an email address, it shows the email name of the person. I had same issue while I was extracting the "from" address. I checked whether the email address type of the from the person (.SenderEmailType) is SMTP or EX and was able to fetch the email address instead of email name. I don't know how to do the same for CC. I have checked online, it is written to loop through "Mailitems.Recipent". I am new to vbscript to I am not sure how to do this. Currently I am using .CC object to get the cc detail.
Set Arg = WScript.Arguments
dim item1
dim objsubject
dim intcount
Dim i
dim savename
dim vTextFile
dim filename
dim extension
Dim t
Dim Itimestamp
dim savefolder
Dim vSenderEmailAddress
Dim vCcEmailAddress
Dim vFlagTextFileCreate
vFlagTextFileCreate = True
savefolder = "C:\Users\tgssupport\Documents\Automation Anywhere Files\Automation Anywhere\My Scripts\Retro Pricing\junk"
vTextFile = savefolder & "\File Report.txt"
vFlagExcelAttachmentFound = False
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then 'Could not get instance of Outlook, so create a new one
Err.Clear
Set olApp = CreateObject("Outlook.Application")
End If
on error goto 0
Set olns = olApp.GetNameSpace("MAPI")
olns.logon "Outlook",,False,True
'6 is for Inbox
Set objFolder = olns.GetDefaultFolder(6)
For each item1 in objFolder.Items
if item1.Unread=true then
objsubject = item1.subject
vCcEmailAddress = item1.CC
If item1.SenderEmailType = "SMTP" Then
vSenderEmailAddress = item1.SenderEmailAddress
ElseIf item1.SenderEmailType = "EX" Then
vSenderEmailAddress = item1.Sender.GetExchangeUser.PrimarySmtpAddress
End If 'If item1.SenderEmailType
msgbox vCcEmailAddress.
msgbox vSenderEmailAddress.
end if 'if item1.Unread=true
Next
olns.logoff
Set olns = Nothing
Set olApp = Nothing
WScript.Quit
With item1.Recipients
For i = 1 To .Count
If .Item(i).Type = OlMailRecipientType.olCC Then
vCcEmailAddress = .Item(i).Address
Exit For
End If
Next i
End With
Set objFolder = olns.GetDefaultFolder(6)
For each item1 in objFolder.Items
For Each RecipientObject In item1.Recipients
If RecipientObject.Type = 2 Then
msgbox RecipientObject.Address
End if
Next
Next

Excel VBA Logic idea

My script is for tracking emails with subject and received time.
I receive 4 emails daily and I need to make reports about when email receiving.
My question is I create check box that allow which emails I want to track, but I don't know how can I make logically. First I tried , I created 15 if statements. I know it's not good so I am looking for new logic. I have attached my code below.
Please share your knowledge.
Plus, restrict method is for specified date and sender.
Sub GetFromOutlook()
Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim OutlookMail As Variant
Dim Folder As MAPIFolder
Dim olItems As Outlook.Items
Dim myItems As Outlook.Items
Dim olShareName As Outlook.Recipient
Dim dStart As Date
Dim dEnd As Date
Dim i As Integer
Dim sFilter As String
Dim sFilterLower As String
Dim sFilterUpper As String
Dim sFilterSender As String
'========================================================
'access to shared mailbox to get items
'========================================================
Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set olShareName = OutlookNamespace.CreateRecipient("Mailbox.teamshared#example.ca")
Set Folder = Session.GetSharedDefaultFolder(olShareName, olFolderInbox).Folders("subfolder1").Folders("subfolder2")
Set olItems = Folder.Items
'========================================================
'If check box is checked
'========================================================
dStart = Range("From_Date").Value
dEnd = Range("To_Date").Value
'========================================================
'Conditions for restrict to get items specificed date
'========================================================
sFilterLower = "[ReceivedTime] > '" & Format(dStart, "ddddd h:nn AMPM") & "'"
sFilterUpper = "[ReceivedTime] < '" & Format(dEnd, "ddddd h:nn AMPM") & "'"
sFilterSender = "[SenderName] = ""no-reply#example.com"""
'========================================================
'Restrict emails followed by above conditions
'========================================================
Set myItems = olItems.Restrict(sFilterLower)
Set myItems = myItems.Restrict(sFilterUpper)
Set myItems = myItems.Restrict(sFilterSender)
'========================================================
'items(emails) display in worksheets
'========================================================
i = 1
For Each myItem In myItems
Range("eMail_subject").Offset(i, 0).Value = myItem.Subject
Range("eMail_date").Offset(i, 0).Value = Format(myItem.ReceivedTime, "h:nn")
'Convert size KB
If myItem.Attachments.Count > 0 Then
Range("eMail_size").Offset(i, 0).Value = myItem.Attachments.Item(1).Size / 1024
Else
Range("eMail_size").Offset(i, 0).Value = "No attached file"
End If
i = i + 1
Next myItem
Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing
Else
MsgBox "You have check at least one"
End If
End Sub

Send Appointment VBA

So, I've been wrestling with this task for WAY too long now. I am trying to make a button that creates an appointment and sends it to someone. So far, I've been successful in creating the appointment with the variables I want, but I can't figure out how to send it to the right person. Or send it at all for that matter. I'm very new to Outlook applications within VBA, so be gentle with me, but here is my code so far:
Sub appt()
Dim OutApp As Object
Dim OutMail As Object
Dim duedate As String
Dim currentrow As String
Dim currentsheet As String
Dim owner As String
currentsheet = ActiveSheet.Name
currentrow = Range("C10:C" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
duedate = Range("C" & currentrow).Offset(0, 1)
owner = Range("C" & currentrow).Offset(0, 2)
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(1)
On Error Resume Next
With OutMail
.Recipients = Range("M3")
.Subject = "Next PDB Task for " & currentsheet
.Importance = True
.Start = "8:00 AM" & duedate
.End = "8:00 AM" & Format(Date + 5)
.ReminderMinutesBeforeStart = 10080
.Body = "Text and Stuff"
.Display
End With
Set OutMail = Nothing
Set OutApp = Nothing
Unload Emy
End Sub
So, this is definitely grabbing the information I want from the sheet it's run in, however it's not going anywhere. Do I need to use something other than .Recipients? Is it possible to forward this (with .Forward maybe?)? Any help would be greatly appreciated!!!
P.S. The email address I want to send the appointment to is in cell M3.
I didn't try the scripts, but it looks like they will do what you want.
Sub ResolveName()
Dim myNamespace As Outlook.NameSpace
Dim myRecipient As Outlook.Recipient
Dim CalendarFolder As Outlook.Folder
Set myNamespace = Application.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Dan Wilson")
myRecipient.Resolve
If myRecipient.Resolved Then
Call ShowCalendar(myNamespace, myRecipient)
End If
End Sub
Sub ShowCalendar(myNamespace, myRecipient)
Dim CalendarFolder As Outlook.Folder
Set CalendarFolder = _
myNamespace.GetSharedDefaultFolder _
(myRecipient, olFolderCalendar)
CalendarFolder.Display
End Sub
excel vba create appointment in someone elses calendar
Sub MultiCalendars()
Dim objPane As Outlook.NavigationPane
Dim objModule As Outlook.CalendarModule
Dim objGroup As Outlook.NavigationGroup
Dim objNavFolder As Outlook.NavigationFolder
Dim objFolder As Folder
Dim calItem As Object
Dim mtgAttendee As Outlook.Recipient
Dim i As Integer
Set Application.ActiveExplorer.CurrentFolder = Session.GetDefaultFolder(olFolderCalendar)
DoEvents
Set objPane = Application.ActiveExplorer.NavigationPane
Set objModule = objPane.Modules.GetNavigationModule(olModuleCalendar)
With objModule.NavigationGroups
Set objGroup = .GetDefaultNavigationGroup(olMyFoldersGroup)
' To use a different calendar group
' Set objGroup = .Item("Shared Calendars")
End With
For i = 1 To objGroup.NavigationFolders.Count
If (objGroup.NavigationFolders.Item(i).Folder.FullFolderPath = "\\Mailbox - Doe, John T\Calendar") Then
Set objNavFolder = objGroup.NavigationFolders.Item(i)
Set calItem = objNavFolder.Folder.Items.Add(olAppointmentItem)
calItem.MeetingStatus = olMeeting
calItem.Subject = "Test Meeting - Ignore"
calItem.Location = "TBD Location"
calItem.Start = #1/19/2015 1:30:00 PM#
calItem.Duration = 90
Set mtgAttendee = calItem.Recipients.Add("John Doe")
mtgAttendee.Type = olRequired
Set mtgAttendee = calItem.Recipients.Add("Jane Doe")
mtgAttendee.Type = olOptional
Set mtgAttendee = calItem.Recipients.Add("CR 101")
mtgAttendee.Type = olResource
calItem.Save
If (calItem.Recipients.ResolveAll) Then
calItem.Send
Else
calItem.Display
End If
End If
Next
Set objPane = Nothing
Set objModule = Nothing
Set objGroup = Nothing
Set objNavFolder = Nothing
Set objFolder = Nothing
Set calItem = Nothing
Set mtgAttendee = Nothing
End Sub
https://answers.microsoft.com/en-us/office/forum/office_2010-customize/excel-vba-create-an-appointment-in-someone-elses/4c2ec8d1-82f2-4b02-abb7-8c2de2fd7656?auth=1

Skip already categorized mails

Current Code:
Dim outlookapp
Dim olns As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim olMail As Object
'Dim olMail As Outlook.MailItem
Dim myTasks
Dim projIDsearch As String
Dim myrecipient As Outlook.Recipient
Dim daysAgo As Long
Set outlookapp = CreateObject("Outlook.Application")
Set olns = outlookapp.GetNamespace("MAPI")
Set myrecipient = olns.CreateRecipient("Ccbcphelpdesk")
myrecipient.Resolve
'Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("ExemptionReview")
Set Fldr = olns.GetSharedDefaultFolder(myrecipient, olFolderInbox)
' Restrict search to daysAgo
daysAgo = 0
Set myTasks = Fldr.Items.Restrict("[ReceivedTime]>'" & Format(Date - daysAgo, "DDDDD HH:NN") & "'")
projIDsearch = ActiveCell.Cells(1, 4)
For Each olMail In myTasks
If (InStr(1, olMail.Subject, projIDsearch, vbTextCompare) > 0) Then
olMail.Categories = "ESP"
olMail.Save
End If
Next
end sub
This looks up emails pertaining to a search string in the subject then tags them as ESP. I need to skip emails that are already categorized.
I have tried:
If (InStr(1, olMail.Subject, projIDsearch, vbTextCompare) > 0) Then
If olmail.categories Is nothing then 'line returns and error 424
olMail.Categories = "ESP"
olMail.Save
End If
End If
How can I skip Emails that are already categorized and only categorize emails with no category?
https://msdn.microsoft.com/en-us/library/office/ff860423.aspx
Categories is a String-type property, so test with something like:
If Len(olmail.Categories) = 0 Then
Use Logical Operators And Not on your Restrict method
Set myTasks = Fldr.Items.Restrict("[ReceivedTime]>'" & Format(Date - daysAgo, "DDDDD HH:NN") & "' And Not [Categories] = 'ESP'")
and remove your If olmail.categories Is nothing that way your not checking every olmail- and it should speedup your loop