【发布时间】:2014-10-13 20:59:17
【问题描述】:
我有一个 Google 表单,在提交时,电子表格会运行一个脚本来比较变量并从模板创建一个新文档。当脚本中的变量不同时,我还想突出显示文档中的文本。我发现在执行 replaceText() 之前,我需要先格式化文档中的文本。
var matching = e.values[29]; //column in spreadsheet
var keymatching = "2b, 6a, 7a, 8b";
// Get document template, copy it as a new temp doc to folder, and save Doc's id
var targetFolder = DocsList.getFolderById("0B4bnlgTJUvsgeV9XelN4a243Y1k");
var file = DocsList.getFileById(docTemplate)
.makeCopy(docName+' ~ '+first_name+' '+last_name);
var copyId = file.getId();
file.addToFolder(targetFolder);
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
var background = background || '#F3E2A9'; // default color is light orangish.
var target = 'keyMatching' //text in document
var bodyElement = copyDoc.getBody()
var searchResult = bodyElement.findText(target);
var thisElement = searchResult.getElement();
var thisElementText = thisElement.asText();
if (matching == keymatching) {} else {thisElementText.setBackgroundColor(searchResult.getStartOffset(),searchResult.getEndOffsetInclusive(),background)};
// Replace place holder keys, in our google doc template
copyBody.replaceText('keyMatching', matching);
我有 27 个目标/键匹配变量。有没有办法循环这个,所以我不会为 27 个中的每一个重新创建 var target、var seachResult、var thisElement 和 var thisElementText?
谢谢
编辑:
我发现我很可能需要使用数组遍历变量。这是我更新的代码:
var matching = e.values[29]; //column in spreadsheet
var keymatching = "2b, 6a, 7a, 8b";
// Get document template, copy it as a new temp doc to folder, and save Doc's id
var targetFolder = DocsList.getFolderById("0B4bnlgTJUvsgeV9XelN4a243Y1k");
var file = DocsList.getFileById(docTemplate)
.makeCopy(docName+' ~ '+first_name+' '+last_name);
var copyId = file.getId();
file.addToFolder(targetFolder);
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document's body section
var copyBody = copyDoc.getActiveSection();
var background = background || '#F3E2A9'; // default color is light orangish.
var target = ["keyMatching", "keyCount1", "keyCount2"]; //text in document, made an array
var bodyElement = copyDoc.getBody()
for (i in target) {
var searchResult = bodyElement.findText(target[i]);
var thisElement = searchResult.getElement();
var thisElementText = thisElement.asText();
if (matching == keymatching) {} else {thisElementText.setBackgroundColor(searchResult.getStartOffset(),searchResult.getEndOffsetInclusive(),background)};
}
// Replace place holder keys, in our google doc template
copyBody.replaceText('keyMatching', matching);
我仍然坚持如何让它只在变量不匹配时突出显示文档中的字段。
【问题讨论】: