Ok think I might have sorted this out.

I've added "On Error Resume Next" on the first line of the function, it seems to run ok now.