简体   繁体   中英

Moving data from one range of cells to another with a script Google Sheets

I asked this question over at the webapps stack exchange, but I didn't get any responses.

Basically, in one sheet I have data in cells C14 through F15, so it's 4 columns and 2 rows of data, 8 cells in total. With a script, I'd like to be able to "copy and paste" the values from these cells into B13:E14 on a different sheet.

I understand how to move values from one cell to another with a script, but I'm having trouble doing it with ranges of values.

Does anyone have any ideas?

Copying a range works just like copying a cell, since you can think of a cell as a range with one column and one row. So you can do something like this:

function copyRange() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sourceRange = spreadsheet.getSheetByName('Sheet1').getRange('C14:F15');
  const destinationSheet = spreadsheet.getSheetByName('Sheet2');
  
  // Copy to B13:E14
  sourceRange.copyValuesToRange(destinationSheet, 2, 5, 13, 14);
}

Also, this operation is quite common, so you might want to take a look at other questions and answers: https://stackoverflow.com/search?q=google%20apps%20script%20copy%20to%20another%20sheet

You can use the copyTo() method.

function copy() {
  const ss = SpreadsheetApp.getActive();
  ss.getRange('Sheet1!C14:F15').copyTo(ss.getRange('Sheet2!B13:E14'), { contentsOnly: true });
}

Note that you can specify the sheet using getSheetByName() (or similar) or you can just write it in as part of your range definition using normal A1 notation.

There are other ways to do this. Here's how it could be done using getValues() and setValues() .

function copy() {
  const ss = SpreadsheetApp.getActive();
  const values = ss.getRange('Sheet1!C14:F15').getValues();
  ss.getRange('Sheet2!B13:E14').setValues(values);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM