How to reference item to count messages in inbox?

A small error is preventing this counting code from operating.

Sub Count2
  Dim objOutlook As Object, objnSpace As Object, objFolder As Object
  Dim Count As Integer
  Set objOutlook = CreateObject("Outlook.Application")
  Set objnSpace = objOutlook.GetNamespace("MAPI")

  Set objFolder = objnSpace.Folders("My Personal Emails").Folders("spam")
  If Err.Number <> 0 Then
    Err.Clear
    MsgBox "No such folder."
    Exit Sub
  End If

  For Each MapiItem In MapiFolderInbox.Messages
  Select Case Weekday(MapiItem.TimeReceived)
    Case vbMonday
      Count = Count + 1
    End Select
  Next MapiItem

  MsgBox "Number of spam messages sent on a Monday: " & Count
End Sub

The error message:

Run-time error '424': Object required

The debugger highlights the line:

For Each MapiItem In MapiFolderInbox.Messages

Solution 1:

Ok, here's a working version:

Sub Count2()

Dim i As Integer, Count As Integer
Dim objOutlook As Outlook.Application
Dim objNSpace As Outlook.NameSpace
Dim objFolder As Outlook.Folder

Set objOutlook = CreateObject("Outlook.Application")
Set objNSpace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNSpace.Folders("My Personal Emails").Folders("spam")

Count = 0
For i = 1 To objFolder.Items.count

  If Weekday(objFolder.Items(i).ReceivedTime) = vbMonday Then
    Count = Count + 1
  End If

Next i

MsgBox "Number of spam messages sent on a Monday: " & Count

End Sub

Solution 2:

Edit: -- it seems you wish to count Spam messages, judging by the last string in your VBA code. Going with @sitnik's solution seems the better approach.

MapiFolderInbox seems to be undefined -- try assigning it to your Inbox folder, something like:

 Set MapiFolderInbox = objnSpace.Folders("My Personal Emails").Folders("Inbox")

Also see: Option Explicit On