Home > Mobile >  Google Sheets Apps Script: Copy selected Cells into new Worksheet
Google Sheets Apps Script: Copy selected Cells into new Worksheet

Time:06-13

I'm new to Apps Script and don't know how I can get my selected cells copied into another worksheet.

I want the following but instead of copying A7:A9 into a new worksheet i want the cells/range that are selected at the time to be copied. the selected cells/range are going to be different each time that i want to use the script.

var rangeList = SpreadsheetApp.getActiveRangeList();

function TestMakro() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A7:A9').activate();
  spreadsheet.insertSheet(1);
  spreadsheet.getRange('Tabellenblatt1!A7:A9').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

thanks

CodePudding user response:

So instead of using SpreadsheetApp.getActive() it's better to define separately the spreadsheet and the active range. you can then get A1 annotation of the active range to find the same area in the new sheet (I assumed that is what you are trying to achieve). Key here is that even if you create a new sheet, it doesn't become Active. Hence you still need to find the same range in it.

Here is the code:

function TestMakro() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const activeRange = spreadsheet.getActiveRange();
  const newSheet = spreadsheet.insertSheet(1)
  activeRange.copyTo(newSheet.getRange(activeRange.getA1Notation()) , SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false)
}
  • Related