G
G
Graun2020-02-01 17:35:20
Google Apps Script
Graun, 2020-02-01 17:35:20

How to cut data from the Table from the second row and paste it into another sheet?

How to cut data from a Table from the second row and paste it into another Table?

The code below works well, but it adds data to the existing ones. What should be done to overwrite existing data starting from the second line?

/**
 *
 */
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Custom menussss')
    .addItem('Copy to logs', 'CopyTabList')
    .addToUi();
}

/**
 *
 */
function CopyTabList() {
  var sss = SpreadsheetApp.openById('Id');
  var ss = sss.getSheetByName('Sheet1');

  var from = SpreadsheetApp.getActiveSheet();
  var fromValues = from.getDataRange().getValues();
  var fromData = fromValues

  var tss = SpreadsheetApp.openById('Id');
  var ts = tss.getSheetByName('Sheet3');

  SpreadsheetApp.getActive().getSheetByName('Sheet3') ||
    SpreadsheetApp.getActive().insertSheet('Sheet3');

  ts.getRange(ts.getLastRow() + 1, 1, fromData.length, fromData[0].length)
    .setValues(fromData);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2020-02-01
@Graun

Well, there are quite a few ways. Which one to choose is not an easy task. Start with a slice

function copyTabList() {
  var from = SpreadsheetApp.getActiveSheet();
  var fromValues = from.getDataRange().getValues();
  var fromData = fromValues.slice(1);

  var tss = SpreadsheetApp.openById('Id');
  var ts = tss.getSheetByName('Sheet3');

  ts.getDataRange()
    .offset(1, 0)
    .clearContent()
    .getRange(2, 1, fromData.length, fromData[0].length)
    .setValues(fromData);
}

And there is also an option with offset (I began to lean towards it because of the speed of work)
function copyTabList() {
  var from = SpreadsheetApp.getActiveSheet();
  var fromValues = from
    .getDataRange()
    .offset(1, 0)
    .getValues();
  var fromData = fromValues;

  var tss = SpreadsheetApp.openById('Id');
  var ts = tss.getSheetByName('Sheet3');

  ts.getDataRange()
    .offset(1, 0)
    .clearContent()
    .getSheet()
    .getRange(2, 1, fromData.length, fromData[0].length)
    .setValues(fromData);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question