我有一組正在復制粘貼到作業表上的資料。資料有一列持續時間寫為 X h X min。但是,這些值不會被識別為數字值,因此無法將資料用于任何計算。我找到了一個 onEdit 腳本,可以將文本更改為適當的時間值,但只有在我逐個編輯每個單元格時它才會起作用。
有什么方法可以用一個可以用按鈕觸發的腳本代替這個腳本,而不是每次編輯單元格時?
function onEdit(e) {
var value = e.value;
if (typeof value == 'string') {
var match = value.match(/(\d ) ?h/i);
var hours = match ? match[1] : 0;
match = value.match(/(\d ) ?m/i);
var minutes = match ? match[1] : 0;
match = value.match(/(\d ) ?s/i);
var seconds = match ? match[1] : 0;
if (hours || minutes || seconds) {
var duration = hours/24 minutes/1440 seconds/86400;
e.range.setValue(duration).setNumberFormat('[h]"h "m"m "s"s"');
}
}
}
我嘗試了以下方法,但不起作用:
function setDuration(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var value = sheet.getRange("C45:C80").getValues();
if (typeof value == 'string') {
var match = value.match(/(\d ) ?h/i);
var hours = match ? match[1] : 0;
match = value.match(/(\d ) ?m/i);
var minutes = match ? match[1] : 0;
match = value.match(/(\d ) ?s/i);
var seconds = match ? match[1] : 0;
if (hours || minutes || seconds) {
var duration = hours/24 minutes/1440 seconds/86400;
range.setValues(duration).setNumberFormat('[h]"h "m"m "s"s"');
}
}
}
我無法理解 onEdit 腳本的作業方式。我知道我需要設定一個for回圈或一個陣列,但我對它們的作業方式感到困惑。
uj5u.com熱心網友回復:
在你的情況下,下面的修改如何?
修改后的腳本:
function setDuration(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange("C45:C80");
var values = range.getValues();
var formats = range.getNumberFormats();
var {converted, format} = values.reduce((o, [value], i) => {
if (typeof value == 'string') {
var match = value.match(/(\d ) ?h/i);
var hours = match ? match[1] : 0;
match = value.match(/(\d ) ?m/i);
var minutes = match ? match[1] : 0;
match = value.match(/(\d ) ?s/i);
var seconds = match ? match[1] : 0;
if (hours || minutes || seconds) {
var duration = hours/24 minutes/1440 seconds/86400;
o.converted.push([duration])
o.format.push(['[h]"h "m"m "s"s"']);
} else {
o.converted.push([value]);
o.format.push(formats[i]);
}
} else {
o.converted.push([value]);
o.format.push(formats[i]);
}
return o;
}, {converted: [], format: []});
range.setValues(converted).setNumberFormats(format);
}
在此修改中,用于將字串轉換為日期和數字格式的腳本被復制到單元格中。
在您的腳本中,
value是一個二維陣列。這樣,您的 if 陳述句始終為false. 這樣,您在 if 陳述句中的腳本就不會運行。我認為這可能是您的問題的原因。
參考:
- 降低()
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358819.html
