Pregunta

I made and tested this macro in Excel 2010 on Windows 7, also tested with another Windows 7 computer but with Excel 2007. Worked on both, but when I try to use it on my work computer (Windows 7, Excel 2007) I get the "type mismatch error" at the first "Next" statement. Looked up and found I could use "Exit For" instead of "next" but then it just complains about the next line that contains "End If". Now it claims "End If without block If". I guess I just can't understand how this worked on one Win7\Excel 2007 computer but not the other.

The macro simply searches for the values of the selected cells in email subjects(if the cell isn't already colored), if there is a match, it changes the color of the cell.

Sub MultipleCellSubjectSearch()

'This macro searches for the selected cell values (if there is no cell color), when it finds a match it turns the cell color yellow

Dim olApp As Outlook.Application
Dim olNamespace As Outlook.Namespace
Dim olItem As MailItem
Dim olInbox  As Outlook.MAPIFolder
Dim olFolder As Outlook.MAPIFolder
Dim oCell As Range

'The following sets the Outlook folder to search
Set olApp = New Outlook.Application
Set olNamespace = olApp.GetNamespace("MAPI")
Set olInbox = olNamespace.GetDefaultFolder(olFolderInbox)

'The following searches for cell value string in subject
For Each oCell In Selection
    If oCell.Interior.Pattern = xlNone Then
        For Each olItem In olInbox.Items
            If InStr(olItem.Subject, (oCell.Value)) <> 0 Then
            oCell.Interior.ColorIndex = 6
            End If
        Next
    End If
Next

Set olInbox = Nothing
Set olNamespace = Nothing
Set olApp = Nothing

End Sub

If anyone has any ideas, they would be greatly appreciated.

¿Fue útil?

Solución

Here is a thought - your olItem is defined as a mailItem. It is possible that the code fails when your next item in the mailbox is not a mail item? Would a calendar request or something else cause this? You might want to put a Debug.Print statement in the inner loop to see what objects are being looked at - and see if the loop does in fact execute until it comes across a strange item in your inbox...

As a quick fix, if you allowed it to be a variant, you would not get a type error. So you would just declare it as

Dim olItem

without the as mailItem

It's a long shot.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top