有沒有辦法通過使用 Google App Script 中的函式來禁用作業表每個單元格中的所有代碼?
例如在 A1 我有:
=query(d10Thur0721!B2:I1275, "select B, C, D, E where D > 0", 0)
在 H2 中,我有:
=if($G$9="", "", "men:"&roundup(sum(countif($G$9:$G$551, "*m*")-countif(G9:G600, "*mef*"))/countif($G$9:$G$551, "**")*100))&"%"
從理論上講,我只想替換=,'=從而禁用所有代碼,但是我不確定如何讓腳本獲取單元格中的實際代碼。如果我參考單元格 A1,Google Apps 腳本將回傳單元格中的任何值,而不是 A1 中的實際代碼。
uj5u.com熱心網友回復:
獲取單元格公式使用SpreadsheetApp.Range.getFormula(),獲取范圍內所有單元格的公式使用SpreadsheetApp.Range.getFormulas()。
要設定單元格公式,請使用SpreadsheetApp.Range.setFormula(formula)where formula is a string,要獲取范圍內所有單元格的公式,請使用SpreadsheetApp.Range.setFormulas(formulas)where formulasis string[][](二維陣列,外部陣列元素是字串陣列)。
要設定單元格值,請使用SpreadsheetApp.Range.setValue(value)where valueis a string,要設定values范圍內的所有單元格,請使用SpreadsheetApp.Range.setValues(values)where valuesis string[][](二維陣列,外部陣列元素是字串陣列)。
下面是一個“創意”腳本。它禁用活動范圍內的公式,保持沒有公式的單元格的值。
而不是使用getFormulaand getFormulas/ setFormulaand setFormulas,它只使用getValuesandgetFormulas而不是setFormula/setFormulas它使用setValues(values)
/**
* Disable formulas in the active range.
* https://stackoverflow.com/a/74329523/1595451
*
* @author Rubén https://stackoverflow.com/users/1595451/rubén
*/
function disableFormulas(){
const range = SpreadsheetApp.getActiveRange();
const formulas = range.getFormulas();
const values = range.getValues();
range.setValues(formulas
.map((rowFormulas, row) => rowFormulas
.map((formula, column) => formula
? formula.replace(/^=/,`'=`)
: values[row][column];
)
)
)
}
參考
- https://developers.google.com/apps-script/reference/spreadsheet/range
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/529351.html
