Excel vbamacros在2007年得到types不匹配错误,但在2010年工作

我在Windows 7的Excel 2010中testing了这个macros,并且testing了另外一个Windows 7计算机,但是使用了Excel 2007.在两者上工作,但是当我尝试在工作计算机(Windows 7,Excel 2007)上使用它时,在第一个“下一个”语句中input“不匹配错误”。 抬头,发现我可以使用“退出”而不是“下一个”,但它只是抱怨下一行包含“结束如果”。 现在它宣称“结束如果没有块如果”。 我想我只是不明白这是如何在一台Win7 \ Excel 2007计算机上工作,而不是其他。

macros只是search电子邮件主题中所选单元格的值(如果单元格尚未着色),如果匹配,则会更改单元格的颜色。

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 

如果有人有任何想法,他们将不胜感激。

这是一个想法 – 你的olItem被定义为一个mailItem 。 当邮箱中的下一个项目不是邮件项目时,代码可能会失败? 日历请求或其他事情会导致这种情况? 您可能希望在内部循环中添加一个Debug.Print语句,以查看正在查看的对象 – 并查看该循环是否确实执行,直至遇到收件箱中的一个奇怪项目。

作为一个快速修复,如果你允许它是一个变种,你不会得到一个types错误。 所以你只要声明为

 Dim olItem 

没有as mailItem

这是一个远射。