vba - 首次运行后对共享文件夹的引用丢失

标签 vba error-handling outlook move shared-directory

我想将电子邮件从共享收件箱移到同一收件箱中的共享子文件夹。
我有两个邮箱,共享的是第二个。
“出站TTA” =第二个共享邮箱的名称。
“接收” =“出站TTA”中收件箱文件夹的名称
“MyFolderEmails” =“接收”文件夹中子文件夹的名称。
该代码只能在一次运行!
第二次显示

Run-time error '-2147221233 (8004010f)':The attempted operation failed. An object could not be found.


错误出现在Set sharedDestinationFolder = sharedInbox.Folders("MyFolderEmails")
Public Sub test2()
    MoveSelectionToFolder
End Sub


Private Sub MoveSelectionToFolder()
    Dim NS As nameSpace

    Dim sharedInbox As folder
    Dim sharedDestinationFolder As folder

    Dim sharedItems As Selection

    Dim i As Long

    Set NS = Application.GetNamespace("MAPI")
    Set sharedInbox = NS.Folders("Outbound TTA").Folders("réception")
    Set sharedDestinationFolder = sharedInbox.Folders("MyFolderEmails")
        
    Set sharedItems = ActiveExplorer.Selection

    For i = sharedItems.Count To 1 Step -1
        sharedItems(i).Move sharedDestinationFolder
    Next i

    Set NS = Nothing
    Set sharedItems = Nothing
    Set sharedInbox = Nothing
    Set sharedDestinationFolder = Nothing

End Sub
同样,即使相似的代码也有相同的命运,只能工作一次;之后,他们显示错误。

最佳答案

确定尝试将对文件夹的引用保留为静态变量,例如这样。 (重新启动Outlook,然后使用代码)

' Set it as a static variable
Global sharedDestinationFolder As Folder

Public Sub test2()
    MoveSelectionToFolder
End Sub


Private Sub MoveSelectionToFolder()
    Dim NS As Namespace

    Dim sharedInbox As Folder
    'Dim sharedDestinationFolder As Folder

    Dim sharedItems As Selection

    Dim i As Long
       
    If sharedDestinationFolder Is Nothing Then
        Set NS = Application.GetNamespace("MAPI")
        Set sharedInbox = NS.Folders("Outbound TTA").Folders("réception")
        Set sharedDestinationFolder = sharedInbox.Folders("MyFolderEmails")
        
        MsgBox "Setting destination folder"
    End If
        
    Set sharedItems = ActiveExplorer.Selection

    For i = sharedItems.Count To 1 Step -1
        If TypeName(sharedItems(i)) = "MailItem" Then
            sharedItems(i).Move sharedDestinationFolder
        End If
    Next i

    Set NS = Nothing
    Set sharedItems = Nothing
    Set sharedInbox = Nothing
    'Set sharedDestinationFolder = Nothing

End Sub
理论上,第一次运行代码时,您将看到消息框。当您再次运行它时,它不会是Nothing,因此,它应该具有对正确文件夹的有效引用(理论上也是)

关于vba - 首次运行后对共享文件夹的引用丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62822143/

相关文章:

vba : Can't seem to turn off the "making unconstrained variables non-negative" option for Solver

html - UIWebView从包中加载html文件,并提供文件信息?

java - 如何解决java中的响应代码406错误?

vba - Access VBA 以表格格式将查询结果发送到 Outlook 电子邮件

excel - 搜索列标题从右到左 vba

vba - Excel UDF 参数返回单元格引用而不是值

vba - 在过程结束和错误处理程序中编写结束语句的好习惯是什么?

php - 如何在 PHP 中禁用错误​​抑制 "@"运算符?

Java EE/Struts 异常处理

html - Outlook 为小于 15 像素的图像添加边距顶部