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

谷歌表格脚本实现A列唯一时间戳防重复(阻止粘贴重复值)问题求助

谷歌表格脚本实现A列唯一时间戳防重复(阻止粘贴重复值)问题求助

我现在遇到个头疼的问题:我的谷歌表格Sheet1的A列存了大量唯一的时间戳(格式比如22/08/2022 15:34:21),我需要确保这些时间戳绝对唯一,重点是要阻止用户通过复制粘贴的方式插入重复值——毕竟普通的数据验证拦不住粘贴操作,这点我已经试过了没用。

我自己写了一段脚本想解决这个问题,但现在出问题了:不管输入的是不是重复值,脚本都会清空单元格内容,虽然会弹出提示框,但正常的新时间戳也被删掉了,这完全不是我想要的效果。另外补充一下,新数据不仅可能由用户在任意行输入,还有后台运行的其他脚本也会往A列写入内容,这点也得考虑进去。

下面是我写的脚本代码:

function PreventTimeStampDuplicate(e) {

const sh = e.range.getSheet();

const columnToCheck = 1; // Change this to the appropriate column number (1 for column A, 2 for B, etc.)

if (sh.getName() == "Sheet1" && e.range.getColumn() == columnToCheck && e.value !== null) {

const values = sh.getRange(2, columnToCheck, sh.getLastRow() - 1, 1).getValues().flat();

const uniqueValues = {};

for (let i = 0; i < values.length; i++) {

if (uniqueValues[values[i]]) {

e.range.clearContent();

showDialog("Duplicate Timestamp", "You have copied a timestamp. Timestamp copy automatically deleted in order to avoid show ID collision.");

break; // Exit the loop early since we found a duplicate

} else {

uniqueValues[values[i]] = true;

}

}

}

}

function showDialog(title, message) {

var ui = SpreadsheetApp.getUi();

ui.alert(title, message, ui.ButtonSet.OK);

}

有没有大佬能帮我看看哪里错了?怎么修改才能让脚本只删除真正重复的时间戳,正常的新值能保留,同时兼容任意行输入和后台脚本写入的场景?万分感谢!

备注:内容来源于stack exchange,提问作者LionelHutz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 10:34:29