I don't know that Excel functions could do this. I would use VBA or maybe PowerQuery.

Could you post the Excel file? Follow instructions at bottom of my post.