在 Google 表格中,我想創建一個宏,當手動填充該行中的另一列時,該宏將自動填充每一行中的一列。自動填充的單元格將使用一個公式,該公式采用手動輸入的大量資訊(日期),并使用一個公式將其與亂數連接起來,以創建一個唯一的 ID。插入并執行公式后,宏需要復制并粘貼“僅值”該公式的結果。關鍵是自動創建一個穩定的 ID 以回應觸發事件(在行中輸入日期)。
在偽代碼中,這是我希望宏執行的程序:
when (date in yyyy-mm-dd format entered into A[i]) {
fill B[i] with =CONCATENATE(SUBSTITUTE(LEFT(A[i], 7), "-", ""),RANDBETWEEN(0,1000000000));
copy B[i];
PASTE_VALUES B[i] in B[i];
}
抱歉,如果我忽略了解決此問題的先前答案。我對編碼并不陌生,但我對 Google 表格中的編碼很陌生,并且不確定使用什么術語或短語來描述我所追求的。
uj5u.com熱心網友回復:
我相信你的目標如下。
- 例如,將格式為的值
yyyy-mm-dd放入單元格“A1”時,您希望將公式放入=CONCATENATE(SUBSTITUTE(LEFT(A1, 7), "-", ""),RANDBETWEEN(0,1000000000))單元格“B1”中。 - 您想將公式的值固定為值。
- 您想使用 OnEdit 觸發器來實作這一點。
- 補充:當“B”列為空時,您想將值放入“B”列。
在這種情況下,下面的示例腳本怎么樣?
示例腳本:
請將以下腳本復制并粘貼到電子表格的腳本編輯器中,然后保存該腳本。并且,請設定您要使用的作業表名稱。當您使用這個腳本時,請將格式為 的值放到yyyy-mm-dd“A”列中,這樣腳本就會運行。
function onEdit(e) {
const sheetName = "Sheet1"; // Please set the sheet name.
const range = e.range;
const sheet = range.getSheet();
const [a, b] = range.offset(0, 0, 1, 2).getDisplayValues()[0];
if (sheet.getSheetName() != sheetName || range.columnStart != 1 || !/\d{4}-\d{2}-\d{2}/.test(a) || b) return;
const dstRange = range.offset(0, 1);
dstRange.setFormula(`=CONCATENATE(SUBSTITUTE(LEFT(${range.getA1Notation()}, 7), "-", ""),RANDBETWEEN(0,1000000000))`);
SpreadsheetApp.flush();
dstRange.copyTo(dstRange, { contentsOnly: true });
}
參考:
- 簡單觸發器
uj5u.com熱心網友回復:
這是我想出的腳本:
/** @OnlyCurrentDoc */
function onEdit(e) { //Runs every time the sheet is edited
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1'); //Change this to whatever your sheet is named
var inputCol = sheet.getRange('A1'); //Change this to whatever column the date is going to be entered
//This is the range that will be checked. Slightly redundant, but makes it easier to reuse this script without needing to retype every variable
var myRange = inputCol;
//Get the row & column indexes of the active cell
var row = e.range.getRow();
var col = e.range.getColumn();
//Check that your edited cell is within the correct column
if (col == myRange.getColumn()) { //This runs only if a value is entered into the column defined in 'inputCol'
if(sheet.getRange(e.range.getA1Notation()).getValue() == '') {return}; //If the edited cell is empty (ie the date is deleted, nothing happens)
if(row == 1) {return} //If the header is changed, nothing happens
let codeCell = sheet.getRange('B' row); //Change to the column that will store the generated code value
codeCell.setValue('=CONCATENATE(SUBSTITUTE(LEFT(A' row ', 7), "-", ""),RANDBETWEEN(0,1000000000))');
let hardValue = codeCell.getValue(); //Gets the value from the formula you just entered
codeCell.setValue(hardValue); //Replaces the formula with just the resulting value
};
}
包括評論以解釋正在發生的一切。下面鏈接的是我用來測驗的電子表格。它設定為允許編輯,因此請隨意使用它來自己測驗腳本。
https://docs.google.com/spreadsheets/d/1UONgRPBEbxn8CQeiRSPS4eFKHjh4ae8hXGYn6ImHxeI/edit?usp=sharing
希望這可以幫助!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/493949.html
