A more compact way of doing the same thing, although I don’t think it will make any difference to the problem
You needed the IsValid, because using LENGTH will give you a nonexistent index. You can always use LASTINDEX.