Search code examples
google-sheetsgoogle-apps-scriptgoogle-sheets-formula

Use formula inside script


I would like to use a formula inside a custom function, like this for example:

function myFunction(range, value) {
    var countNumber = COUNTIF(range; value); // COUNTIF is a formula that can be used in the spreadsheet
    if (countNumber > 0) {
        return "RESULT";
    } else {
        return "OTHER RESULT";
    }
}

And then:

=MYFUNCTION(A1:A5,"VALUETOTEST")


I would like to simplify a huge formula:

Something like:

=IF(SUM(COUNTIFS(G182:G186;"ERROR";H182:H186;"62");COUNTIFS(G182:G186;"ERROR";H182:H186;"ALL"))>0;"ERRO";IF(SUM(COUNTIFS(G182:G186;"RETEST";H182:H186;"62");COUNTIFS(G182:G186;"RETEST";H182:H186;"TODOS"))>0;"RETEST";IF(COUNTIF(G182:G186;"UNIMPLEMENTED")>0;"UNIMPLEMENTED";"SOLVED")))

Solution

  • This is how I solved my problem. I thank to people who helped me to reach this result!

    // Like COUNTIFS
    var countConditionals = function(cells, condition1, condition2) {
    
      var count = 0;
    
      for (i = 0; i < cells.length; i++) {
    
        if (cells[i][0] == condition1 && cells[i][1] == condition2) {
          count++;
        }
    
      }
    
      return count;
    }
    
    // Like COUNTIF
    var countConditional = function(cells, condition) {
    
        var count = 0;
    
        for (i = 0; i < cells.length; i++) {
    
            if (cells[i][0] == condition) {
              count++;
            }
    
        }
    
      return count;
    }
    
    //Whole Formula
    function verificaStatus(cells, db) {
    
      const ERROR  = "ERROR";
      const ALL    = "ALL";
      const RETEST = "RETEST";
      const NOTYET = "UNIMPLEMENTADED";
      const SOLVED = "SOLVED";
    
      var countErrors    = countConditionals(cells, ERROR, db);
      var countErrorsAll = countConditionals(cells, ERROR, ALL);
      var sumErrors      = countErrors + countErrorsAll;
    
      if (sumErrors > 0) {
        return ERROR;
      } else {
    
        var retest    = countConditionals(cells, RETEST, db);
        var retestAll = countConditionals(cells, RETEST, db);
        var sumRetest = retest + retestAll;
    
        if (sumRetest > 0) {
          return RETEST;
        } else {
    
          var countNonCreated = countConditional(cells, NOTYET);
    
          if (countNonCreated > 0) {
            return NOTYET;
          }
    
        }
    
      } 
    
      return SOLVED;
    
    }