You can't do it with a formula, for the reasons you've already outlined. You will need code. You have posted in the non-Excel section, so you'll need to clarify the platform, and then experts will be able to advise whether VBA would work for you or not.