Am trying to modify this script to copy entire rows with the word 'name' in a column to a new sheet.
Got 'Exception: The number of rows in the range must be at least 1' so currently not working at all! Can anyone help?
Thanks
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Admin')
.addItem('Copy name rows', 'copyNameRows')
.addToUi();
}
function copyNameRows() {
const sourceSheet = SpreadsheetApp.getActive().getSheetByName('Source');
const targetSheet = SpreadsheetApp.getActive().getSheetByName('Target');
const dataValues = sourceSheet.getDataRange().getValues();
targetSheet.getRange(2,1,targetSheet.getLastRow() - 1, 28).clear();
var currentTargetRow = 2;
for (var i = 0 ; i < dataValues.length; i++) {
if (dataValues[0][24].toString().toLowerCase() == 'name' ||
dataValues[0][25].toString().toLowerCase() == 'name' ||
dataValues[0][26].toString().toLowerCase() == 'name' ||
dataValues[0][27].toString().toLowerCase() == 'name') {
sourceSheet.getRange(i + 1, 1, 1, 28).copyTo(targetSheet.getRange(currentTargetRow, 1));
currentTargetRow++;
}
}
}
Fiddled with the range values but no joy...As I understand it should check columns 24, 25 and 26 for the word 'name' and if it's there, copy the contents of that row to a new sheet??
Try it this way:
function copyNameRows() {
const ss = SpreadsheetApp.getActive();
const ssh = ss.getSheetByName('Sheet0');
const tsh = ss.getSheetByName('Sheet1');
const svs = ssh.getDataRange().getDisplayValues();
tsh.clearContents();//clear sheet
const n = 'name';
let o = svs.filter((r,i) => r.slice(24,28).some(e => e.toLowerCase() == n))
o.unshift(svs[0]);//put header on top
tsh.getRange(tsh.getLastRow() + 1,1,o.length,o[0].length).setValues(o);
}
Update for you comment
function copyNameRows() {
const ss = SpreadsheetApp.getActive();
const ssh = ss.getSheetByName('Sheet0');
const tsh = ss.getSheetByName('Sheet1');
const svs = ssh.getDataRange().getDisplayValues();
tsh.clearContents();//clear sheet
const n = 'name';
let o = svs.filter((r,i) => r.slice(24,28).some(e => e.includes(n)))
o.unshift(svs[0]);//put header on top
tsh.getRange(tsh.getLastRow() + 1,1,o.length,o[0].length).setValues(o);
}