运行宏

时间:2016-06-08 07:49:55

标签: outlook-vba

我正在尝试在宏下运行,同时这样做会给出错误“对象变量或未设置块变量”。

我的代码:

    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

1 个答案:

答案 0 :(得分:0)

看起来以下文件夹路径不存在:

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

确保Outlook中存在指定的文件夹。

此外,我建议使用Namespace类的GetDefaultFolder方法,该方法返回一个Folder对象,该对象表示当前配置文件所请求类型的默认文件夹;例如,获取当前登录用户的默认日历文件夹。要返回特定的非默认文件夹,请使用“文件夹”集合。

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

您可能还会发现Store类的GetDefaultFolder方法很有帮助。此方法类似于GetDefaultFolder对象的NameSpace方法。区别在于此方法获取与该帐户关联的传递存储上的默认文件夹,而NameSpace.GetDefaultFolder返回当前配置文件的默认存储上的默认文件夹。