Solved
You are using "on error" the wrong way.
It has to be the first statement (otherwise the error occurs and your routine fails) and calculation which may fail is on the RHS, not the LHS.
The following should do the job, but on first sight it looks to me that the value of M does not influence the result.

Welcome to the PTC Community
No account yet? Create an account
Please use your PTC eSupport account.
LoginEnter your E-mail address. We'll send you an e-mail with instructions to reset your password.

