问题
I'm trying to copy certain range from other sheet (or the same one) but only copy it if the range is not empty or have an error message like (#N/A, #REF, etc.).
For example:
- Sheet 1: Contains the original data sheet.
- Sheet 2: Contains the copied data from the script, but the data here only overwritten if the original ones are not empty or errored.
function test() {
SpreadsheetApp.getActive().getSheetByName('sheet2').getRange('A2').setValue('=QUERY(sheet1!A2:E355, "SELECT A, B, C, D, E LIMIT 200",1)')
}
Note: I used QUERY here to copy, but I'm sure it's not the best for copying, as it doesn't retain the value in the other sheet, but just to demonestrate.
回答1:
If I understood you correctly, you want to copy your range to another sheet if the following conditions are met:
- The source range does not contain any cell with an error.
- All empty rows in the source range (if any) are located at the end of the range (there is no row with values after an empty row).
If that's correct, you could do the following (check inline comments):
function copyRange() {
var ss = SpreadsheetApp.getActive();
var sourceSheet = ss.getSheetByName("source_sheet"); // Source sheet name
var targetSheet = ss.getSheetByName("target_sheet"); // Target sheet name
var A1notation = "C6:E23"; // A1 notation of the source range (please change if necessary)
var sourceRange = sourceSheet.getRange(A1notation);
var sourceValues = sourceRange.getValues();
var errors = ["#REF!", "#N/A", "#DIV/0!", ...]; // Array of errors (incomplete)
for (var i = 0; i < sourceValues.length; i++) { // Iterate through all values in source range
for (var j = 0; j < sourceValues[i].length; j++) {
if (errors.includes(sourceValues[i][j])) return; // End execution if error found in a cell
}
}
// Check if there is an inbetween empty row:
var emptyRowInBetween = sourceValues.map(rowValues => {
return rowValues.every(cellValue => {
return cellValue === "";
});
}).join().indexOf("true,false") !== -1;
var targetRange = targetSheet.getRange("A1"); // Range to copy to (please change if necessary)
if (!emptyRowInBetween) sourceRange.copyTo(targetRange); // Copy range to specified destination
}
Update:
If you only want to copy the values, and not the formulas, etc., you can do this:
sourceRange.copyTo(targetRange, SpreadsheetApp.CopyPasteType.PASTE_VALUES);
Note:
- You have to enable V8 for this to work.
Reference:
- Range.copyTo(destination)
来源:https://stackoverflow.com/questions/60783578/googlesheet-script-to-copy-range-only-if-it-is-not-empty-or-error