提问人:LionelHutz 提问时间:10/3/2023 最后编辑:LionelHutz 更新时间:10/6/2023 访问量:104
在编辑之前从值中获取富文本的 URL
Obtain URL from richtext from value before edit
问:
我的脚本的 F 列已激活日期验证(短日期)。 F 列中的所有单元格都包含带有日历事件 URL 的富文本:
每次编辑列 F(= 设置为新日期)时,我都希望我的脚本访问日历事件,并将其更新为新日期。 (这不是我问题的一部分,但解释了我最终想要实现的目标)。 编辑:这是我的整个脚本:
function DateEdit(e) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var editedRange = e.range;
var editedColumn = editedRange.getColumn();
if (editedColumn == 6) {
// Get event URL
var orgNumberFormats = editedRange.getNumberFormats();
editedRange.setNumberFormat("@");
var richTextValue = editedRange.getRichTextValue();
editedRange.setNumberFormats(orgNumberFormats);
var eventUrl = richTextValue.getLinkUrl();
// Get event ID
if (eventUrl) {
var eventIdEncoded = eventUrl.split("/").pop(); // Get the encoded part from the URL
try {
eventIdEncoded = eventIdEncoded.replace(/-/g, '+').replace(/_/g, '/'); // Revert URL-safe Base64 encoding
eventIdEncoded += "==".substring(0, 2 - eventIdEncoded.length % 2); // Add padding if needed
var eventIdDecoded = Utilities.base64Decode(eventIdEncoded);
var eventId = Utilities.newBlob(eventIdDecoded).getDataAsString();
var decodeEventId = eventId.split(" ")[0];
} catch (e) {
Logger.log("Error decoding and extracting the event ID: " + e);
}
} else {
Logger.log("Cell contains no URL.");
}
// Edit Event
try {
var newDateStr = editedRange.getValue(); // Assuming the date is in "dd/mm/yyyy" format
// Split the date string into parts
var dateParts = newDateStr.split('/');
var day = dateParts[0];
var month = dateParts[1];
var year = dateParts[2];
// Create a new Date object with the adjusted date
var newDate = new Date(year, month - 1, day); // Subtract 1 from the month because months are zero-based
if (!isNaN(newDate.getTime())) {
// The date string was successfully converted to a Date object
// Now, you can proceed with your code to update the event date
Logger.log("Event ID: " + decodeEventId)
var calendarId = '[email protected]'; // Replace with your calendar ID
var calendar = CalendarApp.getCalendarById(calendarId);
var event = calendar.getEventById(decodeEventId);
if (event) {
// Get the existing start and end times
var startTime = event.getStartTime();
var endTime = event.getEndTime();
// Create new Date objects with the adjusted date but the same time
var newStartTime = new Date(newDate);
newStartTime.setHours(startTime.getHours(), startTime.getMinutes());
var newEndTime = new Date(newDate);
newEndTime.setHours(endTime.getHours(), endTime.getMinutes());
// Update the event's start and end times with the new date
event.setTime(newStartTime, newEndTime);
Logger.log("Event date updated successfully, and guests have been notified.");
} else {
Logger.log("Event not found with ID: " + decodeEventId);
}
} else {
Logger.log("Invalid date format in the edited cell: " + newDateStr);
}
} catch (e) {
Logger.log("Error updating event with ID: " + decodeEventId + "\n" + e.toString());
}
}
}
问题是,如果不使用日期选择器,富文本中的 URL 可能会被其他用户覆盖和删除。我还没有找到在富文本中保留 URL 的方法。我可以获取编辑前的旧值 (e.oldValue),但不能获取 URL。
我需要我的脚本来获取URL,并在更改日期后将其作为RTF放回单元格(默认情况下,因为其他用户是否使用日期选择器或输入与给定验证格式匹配的手动日期并不重要)。
URL 不会更改,因为日历事件保持不变。
非常感谢任何帮助,提前致谢!
答:
虽然我不确定我是否能正确理解您的问题,但以下示例脚本怎么样?
示例脚本:
请将以下脚本复制并粘贴到 Google 电子表格的脚本编辑器中。并且,请设置 .sheetName
首先,请运行函数。这样,列“F”的当前单元格的 URL 将保存到 PropertiesService。init()
下一步,请手动修改电子表格中“F”列的值。这样,由简单的触发器自动运行。并且,URL 设置为编辑后的单元格。onEdit
const sheetName = "Sheet1"; // Please set your sheet name.
// First, please run this function.
function init() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const urls = sheet.getRange("F1:F" + sheet.getLastRow()).getRichTextValues().map(([f]) => f.getLinkUrl() || "");
PropertiesService.getScriptProperties().setProperty("urls", JSON.stringify(urls));
}
function onEdit(e) {
const { range } = e;
const sheet = range.getSheet();
if (sheet.getSheetName() != sheetName || range.columnStart != 6) return;
const prop = PropertiesService.getScriptProperties();
const propUrls = prop.getProperty("urls");
const urls = propUrls ? JSON.parse(propUrls) : [];
const url = urls[range.rowStart - 1];
const currentUrl = range.getRichTextValue().getLinkUrl();
if (currentUrl) {
urls[range.rowStart - 1] = currentUrl;
prop.setProperty("urls", JSON.stringify(urls));
} else if (url) {
range.setRichTextValue(range.getRichTextValue().copy().setLinkUrl(url).build());
}
}
重要:
- 在此脚本中,它假定列“F”的 URL 是常量。如果添加并更新了“F”列的 URL,请运行该函数。这样,PropertiesService 中的 URL 也会更新。
init()
注意:
此示例脚本是 的简单示例脚本。请小心这一点。
I need my script to obtain the URL & put it back to the cell as RTF after the date was changed
Google Apps 脚本的属性服务规范可以在此报告中看到(作者:我)。如果您的情况超出了 Properties Service 的当前规范,则可能需要使用临时电子表格。
引用:
评论
I understand your idea with the INIT() function, but I would need something that doesn't need manual execution and comes with the trigger.
init
I just can't find a way to obtain the old URL once the cell value has been overwritten
but I would need something that doesn't need manual execution and comes with the trigger.
init
onEdit
basically all I try to achieve is that the URL in the richtext will be preserved, even if a user overwrites the date manually, removing the URL.
评论