I found this piece of code and need to modify it so that if it doesn’t find a result it will return and keep running next lines of code
JavaScript
x
22
22
1
function DeleteTEXT_BULK() {
2
// will delete in bulk whatever the text finder finds. tested and working
3
// YOU MUST ENABLE THE SHEETS API - RESOURCES / ADVANCED GOOGLE SERVICES / GOOGLE SHEETS API
4
// cannot delete blank rows
5
6
const sheetName = "Sheet 1"; // Please set the sheet name.
7
const ss = SpreadsheetApp.getActiveSpreadsheet();
8
const sheet = ss.getSheetByName(sheetName);
9
const sheetId = sheet.getSheetId();
10
const requests = sheet
11
.getRange(`A1:E${sheet.getLastRow()}`)
12
.createTextFinder("^JOHN")
13
.matchCase(true)
14
.useRegularExpression(true)
15
.findAll()
16
.map(r => r.getRow())
17
.reverse()
18
.map(r => ({delete Dimension:{range:{sheetId:sheetId,startIndex:r -
19
1,endIndex:r,dimension:"ROWS"}}}));
20
Sheets.Spreadsheets.batchUpdate({requests: requests}, ss.getId());
21
}
22
So if it doesn’t find “JOHN” it currently stops running and throws an error.
I would like it to move onto next piece of code if no result found.
appreciate any help, this is my first post
Advertisement
Answer
I believe your goal is as follows.
- You want to continue to run the script even when the value of
JOHN
is not found.
In this case, how about the following modification?
Modified script:
JavaScript
1
22
22
1
function DeleteTEXT_BULK() {
2
const sheetName = "Sheet 1"; // Please set the sheet name.
3
const ss = SpreadsheetApp.getActiveSpreadsheet();
4
const sheet = ss.getSheetByName(sheetName);
5
const sheetId = sheet.getSheetId();
6
const ranges = sheet
7
.getRange(`A1:E${sheet.getLastRow()}`)
8
.createTextFinder("^JOHN")
9
.matchCase(true)
10
.useRegularExpression(true)
11
.findAll();
12
if (ranges.length > 0) {
13
const requests = ranges.map(r => r.getRow())
14
.reverse()
15
.map(r => ({ deleteDimension: { range: { sheetId: sheetId, startIndex: r - 1, endIndex: r, dimension: "ROWS" } } }));
16
Sheets.Spreadsheets.batchUpdate({ requests: requests }, ss.getId());
17
}
18
19
// do something.
20
21
}
22
- In this modification, when the value of
JOHN
is not found, byif (ranges.length > 0) {}
, the script ofSheets.Spreadsheets.batchUpdate
is skipped. By this, you can continue to run the script.