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 Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Error handler only works once in loop 1

Status
Not open for further replies.

may1hem

Programmer
Jul 28, 2002
262
GB
I'm looping through a collection of items and I'm deliberately creating an error, just to test the error handler.

The error trap works correctly for the first item in the FOR..NEXT loop, but on the second item it doesn't work and instead Outlook brings up an error message "type mismatch".

Of course I understand the error, but why doesn't the error trap work the second time around?

----------------------------------
Set ol = CreateObject("Outlook.Application")
Set myNameSpace = ol.Application.GetNamespace("MAPI")
Set myFolder = myNameSpace.Folders("myNotes")
Dim myInteger As Integer
Dim myItems As Outlook.Items
Set myItems = myFolder.Items
For Each myitem In myItems
On Error GoTo myErrorHandler
myInteger = cint("abc")
myErrorHandler:
If Err.Number <> 0 Then
msgbox "Error handled"
End If
Next myitem
----------------------------------
 
Hi,

2 things. The On Error belongs outide the loop. Clear the error if there is one.
Code:
    Set ol = CreateObject("Outlook.Application")
    Set myNameSpace = ol.Application.GetNamespace("MAPI")
    Set myFolder = myNameSpace.Folders("myNotes")
    Dim myInteger As Integer
    Dim myItems As Outlook.Items
    
    Set myItems = myFolder.Items
    [b]
    On Error GoTo myErrorHandler
    [/b]
    For Each myitem In myItems
       myInteger = CInt("abc")
myErrorHandler:
       If Err.Number <> 0 Then
          MsgBox "Error handled"[b]
          Err.Clear[/b]
       End If
    Next myitem

    On Error GoTo 0    'turn off error handling

'set objects to nothing
    Set myItems = Nothing
    Set myFolder = Nothing
    Set myNameSpace = Nothing
    Set ol = Nothing

Skip,
[glasses]Don't let the Diatribe...
talk you to death![tongue]

[glasses]Just traded in my old subtlety...
for a NUANCE![tongue]
 
You need to clear the error:
If Err.Number <> 0 Then
Err.Clear
msgbox "Error handled"
End If

combo
 
Furthermore, I'd use the Resume instruction ...

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 



On second thought, I'd use On Error Resume Next, rather than GoTo, which is basically how you are coding the loop. myErrorHandler: not necessary that way.

Skip,
[glasses]Don't let the Diatribe...
talk you to death![tongue]

[glasses]Just traded in my old subtlety...
for a NUANCE![tongue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top