我在这个代码中遇到了这个奇怪的问题。我试图在Outlook的所有子文件夹中列出Excel中的所有电子邮件:
我已经搜索并研究了几个星期而没有任何运气。
'Requires reference to Outlook library
Option Explicit
Public Sub ListOutlookFolders()
Dim olApp As Outlook.Application
Dim olNamespace As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
Dim rngOutput As Range
Dim lngCol As Long
Dim olItem As Outlook.MailItem
Dim rng As Excel.Range
Dim strSheet As String
Dim strPath As String
Set rngOutput = ActiveSheet.Range("A1")
Set olApp = New Outlook.Application
Set olNamespace = olApp.GetNamespace("MAPI")
For Each olFolder In olNamespace.Folders
rngOutput = olFolder.Name
rngOutput.Offset(0, 1) = olFolder.Description
Set rngOutput = rngOutput.Offset(1)
For Each olItem In olFolder.Items
Set rngOutput = rngOutput.Offset(1)
With rngOutput
.Offset(0, 1) = olItem.SenderEmailAddress ' Sender
End With
Next
Set rngOutput = ListFolders(olFolder, 1, rngOutput)
Next
Set olFolder = Nothing
Set olNamespace = Nothing
Set olApp = Nothing
End Sub
Function ListFolders(MyFolder As Outlook.MAPIFolder, Level As Integer, theOutput As Range) As Range
Dim olFolder As Outlook.MAPIFolder
Dim olItem As Outlook.MailItem
Dim lngCol As Long
For Each olFolder In MyFolder.Folders
theOutput.Offset(0, lngCol) = olFolder.Name
Set theOutput = theOutput.Offset(1)
If (olFolder.DefaultItemType = olMailItem) And (Not olFolder.Name = "Slettet post") Then
For Each olItem In olFolder.Items
If olItem.Class = olMail Then
With theOutput
.Offset(0, 1) = olItem.SenderEmailAddress ' Sender
End With
Set theOutput = theOutput.Offset(1)
End If
Next olItem <--- ERROR 13 here
End If
If olFolder.Folders.Count > 0 Then
Set theOutput = ListFolders(olFolder, Level + 1, theOutput)
End If
Next olFolder
Set ListFolders = theOutput.Offset(1)
End Function
代码运行正常10-20项,然后在上述行中给我一个运行时错误13,当我点击调试它告诉我olItem = = Nothing!? - 当我单步执行时,代码再次运行一段时间。
我试图插入&#34; ON ERROR&#34;但是我的列表并不包含所有电子邮件。
我是编程VBA的新手,所以请光临我。
提前致谢
答案 0 :(得分:3)
我正在向你解释我的代码:)
更改
Dim olItem As Outlook.MailItem
到
Dim olItem As Object
并非所有文件夹项都是mailitems,因此请避免以这种方式标注olItem
变量。这个改变在我的机器上运行良好,而最初我遇到了同样的错误