Scan non default outlook inbox for email? - excel

I am using the following vba code which checks for any emails with a specific subject heading.
The problem is it checks my default outlook inbox folder when I need it to check the inbox of my other email account NewSuppliers#Hewden.co.uk
Can someone please show me how I would do this? Thanks in advance
Sub Macro1() Set olApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim myItem As Outlook.MailItem
Dim myAttachment As Outlook.Attachment
Dim I As Long
Dim olMail As Variant
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Set olMail = myTasks.Find("[Subject] = ""New Supplier Request: Ticket""")
If Not (olMail Is Nothing) Then
For Each myItem In myTasks
If myItem.Attachments.Count <> 0 Then
For Each myAttachment In myItem.Attachments
If InStr(myAttachment.DisplayName, ".txt") Then
I = I + 1
myAttachment.SaveAsFile "\\uksh000-file06\Purchasing\NS\Unactioned\" & myAttachment
End If
Next
End If
Next
For Each myItem In myTasks
myItem.Delete
Next
Call Macro2
Else
MsgBox "There Are No New Supplier Requests."
End If
End Sub
outlook folder structure:
account1#hewden.co.uk
Inbox
Drafts
Sent
NewSuppliers#hewden.co.uk
Inbox
Drafts
Sent

You need to use the following, assuming that the folder you want is at the same level in the folder hierarchy
Set Items = Session.GetDefaultFolder(olFolderCalendar).Parent.Folders("YouFolderName").Items
See here for more details ... http://www.slipstick.com/developer/working-vba-nondefault-outlook-folders/
Have you tried the following function from the above link ...
Function GetFolderPath(ByVal FolderPath As String) As Outlook.Folder
Dim oFolder As Outlook.Folder
Dim FoldersArray As Variant
Dim i As Integer
On Error GoTo GetFolderPath_Error
If Left(FolderPath, 2) = "\\" Then
FolderPath = Right(FolderPath, Len(FolderPath) - 2)
End If
'Convert folderpath to array
FoldersArray = Split(FolderPath, "\")
Set oFolder = Application.Session.Folders.item(FoldersArray(0))
If Not oFolder Is Nothing Then
For i = 1 To UBound(FoldersArray, 1)
Dim SubFolders As Outlook.Folders
Set SubFolders = oFolder.Folders
Set oFolder = SubFolders.item(FoldersArray(i))
If oFolder Is Nothing Then
Set GetFolderPath = Nothing
End If
Next
End If
'Return the oFolder
Set GetFolderPath = oFolder
Exit Function
GetFolderPath_Error:
Set GetFolderPath = Nothing
Exit Function
End Function
You may need to use the technique here first to find out the actual folder name ... https://msdn.microsoft.com/en-us/library/office/ff184607.aspx
In the image below, the Drafts, Clients, Outbox folders are all on the same level (they share the same parent folder james#...com), but the ChildFolder folder is not (it's parent is Drafts).

You should be able to just specify the name of your 2nd mailbox as a Folder.
Set Fldr = olNs.Folders("My 2nd mailbox").Folders("Sub Folder")
If you want the main inbox of the 2nd account, then you specify this as the sub folder of the account.
Set Fldr = olNs.Folders("My 2nd Inbox").Folders("Inbox")
Note that it's the name of the mailbox you use, not the e-mail address. Let me know how you get on.

Related

Outlook Selecting a Subfolder in the SharedMailbox using GetSharedDefaultFolder Automation error

The following code is to count the number of emails in a particular SharedMailbox or its subfolder.
I am having trouble selecting a subfolder in SharedMailbox.
I have read a number of resources on GetSharedDefaultFolder including this one.
However, struggling to put it together correctly.
Would be really great if you could help with this.
I am experiencing the following error while running the code.
Run-time error '-2147221233 (80040010f)' Automation error
Sub CountInboxSubjects()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFldr As Outlook.MAPIFolder
Dim MyFolder1 As Outlook.MAPIFolder
Dim MyFolder2 As Outlook.MAPIFolder
Dim MyFolder3 As Outlook.MAPIFolder
Dim olMailItem As Outlook.MailItem
Dim propertyAccessor As Outlook.propertyAccessor
Dim olItem As Object
Dim dic As Dictionary
Dim i As Long
Dim Subject As String
Dim val1 As Variant
Dim val2 As Variant
val1 = ThisWorkbook.Worksheets("Data").Range("I2")
val2 = ThisWorkbook.Worksheets("Data").Range("I3")
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
'Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olShareName = olNs.CreateRecipient("Shared_MailBox")
Set olFldr = olNs.GetSharedDefaultFolder(olShareName, olFolderInbox)
MsgBox (olFldr)
Set MyFolder1 = olFldr.Folders("Sub_Folder")
MsgBox (MyFolder1)
Set MyFolder2 = MyFolder1.Folders("Sub_Sub_Folder")
MsgBox (MyFolder2)
Set MyFolder3 = MyFolder1.Folders("Sub_Sub_Folder2")
MsgBox (MyFolder3)
If ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Inbox" Then
MyFolder = olFldr
ElseIf ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Sub_Folder" Then
MyFolder = MyFolder1
ElseIf ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Sub_Sub_Folder" Then
MyFolder = MyFolder2
ElseIf ThisWorkbook.Worksheets("EPI_Data").Range("I5") = "Sub_Sub_Folder" Then
MyFolder = MyFolder3
End If
Set olItem = MyFolder.Items
'Set myRestrictItems = olItem.Restrict("[ReceivedTime]>'" & Format$("01/01/2019 00:00AM", "General Date") & "' And [ReceivedTime]<'" & Format$("01/02/2019 00:00AM", "General Date") & "'")
Set myRestrictItems = olItem.Restrict("[ReceivedTime]>'" & Format$(val1, "General Date") & "' And [ReceivedTime]<'" & Format$(val2, "General Date") & "'")
For Each olItem In myRestrictItems
If olItem.Class = olMail Then
Set propertyAccessor = olItem.propertyAccessor
Subject = propertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x0E1D001E")
If dic.Exists(Subject) Then dic(Subject) = dic(Subject) + 1 Else dic(Subject) = 1
End If
Next olItem
With ActiveSheet
.Columns("A:B").Clear
.Range("A1:B1").Value = Array("Count", "Subject")
For i = 0 To dic.Count - 1
.Cells(i + 2, "A") = dic.Items()(i)
.Cells(i + 2, "B") = dic.Keys()(i)
Next
End With
End Sub
After trouble-shooting, I am aware the following step has issues.
Set MyFolder1 = olFldr.Folders("Sub_Folder")
MsgBox (MyFolder1)
I expect the msgbox will return the subfolder name but it's reporting error.
Run-time error '-2147221233 (80040010f)' Automation error
I couldn't find out why. can anyone please help..
Try working with Recipient email address, if recipient name then Attempt to resolve Recipient against the Address Book...
Option Explicit
Public Sub Example()
Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.Namespace
Set olNs = olApp.GetNamespace("MAPI")
Dim Recip As Outlook.Recipient
Dim Inbox As Outlook.MAPIFolder
Set Recip = olNs.CreateRecipient("0m3r#Email.com")
Recip.Resolve
If Recip.Resolved Then
Set Inbox = olNs.GetSharedDefaultFolder _
(Recip, olFolderInbox)
End If
Inbox.Display
End Sub
Of course, you must resolve a recipient's name or address against the address book before accessing shared folders.
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olShareName = olNs.CreateRecipient("Shared_MailBox")
olShareName.Resolve
If Recip.Resolved Then
Set olFldr = olNs.GetSharedDefaultFolder(olShareName, olFolderInbox)
...
End If
But the cause of the issue with accessing a subfolder is different...
First of all, try to uncheck Download shared folders checkbox checked on the Advanced tab of your Exchange account properties dialog. See the Detecting if ‘Download Shared Folders’ is Checked in Outlook article for more information.
Second, please take a look at the By default, shared mail folders are downloaded in Cached mode in Outlook 2010 and Outlook 2013 article. What value do you have set for the CacheOthersMail key on the PC?
See Accessing subfolders within shared mailbox for more information.

Access details of subfolders of folders in inbox in a shared mailbox

Shared mailbox name: trvx-prog.obs#orange.com
I need:
to access folders Madhvi and P_Wardah with their four sub folders
set a date range for report extraction (with the subject, sender, date sent, folder name we are accessing)
automate to run each week
I am not able to access the second folder and the subfolders
Option Explicit
Sub EmailStatsV3()
Dim Item As Object
Dim varOutput() As Variant
Dim lngcount As Long
Dim xlApp As Excel.Application
Dim xlSht As Excel.Worksheet
Dim ShareInbox As Outlook.MAPIFolder
Dim olNs As Outlook.NameSpace
Dim olRecip As Outlook.Recipient
Dim SubFolder As Object
Set olNs = Application.GetNamespace("MAPI")
Set olRecip = olNs.CreateRecipient("trvx-prog.obs#orange.com") '// Owner's Name or email address
Set ShareInbox = olNs.GetSharedDefaultFolder(olRecip, olFolderInbox)
Set SubFolder = ShareInbox.Folders("P_Wardah")
ReDim varOutput(1 To SubFolder.Items.Count, 1 To 4)
For Each Item In SubFolder.Items
If TypeName(Item) = "MailItem" Then
lngcount = lngcount + 1
varOutput(lngcount, 1) = Item.ReceivedTime 'stats on when received
varOutput(lngcount, 2) = Item.Subject 'to split out prefix
varOutput(lngcount, 3) = Item.Sender
varOutput(lngcount, 4) = SubFolder.Name
End If
Next
'Creates a blank workbook in excel
Set xlApp = New Excel.Application
Set xlSht = xlApp.Workbooks.Add.Sheets(1)
xlSht.Range("A1").Resize(UBound(varOutput, 1), _
UBound(varOutput, 2)).Value = varOutput
xlApp.Visible = True
End Sub
Received details of only folder P_Wardah
Need to access the folder of Madhvi
Need to access the sub folders of P_Wardah and Madhvi which are (Treated, No Perimeter, Follow Up, Pending)
Need to classify them for a date range of each week
This is not a full answer - Just an aid to help you move forward
You also need a loop to iterate through all the sub folders of SubFolder
Eg
For Each xFldr In SubFolder.Folders
' Recursive Call to process xFldr
Next
So your folder processing routine needs to be in a Sub of it's own and then call itself (recursive call)

How to search for a string in a saved emails folder

We are in the middle of a new production line start-up and have a lot of info and emails to communicate. What we want is that all the info is gathered in a folder on the server and that people who need info could search in a textfield to find related subjects. So what I want is to search for a string in email body's but currently I only know how to do this in my own mail box but not how to do it in saved emails in a folder. The code that I have for now is this and is for a Excel macro:
Sub FindSubjectInEmails()
Dim outlookApp
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim olMail As Variant
Dim myTasks
Dim sir() As String
Set outlookApp = CreateObject("Outlook.Application")
Set olNs = outlookApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
For Each olMail In myTasks
If (InStr(1, olMail.Body, "text_to_find", vbTextCompare) > 0) Then
olMail.Display
Exit For
End If
Next
End Sub
Is this what you are trying?
Option Explicit
Sub Sample()
Dim OutApp As Object, OutMsg As Object
Dim msgFolder As String, emlFile As String
Set OutApp = CreateObject("Outlook.Application")
'~~> Change this to the relevant folder
msgFolder = "C:\Users\routs\Desktop\Test\"
emlFile = Dir(msgFolder & "\*.msg")
'~~> Loop through the folder to work with the emails
Do While Len(emlFile) > 0
Set OutMsg = OutApp.Session.OpenSharedItem(msgFolder & emlFile)
If (InStr(1, OutMsg.Body, "text_to_find", vbTextCompare) > 0) Then
OutMsg.Display
Exit Do
End If
emlFile = Dir
Loop
Set OutMsg = Nothing
Set OutApp = Nothing
End Sub

VBA: Search email in non default outlook inbox?

I am using the following VBA code which checks for any emails with a specific subject heading.
The problem is it checks my default outlook inbox folder when I need it to check the inbox of my other email account.
Can someone please show me how I would do this?
Sub Macro1()
Set olApp = CreateObject("Outlook.Application")
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim myItem As Outlook.MailItem
Dim myAttachment As Outlook.Attachment
Dim I As Long
Dim olMail As Variant
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Set olMail = myTasks.Find("[Subject] = ""New Supplier Request: Ticket""")
If Not (olMail Is Nothing) Then
For Each myItem In myTasks
If myItem.Attachments.Count <> 0 Then
For Each myAttachment In myItem.Attachments
If InStr(myAttachment.DisplayName, ".txt") Then
I = I + 1
myAttachment.SaveAsFile "\\uksh000-file06\Purchasing\NS\Unactioned\" & myAttachment
End If
Next
End If
Next
For Each myItem In myTasks
myItem.Delete
Next
Call Macro2
Else
MsgBox "There Are No New Supplier Requests."
End If
End Sub
Instead of iterating through all folder items in Outlook:
For Each myItem In myTasks
If myItem.Attachments.Count <> 0 Then
For Each myAttachment In myItem.Attachments
I'd suggest using the Find/FindNext or Restrict methods of the Items class. Also you may consider using using the AdvancedSearch method of the Application class. Take a look at the following articles for the sample code which illustrates how to use them in the code:
How To: Use Restrict method to retrieve Outlook mail items from a folder
How To: Use Find and FindNext methods to retrieve Outlook mail items from a folder (C#, VB.NET)
Advanced search in Outlook programmatically: C#, VB.NET
The reason is that you have declared variable myItem as Outlook.MailItem and you use it later to iterate through the collection of items in MAPI folder.
However, MAPI folder contains not only MailItems but also MeetingItems and every time the loop finds an object of MeetingItem type, it throws an Mismatch type error since it expects only objects of MailItem type.
You just need to change declaration of myItem variable to:
Dim myItem as Object
=============================================================
The code below should iterate through the filtered items only:
Sub Work_with_Outlook()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim Fldr As Outlook.MAPIFolder
Dim myItem As Object
Dim myAttachment As Outlook.Attachment
Dim olMail As Variant
Dim i As Long
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items
Set olMail = myTasks.Find("[Subject] = ""test""")
While Not olMail Is Nothing
If olMail.Attachments.Count Then
For Each myAttachment In olMail.Attachments
i = i + 1
myAttachment.SaveAsFile "\\uksh000-file06\Purchasing\Supplier Attachments\test" & i & ".txt"
Next myAttachment
End If
Set olMail = myTasks.FindNext
Wend
MsgBox "Scan Complete."
End Sub

Excel VBA, set an Outlook Folder, which is a public folder

I'm trying to move emails from an inbox folder (named "A_Classer") into a Outlook public folder (variable name for the destination folder is olFolder)
I tried the getshareddefaultfolder method and the OpenSharedFolder method but I couldn't solve my syntax problem
The name of the shared folder is "Québec" and it's path (from the property Windows) is ("Dossiers publics - guillaume.hebert#cima.ca/Tous les dossiers publics/Québec")
Code stops at : set olFolder...
Here's my code below with all the versions I tried
Sub move_to_public_folder()
Dim msg As Outlook.MailItem
Dim olFolder As Outlook.Folder 'public folder where I want the email to be moved
Dim sourceFolder As Outlook.Folder 'current folder of the emails that are to be moved
Dim OlApp As Object
Dim myNamespace As Outlook.Namespace
Dim myRecipient As Outlook.Recipient
Set OlApp = CreateObject("Outlook.Application") 'Outlook application call
Set myNamespace = OlApp.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Guillaume Hébert")
myRecipient.Resolve
If myRecipient.Resolved Then
Cells(1, 1) = Cells(1, 1) + 1
End If
Set olFolder = myNamespace.OpenSharedFolder("Québec") 'FIRST try I made
'Set olFolder = myNamespace.OpenSharedFolder _ 'Second try I made
'("Dossiers publics - guillaume.hebert#cima.ca/Tous les dossiers publics/Québec")
'Set olFolder = myNamespace.GetSharedDefaultFolder _ 'Last try I made
'(myRecipient, olPublicFoldersAllPublicFolders)
Set sourceFolder = Session.GetDefaultFolder(sourceFolderInbox)
Set sourceFolder = sourceFolder.Folders("A_Classer")
If sourceFolder Is Nothing Then Exit Sub
I = sourceFolder.Items.Count
nbre_op = I 'détermine combien de courriel dans le répertoire
I = 1
While I <= nbre_op
Set msg = olFolder.Items(1)
msg.Move olFolder
I = I + 1
Wend
Set OlApp = Nothing
End Sub
Thank you in advance for all the help you will kindly provide
Are you connected to the Exchange server?
If you use the OpenSharedFolder method you need to specify the URL. This method is used to access the following shared folder types:
Webcal calendars (webcal://mysite/mycalendar)
RSS feeds (feed://mysite/myfeed)
Microsoft SharePoint Foundation folders (stssync://mysite/myfolder)
iCalendar calendar (.ics) files
vCard contact (.vcf) files
Outlook message (.msg) files
I'd recommend using the GetSharedDefaultFolder method which returns a Folder object that represents the specified default folder for the specified user. For example, you can get the Inbox folder, then you can find the required one.
What error do you get in the code when you run the following line?
'Set olFolder = myNamespace.GetSharedDefaultFolder(myRecipient, olPublicFoldersAllPublicFolders)
Found it! Tx to #Eugene and #xmojmr.
Sub move_to_public_folder()
Dim msg As Outlook.MailItem
Dim olFolder As Outlook.Folder 'source folder
Dim objFolder As Outlook.Folder 'target folder
'Dim sourceFolder As Outlook.Folder 'current folder of the emails that are to be moved
Dim OlApp As Object
'Dim fldr As Outlook.Folder
Dim chemin_repertoire_outlook_cible As String 'path containing the target folder
Dim myNamespace As Outlook.Namespace
Dim myRecipient As Outlook.Recipient
Set OlApp = CreateObject("Outlook.Application") 'Outlook application call
Set myNamespace = OlApp.GetNamespace("MAPI")
Set myRecipient = myNamespace.CreateRecipient("Guillaume Hébert")
myRecipient.Resolve
If myRecipient.Resolved Then
Cells(1, 1) = Cells(1, 1) + 1
End If
Set OlApp = CreateObject("Outlook.Application") 'Outlook application call
Set olFolder = Session.GetDefaultFolder(olFolderInbox)
Set olFolder = olFolder.Folders("A_Classer")
lig = 11
col = 4
chemin_repertoire_outlook_cible = Cells(lig, col) 'target folder name setting
Set objFolder = GetFolder(chemin_repertoire_outlook_cible)
I = olFolder.Items.Count
nbre_op = I
I = 1
While I <= nbre_op 'loop to move all msg in source folder (olFolder)
Set msg = olFolder.Items(1)
msg.Move objFolder
I = I + 1
Wend
Set OlApp = Nothing
End Sub
The function GetFolder is as follow
Public Function GetFolder(strFolderPath As String) As MAPIFolder
' source of this function is: http://www.outlookcode.com/d/code/getfolder.htm
' strFolderPath needs to be something like
' "Public Folders\All Public Folders\Company\Sales" or
' "Personal Folders\Inbox\My Folder"
Dim objApp As Outlook.Application
Dim objNS As Outlook.Namespace
Dim colFolders As Outlook.Folders
Dim objFolder As Outlook.Folder
Dim arrFolders() As String
Dim I As Long
On Error Resume Next
strFolderPath = Replace(strFolderPath, "/", "\")
arrFolders() = Split(strFolderPath, "\")
Set objApp = Outlook.Application
Set objNS = objApp.GetNamespace("MAPI")
Set objFolder = objNS.Folders.Item(arrFolders(0))
If Not objFolder Is Nothing Then
For I = 1 To UBound(arrFolders)
Set colFolders = objFolder.Folders
Set objFolder = Nothing
Set objFolder = colFolders.Item(arrFolders(I))
If objFolder Is Nothing Then
Exit For
End If
Next
End If
Set GetFolder = objFolder
Set colFolders = Nothing
Set objNS = Nothing
Set objApp = Nothing
End Function
Hope it could help someone else sometime.

Resources