0

我在谷歌電子表格,我知道如何創建一個新的菜單項,但一個人如何執行與谷歌電子表格appscript代碼如下:在Google Spreadsheets中,如何在用戶點擊並激活單元格後,從另一個單元格的值中設置單元格的值?

If in cell A2, I click a menuitem "SetValue", then A2's cell value is set with value from A1. 
If in cell B2, I click a menuitem "SetValue", then B2's cell value is set with value from B1. 
If in cell C2, I click a menuitem "SetValue", then C2's cell value is set with value from C1. 
... (and so forth and so on) 

請記住,用戶可以隨機在啓動菜單項功能之前,單擊第2行中的任何單元格。

回答

0

這應該對你有用。

function myFunction() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var cell = ss.getActiveCell(); 
    var row = cell.getA1Notation()[1]; 
    var column = cell.getA1Notation()[0]; 
    if (row != 2) { 
    ss.toast("not valid selection, must be in row 2"); 
    return; 
    } 
    var sourceVal = ss.getRange(column+(row - 1)).getValue(); 
    cell.setValue(sourceVal); 
    return; 
} 
+0

這將失敗的列> 26 ...(使用2個字母的A1表示法) –

+0

感謝您指出,並沒有意識到 – AshClarke

+0

也:行是一個字符串,當您檢查行時,您必須添加引號以獲得相同的條件== 2。爲了方便,我在另一個答案中寫了一個工作版本。 –

1

下面是@teatimer的其他答案中顯示的函數的另一個版本,適用於所有列。我會在評論中寫了這一點,但它會一直難讀這樣......

function myFunction() { 
    var ss = SpreadsheetApp.getActiveSpreadsheet(); 
    var cell = ss.getActiveCell(); 
    var row = cell.getA1Notation().replace(/[^0-9]/g,'');// keep only numeric values 
    var column = cell.getA1Notation().replace(/[0-9]/g,'');//remove all numeric characters 
    Logger.log('row '+row+' column '+column); 
    if (row != '2') { // row is a string, you must add quotes to get an equal condition 
    ss.toast("not valid selection, must be in row 2"); 
    return; 
    } 
    var sourceVal = ss.getRange(column+(row - 1)).getValue(); 
    cell.setValue(sourceVal); 
} 

您還可以使用正則表達式的另一種形式,以獲得相同的結果:

var row = cell.getA1Notation().replace(/\d/g,'');// remove non decimal values 
    var column = cell.getA1Notation().replace(/\D/g,'');//remove decimal values 
+0

感謝teatimer和塞爾! @Serge - 需要稍作修改 - 翻轉行和列,然後工作。行是數字,列是非數字的。 – user4127929

+0

哦!確實 !我會編輯代碼...感謝提到錯字...我的測試沒問題,但是我有時候玩代碼太多;-) –

相關問題