Thanks for all the help everyone, I subbed in Peter's function and it with some massaging it is all working.
GHarvey I will have a look at your code and see if it runs any faster.
I am processing a huge amount of data so any minor efficiency can potentially save huge amounts of time.