我花了很多时间研究这个问题,但我还没有找到完整的答案。我要做的是从 Outlook 中获取 100封最近的电子邮件,并将它们粘贴到 Excel 工作簿中。我已经构建了一个代码(从几个不同的网站借来的)已经实现了这一点,但它缺少“最新”部分。
当我在 Excel 中执行此代码时,会打印出 101 行,其中包含我指定的信息,这是好的。但它不是最近的电子邮件。如果您在下图中看到,现在的时间是晚上 7:18,但导入 Excel 的电子邮件仅从今天和之前的下午 2:17 开始。(出于隐私原因,我将其他列涂黑)
最初,这些电子邮件只是从 2014 年 5 月的某个随机日期粘贴进来的。我在 Outlook 2013 上删除了我的帐户并重新添加了它,那时 Excel 代码从今天下午 2:17 开始抓取它,而不是几个月前。基于此,我认为这与仅读取在帐户链接到 Outlook 时创建的 PST 文件的代码有关,但我不完全确定。
我已经广泛搜索了这个问题,似乎没有人遇到同样的问题。我只是想知道是否有一种方法可以修改我的代码以仅获取最近的电子邮件。我不想抓取原始 PST 文件中的存档电子邮件。有没有办法在每次执行代码时重建 PST 文件?有没有一种方法可以只从活动的 Outlook 窗口中读取代码,而不是从存档文件中读取?任何建议将不胜感激。
这是我的代码:
Sub Test()
'Dim objOL As Object
'Set objOL = CreateObject("Outlook.Application")
Dim objOL As Outlook.Application
Set objOL = New Outlook.Application
Dim OLF As Outlook.MAPIFolder
Set OLF = GetObject("", "Outlook.Application").GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Dim CurrUser As String
Dim EmailItem
Dim i As Integer
Dim EmailCount As Integer
Dim WS As Worksheet ' assigns variable WS to being a new worksheet
Application.ScreenUpdating = False
Set WS = Sheets.Add(After:=Sheets(Worksheets.Count)) ' creates a new worksheet
ActiveSheet.Name = "List of Received Emails" ' renames the worksheet
' adds the headers
Cells(1, 1).Formula = "From:"
Cells(1, 2).Formula = "Cc:"
Cells(1, 3).Formula = "Subject:"
Cells(1, 4).Formula = "Date"
Cells(1, 5).Formula = "Received"
With Range("A1:E1").Font ' range of cells and the font style
.Bold = True
.Size = 14
End With
EmailItemCount = OLF.Items.Count
i = 0
EmailCount = 0
' reads e-mail information
While i < 100
i = i + 1
With OLF.Items(i)
EmailCount = EmailCount + 1
Cells(EmailCount + 1, 1).Formula = .SenderName
Cells(EmailCount + 1, 2).Formula = .CC
Cells(EmailCount + 1, 3).Formula = .Subject
Cells(EmailCount + 1, 4).Formula = Format(.ReceivedTime, "mm/dd/yyyy")
Cells(EmailCount + 1, 5).Formula = Format(.ReceivedTime, "hh:mm AMPM")
End With
Wend
Set OLF = Nothing
Columns("A:D").AutoFit
Range("A2").Select
Application.StatusBar = False
End Sub
PS 我确实在我的 Excel 工作簿中启用了 Microsoft Outlook 15.0 对象库参考。