這可能是一個愚蠢的問題,但我無法在 stackoverflow、youtube 或開發人員 (google) 網站上找到有關此問題的答案。
我正在嘗試使用 createTextFinder 查找某個單詞,并將其替換為一個新單詞。理想情況下,我想替換單詞的第二個實體而不是第一個,但是如果不可能,那也沒關系。我還試圖確保我的函式可以動態地找到這些詞,而不是停留在定義的范圍內,例如 A1:D2。
因此,對于我們下面的示例,嘗試將 Apple 的第二個實體更改為 Pie。
我覺得非常奇怪的是,replaceWith 似乎不起作用,但是 replaceAllWith 確實起作用了。
問題:
- 無法讓 replaceWith 與 createTextFinder 方法一起使用。收到錯誤
“例外:服務錯誤:電子表格”
當前作業表:

預期結果:

我試過的故障排除:
- 嘗試使用 startFrom 并在 Apple 的第二個實體之前使用一個范圍,但這似乎不起作用
- 嘗試在同一功能中制作另一個文本查找器,但我認為您不允許這樣做?我這樣做是為了做我之前的嘗試
- 將 replaceWith 更改為 replaceAllWith 有效,但隨后嘗試讓它在同一函式中找到“Pie”并將第一個實體更改回“Apple”,但這不起作用
- 也嘗試使用 findNext() 功能,但不幸的是這不起作用,我不確定如何將它與 replaceWith 方法一起使用。
在這些嘗試中發生的常見錯誤是程式指出我沒有正確的功能或引數與方法簽名不匹配
代碼:
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
資源:
谷歌開發者關于 replaceWith
uj5u.com熱心網友回復:
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)
}
});
}
了解更多
uj5u.com熱心網友回復:
基于 Cooper 的解決方案:
function replace_second(word = "Apple", replacement = "Peach") {
try {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1')
.createTextFinder(word).matchEntireCell(true).findAll()[1]
.setValue(replacement);
} catch(e) {}
}
uj5u.com熱心網友回復:
您需要.findNext()至少呼叫一次以替換第一個匹配的單元格。
function findText() {
const workSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
'Sheet1'
);
const tf = workSheet.createTextFinder('Apple');
tf.matchEntireCell(true).matchCase(true); //finds text "Apple" exactly
let match = -1;
while ( match < 2) tf.findNext();//for second match
tf.replaceWith('Pie');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344413.html
標籤:谷歌应用程序脚本
