2015-08-03 94 views
0

我想实现一个VBA应用程序,它使用选定的对象(电子邮件,任务,文件夹)。VBA,MS Outlook,文件夹项目

我的Application.ActiveExplorer.Selection.Item(i_item)尝试似乎只返回邮件,任务,日历条目或笔记,但从来没有一个文件夹(例如'收件箱\')。 当用户选择一封电子邮件,然后启动VBA宏时,解决方案Application.ActiveExplorer.Selection.Item(i_item)可提供所需的结果。

但是,如果Outlook用户选择的最后一个项目是一个文件夹(例如“发送邮件”)。然后VBA makro开始,比宏应该收回文件夹项目(没有额外的用户交互)。目前情况并非如此。上面的代码仍然提供电子邮件或任务。

如何检查,如果最后一个选择是在一个文件夹(而不是电子邮件等)? 如何访问文件夹项目?

如果这是不可能的,我会切换回Pickfolder(就像Darren Bartrup-Cook提议的那样),但这不是我预先解决的问题。

回答

1

我想获取所选文件夹以更改其图标,所以我们的代码在某种程度上是相同的。 我注意到Application.ActiveExplorer.Selection.Item(i_item)它不是完美的,因为它会抛出空文件夹或日历等异常。所以我使用Application.ActiveExplorer.CurrentFolder.DefaultMessageClassApplication.ActiveExplorer.NavigationPane.CurrentModule.NameApplication.ActiveExplorer.NavigationPane.CurrentModule.NavigationModuleType)为了找出我真正在哪里。

通过这种方法很容易获得当前选定的文件夹

Dim folder As Outlook.MAPIFolder 
Dim folderPath As String, currItemType As String 
Dim i As Integer 

currItemType = Application.ActiveExplorer.CurrentFolder.DefaultMessageClass 
If currItemType = "IPM.Note" Then 'mail Item types https://msdn.microsoft.com/en-us/library/office/ff861573.aspx 
    Set folder = Application.ActiveExplorer.CurrentFolder 
    folderPath = folder.Name 
    Do Until folder.Parent = "Mapi" 
     Set folder = folder.Parent 
     folderPath = folder.Name & "\" & folderPath 
    Loop 
Debug.Print folderPath 
End If 

没有得到一个问题呢。就你而言,你可以将选择存储在一个全局变量中,这样你总能知道最后选择了哪个文件夹。

+0

很酷。工作正常。谢谢。 – BerndGit

1

此过程将要求您选择文件夹。
如果中断代码并检查mFolderSelectedMySelectedFolder,那么你应该可以想些办法:

Public Sub Test() 

    Dim MySelectedFolder As Variant 
    Set MySelectedFolder = PickFolder 

End Sub 

Public Function PickFolder() As Object 

    Dim oOutlook As Object   'Outlook.Application 
    Dim nNameSpace As Object  'Outlook.Namespace 
    Dim mFolderSelected As Object 'Outlook.MAPIFolder 

    On Error GoTo ERROR_HANDLER 

    Set oOutlook = CreateObject("Outlook.Application") 
    Set nNameSpace = oOutlook.GetNameSpace("MAPI") 

    Set mFolderSelected = nNameSpace.PickFolder 

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    'The commented out code will return only email folders. ' 
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 
    If Not mFolderSelected Is Nothing Then 
'  If mFolderSelected.DefaultItemType = 0 Then 
      Set PickFolder = mFolderSelected 
'  Else 
'   Set PickFolder = Nothing 
'  End If 
    Else 
     Set PickFolder = Nothing 
    End If 

    Set nNameSpace = Nothing 
    Set oOutlook = Nothing 

    On Error GoTo 0 
    Exit Function 

ERROR_HANDLER: 
    Select Case Err.Number 

     Case Else 
      MsgBox "Error " & Err.Number & vbCr & _ 
       " (" & Err.Description & ") in procedure PickFolder." 
      Err.Clear 
    End Select 

End Function 

注:这是写在Excel中使用并有后期绑定 - 你需要将其更新为在Outlook中工作(无需参考Outlook开始)。

+0

谢谢Darren,我可以用它作为解决方法。我的想法稍有不同。我会在上面的编辑中更详细地解释。 – BerndGit