Your IF functions are referencing 2 different cells:

IF(P2>=Sheet2!M$3:M$589

IF(P22<=Sheet2!Q$3:Q$589

Is that correct?

Not quite sure what this means:

What I want to do is paste the function into cells P3, P4, P5 and at the same time P2 change to the relevant row number
Are you entering the formula in cell P2? If so, that'll cause a circular reference.