Code:
I wasn't able to convert my subroutine into a UDF



Why

You should have been able to drop the code I provided into your script without modification. (Well, maybe a little bug fixing, I couldn't test it here)

Add the "Function ... EndFunction" code to the end of your script.

Replace your Gosub with the function call and you're done.