将活动单元格的值复制到其他/非活动表中-如何确定要使用的目标/目标表

时间:2018-08-04 21:05:46

标签: variables google-apps-script google-sheets cell google-sheets-macros

此脚本根据活动单元格旁边的单元格中的值将活动单元格的值复制到另一个工作表中。

如果我在脚本中编写了确切的单元格,则可以使用,但是每次运行脚本时,它将基于不同的单元格。

我还需要微调目的地。

这里是:

function copytoTabs() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName('Booking In');
    var data = sheet.getActiveCell();
    var value = ss.getSheetByName('Booking In').getActiveCell().getA1Notation();
    var operator = data.offset(0, 1).getValue();

    if (operator == "Michelle") {
        var ts = SpreadsheetApp.getActiveSpreadsheet();
        var tss = ts.getSheetByName('MICHELLE Schedule');
        ts.setActiveSheet(ts.getSheetByName('MICHELLE Schedule'));
        tss.getRange(1, 2).activate();
        tss.getRange(value).copyTo(tss.getActiveRange(),
        SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
    }
    else if (operator == "Georgia") {
        ss.setActiveSheet(ss.getSheetByName("GEORGIA Schedule"));
        ss.getCurrentCell().offset(0, 1, 4, 1).activate();
        ss.getRange('\'Booking In\'!P12').copyTo(ss.getActiveRange(),
        SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
    }
    else if (operator == "Julie") {
        ss.setActiveSheet(ss.getSheetByName("JULIE Schedule"));
        ss.getCurrentCell().offset(0, 1, 4, 1).activate();
        ss.getRange('\'Booking In\'!P12').copyTo(ss.getActiveRange(),
        SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
    }

    ss.setActiveSheet(ss.getSheetByName('Booking In'), true);
}

1 个答案:

答案 0 :(得分:1)

可以使用对象中的运算符名称与工作表标签名称相关联,而不必使用多个if / else块。然后按操作员名称查找工作表标签名称。

function copytoTabs() {
  var activeCell,objectOfMappedValues,operator,sheet,sourceSs,targetSheetTabName,trgtSh;

  sourceSs = SpreadsheetApp.getActiveSpreadsheet();

  objectOfMappedValues = {//This is an object literal - the word literal means that the values are
    //hard coded here in the function as opposed to being set with code
    "Michelle":"MICHELLE Schedule",
    "Georgia":"GEORGIA Schedule",
    "Julie":"JULIE Schedule"
  }

  activeCell = sourceSs.getActiveCell();
  Logger.log('activeCell: ' + activeCell)

  operator = activeCell.offset(0, 1).getValue();//Get the value of one cell

  targetSheetTabName = objectOfMappedValues[operator];//Get the sheet tab name for this operator
  Logger.log('targetSheetTabName: ' + targetSheetTabName)

  trgtSh = ts.getSheetByName(targetSheetTabName);//Get the sheet tab to be the target to set a value
  Logger.log('trgtSh.getName(): ' + trgtSh.getName())

  trgtSh.getRange(activeCell.getA1Notation()).copyTo(trgtSh.getActiveRange())

}

此代码可能不是您要的全部内容,但希望它将使您进入最终解决方案。