Monday, November 14, 2022

[FIXED] How to use error handling multiple time in for loop?

Issue

For Each cell In Workbooks("workbook.xlsm").Sheets("sheet1").Range("P5:P12").Cells
sheetname = cell.Value
Windows("new workbook.xlsx").Activate
Worksheets(division).Select
On Error GoTo SKIPCODE

{code}

SKIPCODE:
Next

While running this code if the sheet with name in range of P5-P12 does not exist it gives an error. FOr first such occurrence error is handled and loop continues but for second occurrence code breaks. Can someone help on this??


Solution

You have to reset the error handler object after having "handled" the error, in your case by just skipping the iteration. Usually this is done automatically by the resume keyword, however, since you are not using resume because you are essentially just ignoring the error, you have to do it manually by using On Error GoTo -1

Try adding that to your code like this:

For Each cell In Workbooks("workbook.xlsm").Sheets("sheet1").Range("P5:P12").Cells
    sheetname = cell.Value
    Windows("new workbook.xlsx").Activate
    Worksheets(division).Select
    On Error GoTo SKIPCODE

    '{code}

SKIPCODE:
    On Error GoTo -1
Next


Answered By - GWD
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.