I'm having a small problem with this formula, with unic digits it works fine but now, I have duplicate digits, it's not calculating the right way can it be fix ?

This formula calculate the skips of a digit and when reappear, it start at 1.

The red cells are highlighted in green normally, but I put them in red for you to see better.

Cell P9 should be a 2 not 1

Cell P10 should be a 3 not 1

Cell P12 should be a 2 not 1

Cell P17 is highlighted and shouldn't maybe need to correct my CF ?

Cell P18 should be a 6 not 1

Cell P19 should be a 7 not 2

The rest look Ok it seems to just happen in the first column !

Can it be fix ?

Thank you.