You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Apps Script需求:按ID更新或追加Google Sheet数据

问题:Google Sheet脚本实现ID存在更新、不存在追加功能

现有Google Sheet包含:

  • Validation_1表单页:读取报告数据并录入验证评论(E列下拉选择Agree/Disagree等),唯一ID存于C2单元格
  • Data目标页:存储验证后的记录,A列为唯一ID

当前脚本仅能在Data页已存在对应ID时更新数据,需修改实现:

  • 若Data页A列存在该ID,更新对应行的验证数据
  • 若ID不存在,将完整记录追加至Data页的下一行空白行

原始代码问题

原代码未处理ID不存在的情况,且存在拼写错误(updatesourchRangeE应为updatesourceRangeE),会导致ID不存在时脚本报错。

修改后的完整代码

const ss = SpreadsheetApp.getActiveSpreadsheet();
const dataWS = ss.getSheetByName("Data");
const updatesourceRangeE = ["C5", "E6", "E7", "E9", "E11", "E13"];
const formWS = ss.getSheetByName("Validation_1");

function saveData() {
  // 获取当前表单的唯一ID
  const id = formWS.getRange("C2").getValue();
  if (!id) {
    SpreadsheetApp.getUi().alert("请先填写唯一ID!");
    return;
  }

  // 在Data页查找ID
  const idFound = dataWS.getRange("A:A").createTextFinder(id).matchEntireCell(true).findNext();
  let targetRow;

  if (idFound) {
    // ID存在,获取对应行号
    targetRow = idFound.getRow();
  } else {
    // ID不存在,获取下一个空白行(从A列最后有数据的行+1)
    targetRow = dataWS.getLastRow() + 1;
  }

  // 收集验证数据:先取C5的Name值,再依次取E列的评论
  const colEdata = updatesourceRangeE.map(range => formWS.getRange(range).getValue());
  // 把ID放到数组首位
  colEdata.unshift(id);

  // 写入数据到目标行
  dataWS.getRange(targetRow, 1, 1, colEdata.length).setValues([colEdata]);
  SpreadsheetApp.getUi().alert("数据保存成功!");
}

关键改动说明

  • 新增ID校验:先判断C2是否为空,避免空ID导致的错误操作
  • 处理ID不存在的场景:通过getLastRow()获取Data页最后一行,+1得到新记录的插入行
  • 修复拼写错误:修正原代码中updatesourchRangeE的拼写错误为updatesourceRangeE
  • 添加操作提示:用alert反馈保存状态,提升用户体验

表格结构参考

Validation_1表单页示例

---A-空列B-报告表头C-报告信息D-空列E-用户输入
1
2Unique ID:12345
3
4DemographicsReport dataComment
5Name:John DoeAgree
6Date of Bith:9/15/64Disagree incorrect year
7Insurance ID:R8384958Agree
8
9Arrival date:8/1/24Agree
10
11Procedure date:8/3/24UTD - record not available
12
13Depart date:8/5/24Agree

Data目标页示例

---ABCDEFG
1Unique IDNameDOBInsur IDArrivalProcDepart
212345John DoeAgreeDisagree incorrect yearAgreeAgreeUTD-record not available
367890NancyAgreeAgreeAgreeAgreeAgree
413579
524680
6
7

内容的提问来源于stack exchange,提问作者deb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 20:24:52