根据先前的单元格值突出显示单元格的后续范围

时间:2020-11-10 19:31:00

标签: google-apps-script google-sheets

如果前一个单元格的值是一个特定的字母,我试图突出显示一行中一系列后续单元格。

例如,如果单元格D5包含“ F”,则该单元格及其后的10个单元格(E5:N5)将变为红色。这需要适用于数组中的每个单元格-例如A1:F500

我尝试了使用自定义公式进行条件格式设置的尝试,但是现在都转向了脚本格式。我当时正在考虑分配一个通过数组运行的IF函数,然后执行上面的命令?

1 个答案:

答案 0 :(得分:0)

解决方案

您可以使用Apps Script来实现。

为此,请在所需的电子表格菜单栏中转到工具->脚本编辑器,然后使用以下功能。如果您已经在工作表中设置了值,则可以使用第一个功能。如果您要在旅途中设置此F值,则第二个也将为此提供支持。首先,我们简单地遍历范围以检查条件满足的位置并更改后续单元格的背景颜色。

请注意,如果范围不是从A1开始,则必须添加n行和n列,范围是从sheet.getRange(i+1,j+1,1,10).setBackground('red');开始。例如,如果您从D3开始,它将看起来像sheet.getRange(i+1+3,j+1+2,1,10).setBackground('red');

function myFunction() {
  // Get the desired sheet of your Spreadsheet where you want this functionallity
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  
  // Get values of your desired range
  var range = sheet.getRange('A1:I20').getValues();
  
  // iterate over each row and over each column within that row
  for(i=0;i<range.length;i++){
    
    for(j=0;j<range[i].length;j++){  
      // If the value on cell with row i and column j is F
      if(range[i][j]==='F'){
        // Set the background colour of the next 10 cells in that row
        // Also note that i+1 and j+1 because we iterate in the for loop from i=0, j=0
        sheet.getRange(i+1,j+1,1,10).setBackground('red');
      }
    }
  }
}


第二个功能函数使用简单的触发器onEdit(),该触发器基本上是一种函数类型,它将检测工作表中的任何编辑更改,例如单元格中的值更改。检测到此类更改后,您可以通过查看触发此更改的事件e来获取此单元格的值,并获取其范围和值。

最后,您只需要从检测到的列中选择所需的范围,并在行中进行更改,然后就可以设置该范围的背景颜色。

function onEdit(e) {
  // Get the desired sheet of your Spreadsheet where you want this functionallity
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  // if the changed cell value is equals to your condition
  if(e.range.getValue()=='F'){
    // set the next 10 columns in the changed row to a red background
    sheet.getRange(e.range.getRowIndex(), e.range.getColumnIndex(), 1, 10).setBackground('red');
  }
}

参考文献

我希望这对您有所帮助。让我知道您是否需要其他任何东西,或者您是否不了解。 :)