尽管在Apps脚本

时间:2018-01-31 19:08:40

标签: javascript google-apps-script google-docs

getBody仍然在Apps脚本中返回null,即使我已经查找错误并调试最多。另一位用户(他向我指出了大部分错误)表示,此代码中的getBody不为null。这是我的代码或Apps脚本的错误吗?

function myFunction() {

var searchResult = DocumentApp.getActiveDocument().getBody().findText("very",searchResult)
Logger.log(searchResult)



while (searchResult !== null) {

searchResult.getElement().asText().setAttributes(searchResult.getStartOffset(),searchResult.getEndOffsetInclusive(),"#FF000")

searchResult = DocumentApp.getActiveDocument().getBody().findText("very",searchResult)

}



function highlightProblem() {

var words = ["very","so","totally","really"] 

words.forEach(findText) 

  }


 function onOpen(){
DocumentApp.getUi().createMenu('everythingisnotfine.avi').addItem('Higlight Words That Make You Sound Like a Dandy', 'higlightProblem').addToUi()
}}

1 个答案:

答案 0 :(得分:0)

您的主要问题是您在使用searchResult之前就已经定义了它。

var searchResult = DocumentApp.getActiveDocument().getBody().findText("very",searchResult)

由于您尚未定义searchResult,因此您无法通过findText() searchResult来启动。一旦你有第一个searchResult变量定义,你可以在while循环中使用来找到匹配

while (searchResult !== null) {
 searchResult = DocumentApp.getActiveDocument().getBody().findText(very,searchResult)
 }

其次,您正在使用onOpen()的上下文定义函数highlightProblem()myFunction(),如此

function myFunction(){  // <--- Start of my function

 function highlightProblem(){
 }
 function onOpen(){
 }
}                      //<-- End of my function 

您需要单独定义每个功能,如下所示。

您的最终代码:

function findText(searchString) {
 Logger.log(searchString)
 var doc = DocumentApp.getActiveDocument()
 //var doc = DocumentApp.openByUrl("Copy and paste URL of your doc here")
 var searchResult = doc.getBody().findText(searchString)
 Logger.log(searchResult)
 var style = {};
  style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#FFFF00';
 while (searchResult !== null) {
 searchResult.getElement().asText().setAttributes(searchResult.getStartOffset(),searchResult.getEndOffsetInclusive(),style)
 searchResult = DocumentApp.getActiveDocument().getBody().findText(searchString,searchResult)
 }
}

function highlightProblem() {
 var words = ["very","so","totally","really"] 
 words.forEach(findText)   
}



 function onOpen(){       
DocumentApp.getUi().createMenu('everythingisnotfine.avi').addItem('Higlight Words That Make You Sound Like a Dandy', 'highlightProblem').addToUi()
    }

运行代码的步骤
1)按原样复制并粘贴脚本编辑器。然后运行onOpen()函数将自定义菜单添加到文档中 2)您可以从脚本编辑器或自定义菜单中运行高亮显示功能 3)如果仍然无法运行它,请取消注释(删除//)此行并复制并粘贴上述URL //var doc = DocumentApp.openByUrl("Copy and paste URL of your doc here")