Error handling in a loop

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,926
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
Which of the two methods below are preferable?

Method1 with error handling:

Code:
Sub Start()

On Error GoTo Errhandler

For Counter = 1 To 1000
            
            i = 1
            
            Do Until TableArray(i, 1) = MyArray(j, 1)
                
                i = i + 1
                
            Loop
                                    
NextCounter:
            
            j = j + 1
            
        Next Counter

Exit Sub

Errhandler:

Resume NextCounter

End sub

or Method2, skipping over errrors?

Code:
Sub Start2()

On Error Resume Next

For Counter = 1 To 1000
            
            i = 1
            
            Do Until TableArray(i, 1) = MyArray(j, 1)
                
                i = i + 1
                
            Loop
            
            j = j + 1
            
        Next Counter

End Sub

Thanks
 

Excel Facts

Square and cube roots
The =SQRT(25) is a square root. For a cube root, use =125^(1/3). For a fourth root, use =625^(1/4).
I would say in their current form they are of equal value. As they will achieve the same end result (skip to the next iteration). Method 1 is preferable in the following 2 instances:
1. To catch an unforseen error, occuring
2. When you wish to take further action following an error, eg. display a message box or Exit/Stop the code execution.

If you are confident of which errors you expect to occur, and you are happy to ignore them Method 2 would suffice but is generally less preferred with more complex modules/code

Hope that helps
Caleeco
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,171
Members
453,021
Latest member
Justyna P

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top