vba中的循环类型不匹配错误

时间:2012-11-29 01:21:21

标签: vba outlook-vba

我正在使用Outlook VBA并构建了一个For Next循环来读取MailItems的主体,其格式类似于Key = Value对。它似乎工作的一点,但在第二次迭代结束时,当它到达“下一个oitem”时,我得到错误抛出“类型不匹配”。好吧,仍然有第三个MailItem被读入,所以我不知道为什么我会收到此错误。任何指导都将不胜感激。

Sub ReadMailItems()

Dim olapp As Outlook.Application
Dim olappns As Outlook.NameSpace
Dim oitem As Outlook.MailItem
Dim ItemsToProcess As Outlook.Items
Dim myFolder As MAPIFolder
Dim sFilter As String
Dim dailyStats As CRBHA_Stats
Dim kvPairs As Collection
Dim Item As KeyValuePair
Dim today As Date
today = Date

On Error GoTo LocalErr

'set outlook objects
Set olapp = New Outlook.Application
Set olappns = olapp.GetNamespace("MAPI")
Set myFolder = olappns.GetDefaultFolder(olFolderInbox)
'Filter or only MailItems received today
sFilter = "[ReceivedTime] >= " & AddQuotes(Format(Date, "ddddd"))
Set ItemsToProcess = Session.GetDefaultFolder(olFolderInbox).Items.Restrict(sFilter)
Set StatsCollection = New Collection

For Each oitem In ItemsToProcess
 If CheckSubject(oitem.Subject) Then
   Set kvPairs = GetKeyValuePairs(oitem.body)
   'Iterate over the Collection and load up
   'an instance of CRBHA_Stats object
   Set dailyStats = New CRBHA_Stats
   dailyStats.SubmissionDate = today
   For Each Item In kvPairs
     If LCase(Item.Key) = LCase("EmployeeID") Then
        dailyStats.EmployeeID = Item.Value
     ElseIf LCase(Item.Key) = LCase("Approved") Then
        dailyStats.Approved = Item.Value
     ElseIf LCase(Item.Key) = LCase("Declined") Then
        dailyStats.Declined = Item.Value
     ElseIf LCase(Item.Key) = LCase("PFA") Then
        dailyStats.PFAs = Item.Value
     ElseIf LCase(Item.Key) = LCase("Followups") Then
        dailyStats.FollowUps = Item.Value
     ElseIf LCase(Item.Key) = LCase("CRA") Then
        dailyStats.CRAs = Item.Value
     End If
    Next Item

    'Add each CRBHA_Stats object to the StatsCollection
    StatsCollection.Add dailyStats

    Debug.Print dailyStats.ToString
    Debug.Print "_____________" & vbCrLf
  End If
Next oitem   '<<<<This is where it cuts out

ExitProc:
Set olapp = Nothing
Set olappns = Nothing
Set myFolder = Nothing
Set ItemsToProcess = Nothing
Set dailyStats = Nothing
Exit Sub

LocalErr:
  If Err.Number <> 0 Then
   Msg = "Error # " & Str(Err.Number) & " was generated by " _
       & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
   MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
   End If
   'Resume Next


End Sub

1 个答案:

答案 0 :(得分:7)

Dim oitem As Object   'not Outlook.MailItem
'....
For Each oitem In ItemsToProcess
    if typename(oitem)="MailItem" then
        'process the mail
        '....
    end if
Next oitem
'........