Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem counting in a loop 1

Status
Not open for further replies.

robcarr

Programmer
May 15, 2002
633
GB
Dear All,

I am using the coding below to count emails in each subfolder within the Inbox, but all it does is count 1 in each folder, does anyone know why it wont count all items in the folder. Here is the coding.

Sub Count_Items_In_Folders()
Dim objApp As Object
Dim namespace As namespace
Set objApp = CreateObject("Outlook.Application")
Set mynamespace = objApp.GetNamespace("MAPI")
Set myFolders = mynamespace.GetDefaultFolder(6)
Set mycollection = myFolders.Folders
For I = 1 To mycollection.Count
Set myfolder = mycollection.Item(I)
For Each myfolder In mycollection
If Err = 0 Then
Set objItem = myfolder.Items(I)
If objItem.UnRead Then
unreadm = unreadm + 1
Else
readm = readm + 1
End If
Err.Clear
End If
Next
MsgBox "Number of Unread Emails is :" & unreadm & ".", vbInformation
MsgBox "Number of Read Emails is :" & readm & ".", vbInformation
Next

End Sub


Thanks Rob.[yoda]
 

For I = 1 To mycollection.Count
Set myfolder = mycollection.Item(I)
For Each myfolder In mycollection

The code above is a redundant loop in loop structure - the first for does exactly the same as the second for. In you have mycollection.count=3, then the code inside the loops will execute 3x3=9 times. In each inside loop, the value of i does not change.
The following code works (although it's very slow on my PC):

Dim objApp As Outlook.Application
Dim ns As Outlook.namespace
Dim fld As Outlook.MAPIFolder
Dim fldInbox As Outlook.MAPIFolder
Dim mi As Outlook.MailItem
Dim unreadm As Integer, readm As Integer
Set objApp = GetObject(, "Outlook.Application")
Set ns = objApp.GetNamespace("MAPI")
Set fldInbox = ns.GetDefaultFolder(6)
For Each fld In fldInbox.Folders
unreadm = 0: readm = 0
For Each mi In fld.Items
If mi.UnRead Then
unreadm = unreadm + 1
Else
readm = readm + 1
End If
Next
MsgBox fld.Name & ":Number of Unread Emails is :" & unreadm & ".", vbInformation
MsgBox "Number of Read Emails is :" & readm & ".", vbInformation
Next

Rob
[flowerface]
 
Rob,
Thanks for doing this it works really well.

Rob. Thanks Rob.[yoda]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top