2012-04-12 118 views
1

我在這個代碼中找到了這個奇怪的問題。我試圖從Outlook中的所有子文件夾中列出Excel中的所有電子郵件:VBA(Excel)每個循環的運行時錯誤13 on

我已經搜索並研究了幾個星期沒有任何運氣。

'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是=什麼!? - 當我單步執行時,代碼再次運行良好。

我試圖插入一個「ON ERROR」,但後來我的列表中沒有包含所有的電子郵件。

我是編程VBA的新手,所以請隨身攜帶。

在此先感謝

回答

3

我裸露我的代碼給你:)

變化
Dim olItem As Outlook.MailItem

Dim olItem As Object

並非所有的文件夾項目將mailitems,所以要避免以這種方式確定您的olItem變量的尺寸。這個改變在我的機器上工作正常,而最初我有同樣的錯誤,你做了

+1

謝謝!它的作用像魅力! – Axbogen 2012-04-12 11:22:31

+0

漂亮的漁獲@brettdj – Jesse 2012-04-12 16:50:01