首页 > 解决方案 > 根据谷歌表格中的背景颜色更改单元格值

问题描述

试图放弃 Excel 转而使用 Google 表格。我有一张空表,上面有一些需要用符号填充的彩色单元格。目前我使用这个 VBA 脚本来完成这项工作:

Sub mark()
    Dim r      As Range
    Dim rCell  As Range

    Set r = Selection.Cells

    For Each rCell In r
        If rCell.Interior.ColorIndex = 10 Then rCell.Value = "×"
        If rCell.Interior.ColorIndex = 3 Then rCell.Value = "×"
        If rCell.Interior.ColorIndex = 45 Then rCell.Value = "×"
        If rCell.Interior.ColorIndex = 1 Then rCell.Value = "×"
        If rCell.Interior.ColorIndex = 15 Then rCell.Value = "×"
    Next

End Sub

有没有办法使用谷歌表格完成同样的事情?

标签: google-sheets

解决方案


解决方案

为了实现这一点,您必须使用 Google Apps 脚本。您可以通过导航将 Apps 脚本项目附加到您的 Google 电子表格中Tools > Script Editor

您应该找到一个名为 的模板函数myFunction,这是您脚本的完美起点。

在这里,您可以开始将您的 VBA 脚本转换为与 Javascript 非常相似的 Apps 脚本。

首先,您应该为脚本定义一些常量:

  // An array containing the color codes you want to check
  const colors = ['#00ff00']; // Watch out, it's case sensitive 
  // A reference to the attached Spreadsheet
  const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetName'); // Selecting the Worksheet we want to work with by name
  // Here we retrieve the color codes of the backgrounds of the range we want to check
  const range = ss.getDataRange().getBackgrounds(); // Here I select all the cells with data in them

现在让我们循环遍历我们的范围行和列以应用逻辑:

.getBackgrounds()方法以 形式返回一个多维数组array[row][column] -> "background-color-code"

  for (let i = 0; i<range.length; i++) {
    let row = range[i];
    // Let's loop through the row now
    for (let j = 0; j< row.length; j++) {
      let color = row[j];
      // If the background color code is among the ones we are checking we set the cell value to "x"
      if(colors.includes(color)) {
        // Javascript index notation is 0 based, Spreadsheet one though, starts from 1
        ss.getRange(i+1, j+1).setValue("x"); // Let's add 1 to our indexes to reference the correct cell with the .getRange(row, column) function
      }
    }
  }

参考

请查看文档以进一步阅读和方法规范

Google Apps 脚本电子表格服务

范围类

.getBackgrounds()

.getRange(行,列)


推荐阅读