解决方案
为了实现这一点,您必须使用 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)