0

I have an OnError method inside the for loop. I am getting an error when the OnError is used for the second time.

This is my code,

For i = lastrow To 2 Step -1
  Sheets(TabName2).Activate
  CombinedKeyVal = Range(CombinedKeyColLet & i).Value

  On Error GoTo Jumpdelete

  Present = WorksheetFunction.Match(CombinedKeyVal, Sheets(TabName1).Columns(6), 0)
  If Present <> "" Then
    GoTo Jumpdontdelete
  End If

Jumpdelete:
  Sheets(TabName2).Activate
  Rows(i & ":" & i).Delete

Jumpdontdelete:

Next

How do I handle this for n number of times. Please kindly share your thoughts.

3
  • 2
    You are supposed to use resume to return from your error handler. E.g. resume Jumpdontdelete. Commented May 18, 2017 at 19:29
  • What's the error you're seeing? Commented May 18, 2017 at 19:33
  • saying match not found ! for the line present=application* Commented May 18, 2017 at 19:34

1 Answer 1

4

In this specific case, Dim Present As Variant and use Application.Match instead of WorksheetFunction.Match. The Application.Match function returns an error without raising it (this is why you need to assign as a Variant type):

Dim Present As Variant
For i = lastrow To 2 Step -1
    CombinedKeyVal = Sheets(TabName2).Range(CombinedKeyColLet & i).Value
    Present = Application.Match(CombinedKeyVal, Sheets(TabName1).Columns(6), 0)
    If IsError(Present) Then
        Sheets(TabName2).Rows(i & ":" & i).Delete
    End If
Next

This avoids the spaghettification of your code with tons of GoTo and Resume statements which are tricky to follow & troubleshoot.

Also I cleaned up your code a little bit to avoid relying on Activate.

Sign up to request clarification or add additional context in comments.

1 Comment

That is the answer. Don't use errors for flow control, and of course avoid GOTO jumps and spaghetti logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.