I wanted to run a VB script in MS-Outlook 2010, in a rule applied to every incoming messages, but I was not sure what was the cause of the issue preventing it to run as I expected.
It meant to find e-mails that contain a desired word in its body, but in various upper/lower letter combination, e.g. “Sometext”, “sometext”, or “SOMETEXT”. Then make them “Unreaded” and then move them to “Deleted Items” folder.
So I tried the following way to pinpoint the point of error, as I was not able to find out a way to use the debug option of VB (I am not quite sure if it is even possible).
- I added “On Error GoTo” statement to the VB script, to find out where and why this error ever happen.
- I added an error “Handler” part to the VB script, and run the script against some sample e-mails.
- Thanks to “Pinpointing the Exact Line Where A Crash Occurs in VB6 or VBA” that has made finding the line of error possible for me, using “Erl”, knowing where the error occurred is just to read the error message of the “MsgBox”.
The following is the complete VB code. Pay attention to line numbers, in fact they are the trick to make “Erl” shows the error line number.
Sub CheckSpam(Item As Outlook.MailItem)
Dim deletedFolder As Outlook.Folder
10 On Error GoTo Handler
20 If InStr(LCase(Item.Body), "sometext") > 0 Then ' "sometext" all in lower case
30 Set deletedFolder = Application.GetNamespace("MAPI"). _
40 Item.UnRead = False
50 Item.Move (deletedFolder)
60 Set deletedFolder = Nothing
760 End If
80 Exit Sub
90 MsgBox "Error Line: " & Erl & vbCrLf & _
"Error: (" & Err.Number & ") " & Err.Description, vbCritical
- Then after running on sample e-mail message, I realized that line 50 give the following error:
“Object is required”.
- By replacing line 50 with the following the issue has been removed.
50 Item.Move deletedFolder
I don’t know why the parenthesis should be removed but by looking at some examples I have realized that this is the cause of error.