【问题标题】:Google Sheets Script Find Cell Errors In RangeGoogle表格脚本查找范围内的单元格错误
【发布时间】:2021-08-27 11:40:28
【问题描述】:

我正在尝试使用脚本中的 Range 来查找有错误的单元格。范围由使用 Sparkline() 从 GoogleFinance() 获取数据的单列 AB 单元格组成,这经常返回错误 Google Finance internal error.,并显示 #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(),但没有找到任何返回单元格错误的内容。

有什么建议吗?

【问题讨论】:

  • 我不确定你想用你的脚本做什么,但这看起来很奇怪:var range = sheet.getRange('Portfolio_Sparklines');。你需要read the documentation
  • 嗨 Dimitry,Portfolio_Sparklines 是一个命名范围。我经常使用它们,因为它们在多张纸上被引用。与在脚本中输入硬编码范围相比,在脚本中使用它们的一大优势是它们反映了对工作表布局的任何更改,例如添加一列。
  • 我不确定它的问题,但你从来没有声明rv。如果你只登录data[i][0]会发生什么?
  • 顺便说一句,Logger 有很多问题,如果可以的话,请改用console.log()
  • 我修复了缺少的声明 var,并尝试了您的建议(console.log,data[i][0]),但仍然没有任何乐趣。

标签: google-apps-script google-sheets


【解决方案1】:

问题

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

Google 财经在 Google Apps 脚本中被阻止。见Reading the values of cells that summarize Google Finance data results via Apps Script

附言

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

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

【讨论】:

  • 谢谢。 (1) 我想我误解了 GoogleFinance() 中的文档 - 认为该函数不能在脚本中使用,不明白结果 - 包括错误 - 也不能返回。 (2) 取点 reflush()。 (3) 很久没用GAS了,还在尝试使用数组。我需要进一步研究。