首页 > 解决方案 > 谷歌表格脚本查找范围内的单元格错误

问题描述

我正在尝试使用脚本中的 Range 来查找有错误的单元格。ABRange 由使用 Sparkline() 从 GoogleFinance() 获取数据的单列单元格组成,该数据通常返回 ErrorGoogle Finance internal error.和 display #N/A。错误显示

在此处输入图像描述

但是,当我尝试获取值时,该函数没有返回任何内容:

function portfolioRefreshSparklines(){
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Portfolio');
  const msg = 'Refreshing...';
  const err = '#N/A';

  var range = sheet.getRange('Portfolio_Sparklines');
  var col = range.getColumn();
  var rowStart = range.getRow();
  Logger.log('col: ' + col + '; rowRange: ' + rowStart);

  var data = range.getValues();
  for ( i=0; i<data.length; i++ ) {


    // this is NOT returning the `#N/A` error (`Google Finance internal error.`)
    var rv = data[i][0];
    Logger.log('i: ' + i + '  rv: '+ rv)  

  
    // If an error is found, set the cell's formula to the msg, then back to the original formula.
    // Think I have to reference the cell directly to do the setFormula() switch, not within the data array?
    if ( rv.includes(err) ){
      var row = rowStart + i;
      var cell = sheet.getRange(row, col);
      Logger.log('cell: ' + cell.getA1Notation() );
      rv = cell.getFormula();
      cell.setFormula(msg);
      cell.setFormula(rv);
    }
  }
  SpreadsheetApp.flush();
}

我搜索了 Range 类,尝试使用函数 getDisplayValues(),但没有找到任何返回单元格错误的内容。

有什么建议吗?

标签: google-apps-scriptgoogle-sheets

解决方案


从问题

但是,当我尝试获取值时,该函数没有返回任何内容:

Google 财经在 Google Apps 脚本中被阻止。请参阅通过 Apps 脚本读取汇总 Google 财经数据结果的单元格的值

附言

  1. SpreadsheetApp.flush()包含在最后一个函数语句中是没有意义的。当您需要强制在函数结束之前应用所做的更改时应该使用它,因为您将读取由脚本更改的内容以供稍后使用。

  2. 最佳做法不鼓励在循环中使用 Google Apps 脚本类(在本例中 var cell = sheet.getRange(row, col);),因为它们很慢。


推荐阅读