根据列值将一个 Google Sheet 拆分为多个 Sheet - 替换重复的 Sheet

Split One Google Sheet into Multiple Sheets based on Column Value - Replace Duplicate Sheets

这超出了我的知识水平,我希望得到帮助。下面的脚本有一些限制。此脚本检查区域选项卡是否存在,如果不存在,源工作表中的区域数据将复制到该区域名称的新选项卡。区域是源工作表的第 24 列,数据从第 3 行开始,header 是第 2 行。

如果区域选项卡已经存在,我希望它被删除重新创建或用当前数据重新填充而不是被跳过。

function createSheets(){

const ss = SpreadsheetApp.getActiveSpreadsheet()
const sourceWS = ss.getSheetByName("Forecast (SQL) Validation")

const regions = sourceWS
  .getRange(3,24,sourceWS.getLastRow()-2,1)
  .getValues()
  .map(rng => rng[0])

const uniqueRegion = [ ...new Set(regions) ]

const currentSheetNames = ss.getSheets().map(s => s.getName())

let ws

uniqueRegion.forEach(region => {

  if(!currentSheetNames.includes(region)){

    ws = null
    ws = ss.insertSheet()
    ws.setName(region)
    ws.getRange("A2").setFormula(`=FILTER('Forecast (SQL) Validation'!A3:CR,'Forecast (SQL) Validation'!X3:X="${region}")`)
    sourceWS.getRange("A2:CR2").copyTo(ws.getRange("A1:CR1"))

}//If regions doesn't exist

})//forEach loop through the list of region

} //close createsheets functions

这样试试

function createSheets() {
  const ss = SpreadsheetApp.getActive()
  const ssh = ss.getSheetByName("Forecast (SQL) Validation");
  const regions = ssh.getRange(3, 24, ssh.getLastRow() - 2, 1).getValues().flat();
  const urA = [...new Set(regions)];
  const shnames = ss.getSheets().map(s => s.getName())
  let ws;
  urA.forEach(region => {
    let idx = shnames.indexOf(region);
    if (~idx) {
      ss.deleteSheet(ss.getSheetByName(shnames(idx)));//if it does exist delete it and create a new one
    }//if it does not exist the just create a new one
    ws = null;
    ws = ss.insertSheet(region);
    ws.getRange("A2").setFormula(`=FILTER('Forecast (SQL) Validation'!A3:CR,'Forecast (SQL) Validation'!X3:X="${region}")`)
    ssh.getRange("A2:CR2").copyTo(ws.getRange("A1:CR1"))
  })
}

解释:

遍历所有选项卡,如果该选项卡已经存在,请通过 deleteSheet 删除它,然后再次创建它,就像您对 non-existent 选项卡所做的那样..