Google-sheets – How to use Google’s functions in a spreadsheet’s script

google sheetsgoogle-apps-scriptimportxml

When I use a function such as =importXml("http://www.google.com", "//a/@href") in a Google Spreadsheet cell, it works just fine. However, when I try to use the same function in a script, it gives an error message.

My script has the following code:

function myFunction() {
  return importXml("http://www.google.com", "//a/@href");
}​

When I call the function from a cell by using =myFunction(), I get the following error:

error: ReferenceError: "importXml" is not defined.

How can I use the importXml function in a script?

Best Answer

In addition to the remark made by Barry, here's a link that explains the usage of XML in combination with Google Apps Script (GAS): XML with GAS

You can use the importXML formula in GAS, but you have to address it as a formula:

function myXML() {
  var cell = SpreadsheetApp.getActiveSpreadsheet()
    .getActiveSheet().getActiveCell();
  cell.setFormula('=importXml("http://www.google.com", "//a/@href")');  
}

Reference: setFormula