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

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.

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.

How to get body of the email from a shared folder?

The following code helps me to get data from my default folder in inbox but I
want to change my folder which is a shared folder and placed in favorite folders
I already tried to change getDefaultFolder with sharedDefaultFolder but it doesn't work.
Dim olApp As Object
Dim olNs As Object
Dim olFldr As Object
Dim olItms As Object
Dim olMail As Object
Set olApp = OutlookApp()
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(6).Folders("impMail")
Set olItms = olFldr.Items
You cannot simply change GetDefaultFolder to GetSharedDefaultFolder, you have to also add Recipient object The owner of the folder.
expression: .GetSharedDefaultFolder(Recipient**, FolderType)
Example With Email address
Option Explicit
Public Sub Example()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim RecipientShareName As Outlook.Recipient
Set RecipientShareName = olNs.CreateRecipient("0m3r#email.com") 'address
RecipientShareName.Resolve
Dim ShareInbox As Outlook.Folder
Set ShareInbox = olNs.GetSharedDefaultFolder(RecipientShareName, _
olFolderInbox) 'Inbox
Dim Items As Outlook.Items
Set Items = ShareInbox.Items
Dim i As Long
Dim Item As Outlook.MailItem
For i = Items.Count To 1 Step -1
If TypeOf Items(i) Is Outlook.MailItem Then
Set Item = Items(i)
Debug.Print Item.Subject '// Print Item to Immediate window
End If
Next
End Sub
Or if your using With just Name, then make sure recipient object is resolved
Example with recipient Name
Option Explicit
Public Sub Example()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim RecipientShareName As Outlook.Recipient
Set RecipientShareName = olNs.CreateRecipient("0m3r") 'address
RecipientShareName.Resolve
If Not RecipientShareName.Resolved Then
MsgBox "Error on Recipient Object"
Exit Sub
Else
Dim ShareInbox As Outlook.Folder
Set ShareInbox = olNs.GetSharedDefaultFolder(RecipientShareName, _
olFolderInbox) 'Inbox
End If
Dim Items As Outlook.Items
Set Items = ShareInbox.Items
Dim i As Long
Dim Item As Outlook.MailItem
For i = Items.Count To 1 Step -1
If TypeOf Items(i) Is Outlook.MailItem Then
Set Item = Items(i)
Debug.Print Item.Subject '// Print Item to Immediate window
End If
Next
End Sub
Does your satement " set olFldr ..." give you the correct folder?
You might check your folders with a statement like:
for each myO in olNs.GetDefaultFolder(6).folders : debug.Print myO.name : next

How to get recipient email address from Excel?

I'm trying to get the .To email address from my sent box using Excel-VBA. However, To only returns the name not the email address. After some search found that the recipient should be what I'm looking for. Tried by following the msdn guide, but the code does not seem to work.
Sub test()
Dim objoutlook As Object
Dim objNamespace As Object
Dim olFolder As Object
Dim OutlookMail As outlook.MailItem
Set objoutlook = CreateObject("Outlook.Application")
Set objNamespace = objoutlook.GetNamespace("MAPI")
Set olFolder = objNamespace.GetDefaultFolder(olFolderSentMail)
Set OutlookMail = objoutlook.CreateItem(olMailItem)
Dim recips As outlook.Recipients
Dim recip As outlook.Recipient
Dim pa As outlook.PropertyAccessor
Const PR_SMTP_ADDRESS As String = _
"http://schemas.microsoft.com/mapi/proptag/0x39FE001E"
Set recips = OutlookMail.Recipients
For Each recip In recips 'Something is wrong here
Set pa = recip.PropertyAccessor
Debug.Print recip.Name & " SMTP=" & pa.GetProperty(PR_SMTP_ADDRESS)
Next
Set olFolder = Nothing
Set objNamespace = Nothing
Set objoutlook = Nothing
End Sub
I'm not really familiar with VBA, please guide along.
You can try this:
Private Sub GetRecipientSMTP(objAllRecip As Outlook.Recipients)
Dim objRecip As Outlook.Recipient
Dim objExUser As Outlook.ExchangeUser
Dim objExDisUser As Outlook.ExchangeDistributionList
For Each objRecip In objAllRecip
Select Case objRecip.AddressEntry.AddressEntryUserType
Case 0, 10
Set objExUser = objRecip.AddressEntry.GetExchangeUser
If Not objExUser Is Nothing Then _
Debug.Print objExUser.PrimarySmtpAddress '/* or copy somewhere */
Case 1
Set objExDisUser = objRecip.AddressEntry.GetExchangeDistributionList
If Not objExDisUser Is Nothing Then _
Debug.Print objExDisUser.PrimarySmtpAddress '/* or copy somewhere */
Case Else
'/* Do nothing, recipient not recognized */
End Select
Next
End Sub
You can run it in your sub like below using recips from your code (or see sample usage).
GetRecipientSMTP recips
Basically, this will check on the each Recipient on Recipients you supplied. Then will check if it is an ExchangeUser type or ExchangeDistributionList before returning the PrimartSMTPAddress. HTH.
Sample Usage:
Sub marine()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFolder As Outlook.Folder
Dim olMail As Outlook.MailItem
Dim i As Integer
Set olApp = GetObject(, "Outlook.Application") '/* assuming OL is running */
Set olNs = olApp.GetNamespace("MAPI")
Set olFolder = olNs.GetDefaultFolder(olFolderInbox)
With olFolder
For i = .Items.Count To 1 Step -1
If TypeOf .Items(i) Is MailItem Then
Set olMail = .Items(i)
GetRecipientSMTP olMail.Recipients
End If
Exit For '/* I just want to process the first mail */
Next
End With
End Sub
Note: I used early binding and set reference to Outlook Object Library.
Quick Example
Option Explicit
Public Sub Example()
Dim OUTLOOK_APP As Outlook.Application
Dim olNs As Outlook.Namespace
Dim SENT_FLDR As MAPIFolder
Dim Items As Outlook.Items
Dim olRecip As Outlook.Recipient
Dim olRecipAddress As String
Dim i As Long
Set OUTLOOK_APP = New Outlook.Application
Set olNs = OUTLOOK_APP.GetNamespace("MAPI")
Set SENT_FLDR = olNs.GetDefaultFolder(olFolderSentMail)
Set Items = SENT_FLDR.Items
For i = Items.Count To 1 Step -1
DoEvents
If Items(i).Class = olMail Then
For Each olRecip In Items(i).Recipients
olRecipAddress = olRecip.Address
Debug.Print olRecipAddress
Next
End If
Next
End Sub
this is my way of getting Recipient email Address. I hope it would help you.
Sub CopyCurrentContact()
Dim objRcp As Outlook.Recipient
Dim objRcpS As Outlook.Recipients
Dim rcpStr As String
Set outLookObj = CreateObject("Outlook.Application")
Set InspectorObj = outLookObj.ActiveInspector
Set ItemObj = InspectorObj.CurrentItem
Set objRcpS = ItemObj.Recipients
For Each objRcp In objRcpS
rcpStr = objRcp.Address & "; " & rcpStr
Debug.Print rcpStr
Next objRcp
End Sub

Counting the number of emails in an Outlook Drafts folder

I am trying to count the number of emails in my Outlook "Drafts" folder from Excel VBA.
I have not programmed using the Outlook object hierarchy so I am having some trouble.
Below is one of the variations I've tried.
Dim objOutlook As Object
Set objOutlook = CreateObject("Outlook.Application")
Dim objNameSpace As Object
Set objNameSpace = objOutlook.GetNamespace("MAPI")
Set items = objNameSpace.GetDefaultFolder(olFolderDrafts).items
MsgBox items.count
When I run this code I receive the error:
Run-time error 5 Invalid procedure call or argument
I was able to answer my own question. Firstly, I did not have the MS Outlook Object library clicked. Secondly, I modified my code to the following:
Dim objOutlook As Object, objNameSpace As Object, objFolder As Object
Set objOutlook = CreateObject("Outlook.Application")
Set objNameSpace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNameSpace.GetDefaultFolder(olFolderDrafts)
MsgBox objFolder.items.count
You could also do This
Option Explicit
Public Const olFolderInbox As Long = 6
Public Const olFolderDrafts As Long = 16
Public Const olFolderContacts As Long = 10
Public Const olFolderDeletedItems As Long = 3
Public Sub Count_MailItems()
Dim olApp As Object ' Outlook.Application
Dim olNs As Object ' Outlook.Namespace
Dim Folder As Object ' Outlook.MAPIFolder
Dim Items As Object ' Outlook.Items
Dim Msg As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
' Set Folder = olNs.Session.PickFolder
'or
' Set Folder = olApp.ActiveExplorer.CurrentFolder
'or
Set Folder = olNs.GetDefaultFolder(olFolderInbox)
' olFolderDrafts
' olFolderContacts
' olFolderDeletedItems
Set Items = Folder.Items
Msg = Items.Count & " Items in " & Folder.Name & " Folder"
MsgBox (Msg)
End Sub

Scan non default outlook inbox for email?

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.

Resources