Sunday, June 26, 2022

[FIXED] How to reference a folder by name?

Issue

When I try to open a non-default mail folder I'm getting

Compile Error: Type Mismatch

It occurs at Set oMailBox.

Sub openSxxInbox()

Dim oOutlook As Outlook.Application
Dim oFolder As Outlook.Folder
Dim oMailBox As Outlook.Folder
Dim oFldr As Outlook.Folder

Set oOutlook = CreateObject("Outlook.Application")
Set oNS = oOutlook.GetNamespace("MAPI")
Set oMailBox = "Sxx"
Set oFldr = "Inbox"

oNS.Logon 'does not do anything if Outlook is already running

Set oFolder = oNS.Folders(oMailBox).Folders(oFldr)

    If (oOutlook.ActiveExplorer Is Nothing) Then
        oFolder.Display
        Else
        Set oOutlook.ActiveExplorer = oFolder
    End If

End Sub

Solution

In the code you may find the following line:

Dim oMailBox As Outlook.Folder

and later you are trying assign a string value which is not correct:

Set oMailBox = "Sxx"
Set oFldr = "Inbox"

There is no direct cast between folder objects and strings. You can use the NameSpace.GetDefaultFolder method which returns a Folder object that represents the default folder of the requested type for the current profile; for example, obtains the default Inbox folder for the user who is currently logged on.

Note, you may find the Store.GetDefaultFolder method helpful which returns a Folder object that represents the default folder in the store and that is of the type specified by the FolderType argument. This method is similar to the GetDefaultFolder method of the NameSpace object. The difference is that this method gets the default folder on the delivery store that is associated with the account, whereas NameSpace.GetDefaultFolder returns the default folder on the default store for the current profile.

Also you can define the object as string in the code:

Sub openSxxInbox()

Dim oOutlook As Outlook.Application
Dim oFolder As Outlook.Folder
Dim oMailBox As string
Dim oFldr As string

Set oOutlook = CreateObject("Outlook.Application")
Set oNS = oOutlook.GetNamespace("MAPI")
oMailBox = "Sxx"
oFldr = "Inbox"

oNS.Logon 'does not do anything if Outlook is already running

Set oFolder = oNS.Folders(oMailBox).Folders(oFldr)

    If (oOutlook.ActiveExplorer Is Nothing) Then
        oFolder.Display
        Else
        Set oOutlook.ActiveExplorer = oFolder
    End If

End Sub


Answered By - Eugene Astafiev
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.