VBA(Excel)在每个循环上运行时错误13

我在这个代码中find了这个奇怪的问题。 我试图从Outlook中的所有子文件夹中列出Excel中的所有电子邮件:

我已经search了几个星期,没有任何运气。

'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在上述行,当我打debugging它告诉我,olItem =没有! – 当我单击时,代码再次运行良好。

我试图插入一个“ON错误”,但是我的列表不包含所有的电子邮件。

我是编程VBA的新手,所以请裸照我。

提前致谢

我正在禁止我的代码给你:)

更改
Dim olItem As Outlook.MailItem

Dim olItem As Object

不是所有的文件夹项目都是mailitems,所以避免用这种方式来标注你的olItemvariables。 这个改变在我的机器上工作得很好,而最初我有和你一样的错误