[英]How to fix or adapt this Find and Replace in Google Apps Script
我有一張表,我經常需要將大量數據粘貼到其中,並且需要進行十次“查找和替換”迭代來修復一些數據。 我粘貼的數據來自一個數據庫,我將無法直接訪問該數據庫,並且由於某種原因,每當他們將其導出時,許多常見的特殊字符(例如é
或'
都會被打亂)。
我竊取並改編了這個出色的解決方案來制作一個腳本,該腳本將子字符串替換為數據中任何位置的其他字符串。 該腳本在活動工作表中搜索被弄亂的特定字符串並用正確的字符替換它們。
該腳本運行良好,只是由於某些未知原因偶爾將單個字符替換-
'
。 如果它是一致的,我可以使用它,但由於某種原因,它只是間歇性地發生。 我懷疑這與角色有關|
基本上在下面的第 8 行或第 9 行中起到 OR 的作用,但我無法弄清楚為什么它只會不時地這樣做。
一個完美的解決方案是阻止這種間歇性更換的發生。 下一個最好的事情是調整腳本以在完成當前正在執行的操作之后將出現的'
替換為-
在單個列 G 中。 我認為對於我的技能水平(零)來說更容易實現的是制作腳本的副本,該副本只會在 G 列中將'
替換為-
我的理解是第 5 行中的getValues()
基本上選擇了整個工作表,我嘗試將其替換為各種其他get
事物以獲取 G5:G,但我無法讓它正常工作。 我絕對沒有編碼經驗,除非你算上對 Sheets 內置函數的一些巧妙使用。 不幸的是,我不明白調試時收到的錯誤消息。
當前腳本:
function runReplaceInSheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
// get the current data range values as an array
// Fewer calls to access the sheet -> lower overhead
var values = sheet.getDataRange().getValues();
// Replace Subject Names
replaceInSheet(values, /\'|-/g, "'");
replaceInSheet(values, /\’|-/g, "'");
replaceInSheet(values, /\√°|-/g, "á");
replaceInSheet(values, /\√©|-/g, "é");
replaceInSheet(values, /\√≠|-/g, "í");
replaceInSheet(values, /\√≥|-/g, "ó");
replaceInSheet(values, /\√Å|-/g, "Á");
replaceInSheet(values, /\√Ø|-/g, "ï");
replaceInSheet(values, /\ƒó|-/g, "ė");
replaceInSheet(values, /\≈´|-/g, "ū");
// Write all updated values to the sheet, at once
sheet.getDataRange().setValues(values);
}
function replaceInSheet(values, to_replace, replace_with) {
//loop over the rows in the array
for(var row in values){
//use Array.map to execute a replace call on each of the cells in the row.
var replaced_values = values[row].map(function(original_value) {
return original_value.toString().replace(to_replace,replace_with);
});
//replace the original row values with the replaced values
values[row] = replaced_values;
}
}
我做了各種嘗試來修改它,只用命名范圍PO_EligibilityGG
或 G 列替換getValues
,但為簡潔起見,我將只粘貼我認為最接近工作的版本:
function runReplaceInSheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet()
// get the current data range values as an array
// Fewer calls to access the sheet -> lower overhead
var values = sheet.getRange('PO_EligibilityGG');
// Replace Subject Names
replaceInSheet(values, /\'|-/g, "-");
// Write all updated values to the sheet, at once
sheet.getRange('PO_EligibilityGG').setValues(values);
}
...
錯誤信息:
例外:參數 (SpreadsheetApp.Range) 與 SpreadsheetApp.Range.setValues 的方法簽名不匹配。 runReplaceInSheet @ Code.gs:11
我現在每天必須在 3 張不同的紙張上運行此替換 2 或 3 次,消除此問題只會讓應用程序擺脫痛苦。
根據我在您的情況下看到的情況,您似乎沒有正確使用 getRange 獲得 G 列中的值。
在使用 getRange 獲取 G 列中的值時嘗試此代碼:
function valuesOfColumnG(){
var ss = SpreadsheetApp.getActiveSheet();
var len = ss.getLastRow();
for(var i = 1; i < len +1; i++){
var valuesOfG = ss.getRange("G"+i).getValue();
console.log('Values of G ' + valuesOfG);
}
}
https://developers.google.com/apps-script/reference/spreadsheet/sheet#getRange(String)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.