2026年10月12日 星期一

[研究]GAS跨Google試算表讀、寫欄位值

[研究]GAS跨Google試算表讀、寫欄位值

2026-10-12

GAS如何取得 Google試算表 (假設稱為 AAA1) 的 A1 欄位值,加上 Google試算表 (假設稱為 AAA2) 的 A2 欄位值,填寫另一個 Google試算表 (假設稱為 AAA3) 的 A3 欄位值?

GAS (Google Apps Script)


function addThreeSpreadsheets() { // 三份 Google 試算表的 ID const id1 = "AAA1的試算表ID"; const id2 = "AAA2的試算表ID"; const id3 = "AAA3的試算表ID"; // 取得三份試算表 const ss1 = SpreadsheetApp.openById(id1); const ss2 = SpreadsheetApp.openById(id2); const ss3 = SpreadsheetApp.openById(id3); // 取得各試算表的工作表(第一個工作表) const sheet1 = ss1.getSheets()[0]; const sheet2 = ss2.getSheets()[0]; const sheet3 = ss3.getSheets()[0]; // 讀取 AAA1 的 A1、AAA2 的 A2 const value1 = Number(sheet1.getRange("A1").getValue()) || 0; const value2 = Number(sheet2.getRange("A2").getValue()) || 0; // 相加 const result = value1 + value2; // 寫入 AAA3 的 A3 sheet3.getRange("A3").setValue(result); }

如何取得試算表 ID?

例如 AAA1 的網址是:

https://docs.google.com/spreadsheets/d/1AbCdEfGhIjKlMnOpQrStUvWxYz123456789/edit#gid=0

其中:

- 試算表 ID:1AbCdEfGhIjKlMnOpQrStUvWxYz123456789

- gid=0:工作表分頁的 ID,不是試算表 ID。

將程式中的 AAA1的試算表ID 替換成真正的 ID 即可。

三種方法比較

方法

適用情況

寫入方式

openById()

已知試算表 ID

getRange("A1").setValue("資料")

openByUrl()

已知完整網址

getRange("A1").setValue("資料")

getSheetByName()

要指定工作表名稱

先取得指定工作表,再寫入

(完)

相關

沒有留言:

張貼留言