从Excel引用Outlook文件夹

时间:2017-01-05 00:58:48

标签: excel vba excel-vba outlook outlook-vba

我创建了一个宏来读取Outlook电子邮件并将值和标题(主题时间已发送等)提取到Excel。

之前有效,但现在提示错误“尝试的操作失败。无法找到对象”。

文件夹的位置是“收件箱/ TIBCO报告文件夹”。错误是在行

提示
Set olFolder = olFolder.Folders(1).Folders("Inbox").Folders("TIBCO Reports Folder")

以下是代码的一部分:

Dim olApp As Object
Dim olFolder As Object
Dim olMailItem As Object

Dim strTo As String
Dim strFrom As String
Dim dateSent As Variant
Dim dateReceived As Variant
Dim strSubject As String
Dim strBody As String

Dim date1 As Date
Dim date2 As Date

Dim loopControl As Variant
Dim mailCount As Long
Dim totalItems As Long
 '-------------------------------------------------------------

 '//Turn off screen updating
Application.ScreenUpdating = False

 '//Clearing worksheet content
 'Sheets("OutlookEmail").Cells.Clear

 '//Setup headers for information
Sheets("OutlookEmail").Select
Range("A1:F1").Value = Array("Subject", "From", "Date/Time Sent", "Date/Time Received", "To", "Attachment")

 '//Format columns E and F to
Columns("C:D").EntireColumn.NumberFormat = "MM/DD/YYYY HH:MM:SS"

 '//Create instance of Outlook
Set olApp = CreateObject("Outlook.Application")

 '//Select folder to extract mail from
Set olFolder = olApp.GetNamespace("MAPI")
Set olFolder = olFolder.Folders(1).Folders("Inbox").Folders("TIBCO Reports Folder")

2 个答案:

答案 0 :(得分:2)

当您使用Excel中的Outlook时,请设置Outlook收件箱引用,如下所示。

Option Explicit
Public Sub Example()
    Dim olApp As Outlook.Application
    Dim olNS As Outlook.Namespace
    Dim Inbox As Outlook.MAPIFolder
    Dim Items As Outlook.Items
    Dim i As Long

    '// Ref to Outlook Inbox
    Set olApp = New Outlook.Application
    Set olNS = olApp.GetNamespace("MAPI")
    Set Inbox = olNS.GetDefaultFolder(olFolderInbox).Folders("Folder Name")

    Set Items = Inbox.Items

    For i = Items.count To 1 Step -1
        Debug.Print Items(i) '
'       do something with Items
    Next
End Sub

确保在VBE的工具>参考菜单中设置Microsoft Outlook对象XX.X

请参阅此处的另一个示例https://stackoverflow.com/a/40356349/4539709

答案 1 :(得分:1)

不是答案,而是一个太长而无法发表评论的调试策略。

这样的行
Set olFolder = olFolder.Folders(1).Folders("Inbox").Folders("TIBCO Reports Folder")

很难调试。每个点(.)都尝试访问一个属性。其中一次尝试失败了。你不知道哪一个,因为有三个。

你可以做的是用行替换那一行

Set oFolder = olFolder.Folders(1)
Set oFolder = olFolder.Folders("Inbox")
Set oFolder = olFolder.Folders("TIBCO Reports Folder")

这三行中的一行将失败。看看哪一个可以让您专注于调试工作。