2016-06-08 69 views
0

我想在運行宏下面運行,它給了我錯誤「對象變量或塊變量未設置」。對象變量或在運行宏時沒有設置塊變量

我的代碼:

Dim i As Long 
Public WithEvents olInboxItems As Items 

Public Sub Application_Startup() 
    Dim objNS As NameSpace 
    Set objNS = Application.Session 
    Set olInboxItems = GetFolderPath("Fulfilment.qatar\Inbox\Team Helpdesk May 2016").Items 
Set objNS = Nothing 
End Sub 

Public Sub olInboxItems_ItemAdd(ByVal Item As Object) 
    Dim strCat As String 

    If Item.Class = olMail Then 

    Select Case i 
    Case 0 
      strCat = "Case 0" 
    Case 1 
      strCat = "Case 1" 
    Case 2 
      strCat = "Case 2" 
    Case 3 
      strCat = "Case 3" 
    Case 4 
      strCat = "Case 4" 
    End Select 

    Item.Categories = strCat 
      Item.Save 
     Err.Clear 
    End If 
    i = i + 1 
    Debug.Print i 
    If i = 5 Then i = 0 
End Sub 


' Use the GetFolderPath function to find a folder in non-default mailboxes 
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 
+0

埃羅91下面的代碼: – user2646207

+0

公用Sub Application_Startup() 昏暗objNS作爲命名空間 設置objNS = Application.Session 設置olInboxItems = GetFolderPath( 「Fulfilment.qatar \收件箱\團隊服務檯2016年5月」)的項目 設置。 objNS = Nothing End Sub – user2646207

回答

0

看起來像下面的文件夾路徑不存在:

GetFolderPath("Fulfilment.qatar\Inbox\Team Helpdesk May 2016"). 

確保在Outlook中存在指定的文件夾中。

另外,我建議使用Namespace類的GetDefaultFolder方法,該方法返回一個Folder對象,該對象表示當前配置文件請求類型的默認文件夾;例如,爲當前登錄的用戶獲取默認的日曆文件夾。要返回特定的非默認文件夾,請使用Folders集合。

Sub ChangeCurrentFolder() 
    Dim myNamespace As Outlook.NameSpace 
    Set myNamespace = Application.GetNamespace("MAPI") 
    Set Application.ActiveExplorer.CurrentFolder = _ 
    myNamespace.GetDefaultFolder(olFolderCalendar) 
End Sub 

您可能還會發現Store類的GetDefaultFolder方法有幫助。該方法類似於NameSpace對象的GetDefaultFolder方法。區別在於此方法獲取與帳戶關聯的交付存儲的默認文件夾,而NameSpace.GetDefaultFolder返回當前配置的默認存儲的默認文件夾。