Search code examples
google-sheetsformula

Dynamically Updating Formula Based on a Cell Reference


In one of my projects I am using the following code: (The queries are left blank as what they look for is not the issue.)

=UNIQUE({QUERY(1);Query(2)})

What I want to be able todo, is have a user enter a number into a cell and based on number that it would add more queries the to formula. So if the user put in the number 5 it would be;

=UNIQUE({QUERY(1);QUERY(2);QUERY(3):QUERY(4);QUERY(5)})

I want to do this in a formula and only use AppScript as a last resort. Is this even possible to-do?


Solution

  • Prepopulate all the queries, and omit some IF the input number isn't high enough.

    =UNIQUE({
      IF(H1<1,"",QUERY(A1:E5,"select A where A is not null"));
      IF(H1<2,"",QUERY(A1:E5,"select B where B is not null"));
      IF(H1<3,"",QUERY(A1:E5,"select C where C is not null"));
      IF(H1<4,"",QUERY(A1:E5,"select D where D is not null"));
      IF(H1<5,"",QUERY(A1:E5,"select E where E is not null"))
    })
    

    screenshot showing a demo of the above formula operating on some fake data and only calculating 4 of the 5 queries, with the input number 4 in a nearby cell.