![](/img/trans.png)
[英]How do I copy data from one cell to another based on a cell value? (Google Spreadsheets)
[英]How do I copy the highest value of a cell?
基本上我想復制一個單元格,但取該單元格的最大數字。
前任
我有一個初始值為 10 的單元格 B1 在另一個單元格前 B2 上復制單元格 B1,該值將始終為 10 但如果單元格 B1 變為 5 我希望單元格 B2 保持為 10。但反過來,如果單元格 B1 變為 20,單元格 B2 也會變為 20等等......如果單元格B1仍然減少到8,例如,單元格B2現在總是保持20,以這種方式繼續。
基本上我希望 B2 取 B1 的值,但不等於 B1 曾經擁有的最大值。
function max() {
let mval = ParseInt(PropertiesService.getScriptProperties().getProperty('mval'));
const ss = SpreadsheetApp.openById(gobj.globals.ssid);//this is a global object that I keep things I use a lot. Just replace it with the id of whatever spreadsheet you using
const sh = ss.getSheetByName('Sheet0');//change as required
let val = sh.getRange('A1').getValue();//change as required
if (val > mval) {
PropertiesService.getScriptProperties().setProperty('mval',val);
return val;
} else {
return mval;
}
}
在您的情況下,以下由 Google Apps Script 創建的示例腳本如何? 在此示例腳本中,該腳本可用作自定義函數。
請將以下腳本復制粘貼到電子表格的腳本編輯器中並保存。
function SAMPLE(v, key = "sample") {
if (v != "" && isNaN(v)) throw new Error("Inputted value is not number.")
const p = PropertiesService.getScriptProperties();
if (v == "") {
p.deleteProperty(key);
}
const previousValue = p.getProperty(key);
if (previousValue) {
const pv = Number(previousValue);
v = pv < v ? v : pv;
}
p.setProperty(key, v);
return v
}
=SAMPLE(A1Notation)
的自定義函數放到一個單元格中。 至此,腳本運行完畢。當為您的問題中的流程運行上述腳本時,將獲得以下結果。
在這個腳本中,當單元格為空時,PropertiesService 被重置。
=SAMPLE(A1Notation, "keyName")
。 通過這種方式,特定的密鑰用於 PropertiesServices。 這樣,每個自定義函數都可以用於每個最大值。/**
* @param {GoogleAppsScript.Events.SheetsOnEdit} e
*/
function onEdit(e) {
const [sheetName, maxRangeName] = ['Sheet1', 'B1'];
let sheet;
if (
e.range.getA1Notation() !== maxRangeName ||
(sheet = e.range.getSheet()).getName() !== sheetName
)
return;
const b2Rng = sheet.getRange('B2'),
[b1, b2] = [e.value, b2Rng.getValue()];
if (b1 > b2) b2Rng.setValue(b1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.