Google Apps Script: Finding text and setting cursor to found text

浪子不回头ぞ 提交于 2019-12-12 04:56:57

问题


I would like to setCursor to the location that is returned by findText.

Here is what I am trying:

    var position = doc.newPosition(foundElement.getElement(), foundElement.getStartOffset());
    doc.setCursor(position);

But, the cursor does not move. Even with the simple examples like

 //setting cursor at the beginning of the doc
 var paragraph = doc.getBody().getChild(0);
 var position = doc.newPosition(paragraph.getChild(0), 0);
 doc.setCursor(position);

findText returns a rangelement, while document.setCursor expects a position. How do I go from rangeelement to position? :)

This got me halfway to the solution Finding text (multiple times) and highlighting


回答1:


Tried this code and it is perfectly setting the cursor in the beginning of the found text.

function myFunction() {
  var doc = DocumentApp.getActiveDocument();
  var paragraph = doc.getBody().getChild(0);
  var foundElement = doc.getBody().findText("text");
  var position = doc.newPosition(foundElement.getElement(), foundElement.getStartOffset());
    doc.setCursor(position);
}

Hope that helps!



来源:https://stackoverflow.com/questions/28412258/google-apps-script-finding-text-and-setting-cursor-to-found-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!