I have a FormatCondition
. I am reading the .Formula1
and the .AppliesTo
I want to find if the Formula contains a cell reference that will change across the range specified by the AppliesTo, eg =NOT(ISNUMBER(C3))
in a range C3:D10
.
From what I can tell, that reference might be relative (eg C3
) or mixed (eg $C3
or C$3
) but not absolute. It will also be the 'top-left most cell in the applied range' based on https://www.ablebits.com/office-addins-blog/2014/08/07/relative-absolute-cell-references-excel-conditional-formatting/ and some other sites.
If the range is something like C3:D10
then that's easy. Find the top left using eg myRange.Cells(1, 1)
, convert it to a string using .Address
or similar and then look for that string in the Formula, along with relevant variations adding a $
. Sure, I'd have to be careful about things like strings (eg top left cell is C3' and formula is
="CC3NE"`), but it's possible (still, I'd welcome suggestions on how to do that better, but that's not the question).
The real problem is if the range is more complex, as seems to happen often with Conditional Formatting. An example is $CQ$39:$FT$39,$BE$39,$BE$8:$BE$9,$CU$8:$FT$9,$CU$12:$FT$14,$BE$12:$BE$14,$BE$16:$BE$30,$CQ$16:$FT$30,$CQ$32:$FT$36,$BE$32:$BE$36
. .Cells(1, 1)
doesn't give the right answer for that (BE8
, according to the formula that Excel made).
Further, what if the range were something like $A$5,$E$1
- there is no 'top left'. So how does excel (or the user) decide which should be in the formula?
Thus the primary question is: What is the system for Excel determining which cell to use in a formula, because I don't believe it is 'top left' - it might be 'find the topmost row, then find the leftmost cell there', or it might be the reverse, or something completely different.
The second question is: how best can I find that cell from a given range?
The bonus question (I'm happy if this doesn't get answered here) is: Is there a good way to then find references to that cell in a formula, including relative and mixed versions of the cell?
Note that these strange ranges are coming about from Rows and Columns being Cut and Pasted on a sheet with Conditional Formatting, with Excel chopping up the conditional formatting as a result (changing the range, and changing the formula, both without user input). So the priority is to deal with whatever Excel would set the formula to be on its own in such a scenario, not necessarily what a user might do - but handling both would be even better.