Import Emails from specific folder in Outlook

2019-07-09 02:28发布

I'm currently using the following code in Excel to access folders in an unmanned Outlook mailbox other than my own.

However is there a way I can set the folder in the code rather than using the folder picker.

Sub Launch_Pad()   
Dim olApp As Outlook.Application
Dim olNS As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder

Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.PickFolder

n = 2
Cells.ClearContents

Call ProcessFolder(olFolder)

Set olNS = Nothing
Set olFolder = Nothing
Set olApp = Nothing
Set olNS = Nothing
End Sub

Sub ProcessFolder(olfdStart As Outlook.MAPIFolder)

Dim olFolder As Outlook.MAPIFolder
Dim olObject As Object
Dim olMail As Outlook.MailItem
   n = 1
For Each olObject In olfdStart.Items
    If TypeName(olObject) = "MailItem" Then

        n = n + 1
        Set olMail = olObject
            Cells(n, 1) = olMail.Subject
            Cells(n, 2) = olMail.ReceivedTime
            Cells(n, 3) = olMail.Body

    End If
Next
Set olMail = Nothing
Set olFolder = Nothing
Set olObject = Nothing
End Sub

3条回答
甜甜的少女心
2楼-- · 2019-07-09 02:43

Work with GetSharedDefaultFolder Method to get access to another user for one or more of their default folders.

Example here is shared Inbox

Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
Dim olRecip As Outlook.Recipient

Set olApp = Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olRecip = olNs.CreateRecipient("0m3r@EmailAddress.com")
Set olFolder = olNs.GetSharedDefaultFolder(olRecip, olFolderInbox)

Or

Set olFolder = olNs.GetSharedDefaultFolder(olRecip, olFolderInbox).Folders("SubfolderName")

GetSharedDefaultFolder Method Returns a MAPIFolder object that represents the specified default folder for the specified user. This method is used in a delegation scenario, where one user has delegated access to another user for one or more of their default folders (for example, their shared Calendar folder).

查看更多
孤傲高冷的网名
3楼-- · 2019-07-09 02:55

Thanks Erdem

Sub ShareMail()

    Dim olNamespace As Outlook.Namespace
    Dim olApp As Outlook.Application
    Dim olNs As Outlook.Namespace
    Dim olFolder As Outlook.MAPIFolder
    Dim olRecip As Outlook.Recipient

    Set olApp = Outlook.Application
    Set olNs = olApp.GetNamespace("MAPI")
    Set olRecip = olNs.CreateRecipient("mail@mail.com")
    Set olFolder = olNs.GetSharedDefaultFolder(olRecip, olFolderInbox).Folders("myfolder")

   Call ProcessFolder(olFolder)

    Set olApp = Nothing
    Set olNs = Nothing
    Set olRecip = Nothing
    Set olFolder = Nothing


End Sub
查看更多
Melony?
4楼-- · 2019-07-09 02:55

If the folder should be the inbox you can use below

Set olFolder = olNS.GetDefaultFolder(olFolderInbox)

Or for a subfolder

Set olFolder = olNS.GetDefaultFolder(olFolderInbox).Folders("mysubfolder")
查看更多
登录 后发表回答