问题
I have written a script that intends to clear the content of a Google Sheets spreadsheet and copy and paste the content of another sheet.
The sheet that needs to be cleared is called "NEW_SHEET" and the one to be copied over is called "Database".
For some reason, the script is not working at the moment. Nothing happens when I run it.
Also, at the moment, I am using .getActiveRange to select the range to clear. However, I would like that to be columns A to AC and only to the last row with data in it.
This is the code I am using:
function importDB() {
//Delete content of New Sheet
var sh1 = SpreadsheetApp.openById('SHEET_ID').getSheetByName('NEW_SHEET')
var range1 = sh1.getActiveRange()
range1.clearContent()
//Copy new database data
var sh = SpreadsheetApp.openById('SHEET_ID').getSheetByName('Database')
var range = sh.getDataRange();
var data = range.getValues();
var ts = SpreadsheetApp.openById('SHEET_ID').getSheetByName('NEW_SHEET')
ts.setValues(data)
}
回答1:
You shouldn't be using getActiveRange() here. The code below should work.
function importDB() {
//Delete contents of "A:AC" in New Sheet
var sh1 = SpreadsheetApp.openById('SHEET_ID').getSheetByName('NEW_SHEET').getRange("A:AC");
sh1.clearContent();
//Copy new database data
var sh = SpreadsheetApp.openById('SHEET_ID').getSheetByName('Database');
var range = sh.getDataRange();
range.copyTo(sh1.getCell(1,1));
}
With the copyTo() function, you only the first cell in the destination matters. So you need to be careful that the data being copied from "Database" doesn't extend past column AC, otherwise you'll be overwriting that data in "NEW_SHEET". To prevent that, you could try var range = sh.getRange("A:AC") rather than copying over the entire data range.
来源:https://stackoverflow.com/questions/49628746/clear-content-and-copy-from-another-sheet