This may be a dumb question but I was unable to find an answer on stackoverflow, youtube, or the developers (google) site either for this issue.
I'm trying to use createTextFinder to find a certain word, and replace it with a new word. Ideally I'd like to replace the 2nd instance of the word instead of the first, however if that isn't possible that's OK. I'm also trying to ensure that my function can find these words dynamically instead of resting on defined ranges such as A1:D2 as an example.
So for our example below trying to change the 2nd instance of Apple to Pie.
What I find really bizarre, is that replaceWith doesn't seem to work, but replaceAllWith did work.
Problem:
"Exception: Service error: Spreadsheets"
Current Sheet:

Expected Outcome:

Troubleshooting I've tried:
Common errors occuring during these attempts is the program stating I do not have a proper function or that the parameters don't match the method signature
Code:
function findText() {
const workSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');//I have a few tabs and would like to call to them directly
const tf = workSheet.createTextFinder('Apple');
tf.matchEntireCell(true).matchCase(false);//finds text "Apple" exactly
tf.replaceWith('Pie');
}//end of function findText
Resources:
Google Developers on replaceWith
function replacesecondinstanceofword( word = "Apple",replacement = "Peach") {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const tf = sh.createTextFinder(word).matchEntireCell(true).findAll();
tf.forEach((f,i) => {
if(i == 1) {
sh.getRange(f.getRow(),f.getColumn()).setValue(replacement)
}
});
}
Learn More
Based on Cooper's solution:
function replace_second(word = "Apple", replacement = "Peach") {
try {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1')
.createTextFinder(word).matchEntireCell(true).findAll()[1]
.setValue(replacement);
} catch(e) {}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With