Error handling in a loop

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,924
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

Copy formula down without changing references
If you have =SUM(F2:F49) in F50; type Alt+' in F51 to copy =SUM(F2:F49) to F51, leaving the formula in edit mode. Change SUM to COUNT.
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,223,897
Messages
6,175,270
Members
452,628
Latest member
dd2

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