A script to find a section of a formula in a group of cells and replace it with input from the user

女生的网名这么多〃 提交于 2021-02-11 16:31:09

问题


I've put together an attendance google sheet that pulls data from weekly attendance tabs to a master sheet with all the weeks together. So far the master sheet is set so that more weeks can be added by pressing a button by duplicating the first week of the master sheet and appending it to the last column of the sheet.

So what I need help with is in the cells of the new duplicated week find a portion of the formula, in the case would be the dates of the old week tab '9/21-9/25' (the full formula is ='9/14-9/18'!$E$5) and replace it with the new week inputted by the user with a prompt, example '9/28-10/2'.

This is the code I've come up with so far.

function newWeek() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var lastCol = sheet.getLastColumn();
  var rowCol = sheet.getLastRow();
  var maxCols = sheet.getMaxColumns();

  // Number of columns to duplicate//
  var numCols = 15
  //Selects the previous week//
  var range = sheet.getRange(1, lastCol - 14, rowCol, 15);
  //Inserts columns for next week//
  sheet.insertColumnsAfter(lastCol, numCols);
  //Copies previous weeks properties into new columns//
  range.copyTo(sheet.getRange(1, lastCol + 1, rowCol, 15));
}

And if you think of an easier solution for what I am trying to do please let me know. It needs to be just a press of the button and enter the new dates and everything is created and pulled from the new week tab.


回答1:


Class TextFinder can be used to search and replace within formulas using matchFormulaText() method:

Snippet:

range.createTextFinder('9/21-9/25')
  .matchFormulaText(true)
  .replaceAllWith('9/28-10/2')


来源:https://stackoverflow.com/questions/64038100/a-script-to-find-a-section-of-a-formula-in-a-group-of-cells-and-replace-it-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!