【问题标题】:Change cell value based on its background color in google sheets根据谷歌表格中的背景颜色更改单元格值
【发布时间】:2020-11-05 12:09:48
【问题描述】:

试图放弃 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


    【解决方案1】:

    解决方案

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

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

    在这里您可以开始将您的 VBA 脚本翻译成与 Javascript 非常相似的 Apps Script。

    首先你应该为你的脚本定义一些常量:

      // 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 Script Spreadsheet Service

    Range Class

    .getBackgrounds()

    .getRange(row,column)

    【讨论】:

    • 我很高兴它有帮助!请接受答案,以便有相同问题的其他人更容易找到解决方案!一些细节here
    猜你喜欢
    • 2013-04-28
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2015-02-03
    • 2014-09-30
    相关资源
    最近更新 更多