VBA OUTLOOK CODE 组织默认文件夹子文件夹

问题描述 投票:0回答:1

我正在寻找组织默认文件夹子文件夹,但我似乎无法正确编码,有人可以看一下吗?

文件夹结构

Sub OrganizeEmailsBySender()
    Dim olApp As Outlook.Application
    Dim olNamespace As Outlook.NameSpace
    Dim olInbox As Outlook.Folder
    Dim olBackupFolder As Outlook.Folder
    Dim olBackupEnd2022Folder As Outlook.Folder
    Dim olMail As Outlook.mailItem
    Dim olItems As Outlook.Items
    Dim olSenderFolder As Outlook.Folder
    Dim olSenderName As String
    Dim olItem As Object
    Dim i As Long
    
    ' Initialize Outlook application and namespace
    Set olApp = Outlook.Application
    Set olNamespace = olApp.GetNamespace("MAPI")
    
    ' Specify the default folder and the BACKUP END 2022 folder within it
    Set olBackup = olNamespace.GetDefaultFolder(olFolderBACKUP)
    Set olBackupEnd2022 = olBackup.Folders("BACKUP END 2022")
    Set olItems = olBackupEnd2022Folder.Items
    
    ' Loop through each email in the BACKUP END 2022 folder
    For i = olItems.Count To 1 Step -1
        Set olItem = olItems(i)
        
        ' Check if the item is a mail item
        If TypeOf olItem Is Outlook.mailItem Then
            Set olMail = olItem
            olSenderName = olMail.SenderName
            
            ' Check if a folder for the sender already exists
            On Error Resume Next
            Set olSenderFolder = olBackupEnd2022Folder.Folders(olSenderName)
            On Error GoTo 0
            
            ' If the folder does not exist, create it
            If olSenderFolder Is Nothing Then
                Set olSenderFolder = olBackupEnd2022Folder.Folders.Add(olSenderName)
            End If
            
            ' Move the email to the sender's folder
            olMail.Move olSenderFolder
        End If
    Next i
    
    ' Clean up
    Set olMail = Nothing
    Set olItems = Nothing
    Set olInbox = Nothing
    Set olBackupFolder = Nothing
    Set olBackupEnd2022Folder = Nothing
    Set olSenderFolder = Nothing
    Set olNamespace = Nothing
    Set olApp = Nothing
    
    MsgBox "Emails have been organized by sender's name.", vbInformation
End Sub

出现 OBJECT REQUIRED 错误

设置 olBackupEnd2022 = olBackup.Folders("备份 2022 年结束")

vba outlook
1个回答
0
投票

Outlook 对象模型中没有

olFolderBACKUP
枚举。唯一可用的值列在 https://learn.microsoft.com/en-us/office/vba/api/outlook.oldefaultfolders

最好在代码中使用

Option Explicit
来防止 VB 运行时允许使用未声明的变量和常量。否则未声明的
olFolderBACKUP
将默认为 0。

在您的特定情况下,要按名称打开与默认收件箱文件夹位于同一级别的文件夹,您可以使用其中之一

Set olBackup = olNamespace.GetDefaultFolder(olFolderInbox).Parent.Folders("BACKUP")

Set olBackup = olNamespace.DefaultStore.GetRootFolder.Folders("BACKUP")
© www.soinside.com 2019 - 2024. All rights reserved.