'How to edit an existing formula using google app script?

I have a macro that I'm creating that needs to

  1. create a new sheet then

  2. add that sheet to several formulas that are fairly complex and long such as …

    COUNTIF({'sheet1'!A:A;'sheet2'!A:A;'sheet3'!A:A;...},B2)
    
    SORT(UNIQUE({'sheet1'!A2:B;'sheet2'!A2:B;'sheet3'!A2:B;...}))
    
    TEXTJOIN(", ",TRUE,IF(NOT(ISNA(VLOOKUP(B192,'sheet1'!A:A,1,FALSE))),!NamedRange1,""),...
    

I've got the creation of the sheet working, but the code below for the adding to the formulas hasn't worked.

  var spreadsheet = SpreadsheetApp.getActive();
  //fullnamestring is a string value with the name of the sheet we are creating.

  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Formula Sheet'), true);
  spreadsheet.getRange('A2').activate();

  var needToOrderFomula = SpreadsheetApp.getActiveSheet().getRange('A2').getFormula();

  needToOrderFomula.replace('!A:A},B2)', '!A:A\''+fullNameString+'\'!A:A},B2)');
  spreadsheet.getRange('A2').setFormula(needToOrderFomula);

  var needToOrderRange = spreadsheet.getRange('!A3:A1000');
  spreadsheet.getRange('A2').copyTo(needToOrderRange, SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);```


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source