Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vba - Get MAPI Folder in Outlook from Folder Path

I am trying to use the function from on this page: http://www.outlookcode.com/d/code/getfolder.htm to use the folder path to navigate to a folder. (I will copy that code onto the bottom of this question--I used it as-is, unmodified at all.) The reason I need to use this is that the default inbox in Outlook is not the same as the inbox I need to be active. I know the path of the relevant inbox by right clicking on it and hit properties, and looking at location.

This is the code I use:

Set objOutlook = CreateObject("Outlook.Application", "localhost")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set Inbox = GetFolder("\[email protected]")
Debug.Print Inbox '<-- This fails
Set InboxItems = Inbox.Items '<-- This also fails
InboxItems.SetColumns ("SentOn")

This returns runtime error 91, Object variable or With block variable not set.

I have no idea what this means. If you could help me solve this error, that would be awesome, and if you have a way that I could avoid this problem entirely, that would be awesome also. Thanks!

Public Function GetFolder(strFolderPath As String)As MAPIFolder
  ' strFolderPath needs to be something like 
  '   "Public FoldersAll Public FoldersCompanySales" or
  '   "Personal FoldersInboxMy Folder"

  Dim objApp As Outlook.Application
  Dim objNS As Outlook.NameSpace
  Dim colFolders As Outlook.Folders
  Dim objFolder As Outlook.MAPIFolder
  Dim arrFolders() As String
  Dim I As Long
  On Error Resume Next

  strFolderPath = Replace(strFolderPath, "/", "")
  arrFolders() = Split(strFolderPath, "")
  Set objApp = 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found the answer. Turns out it's something stupid, as per usual :)

Set Inbox = GetFolder("\[email protected]")

needs to be

Set Inbox = GetFolder("[email protected]/inbox")

. This fixes the problem. I figured I would leave this here in case anyone else has this problem, the solution is simply to follow the given format...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...