Solution
In order to achieve this you will have to use Google Apps Script. You can attach an Apps Script project to your Google Spreadsheet by navigating Tools > Script Editor
.
You should find a template function called myFunction
, a perfect starting point for your script.
Here you can start translating your VBA script to Apps Script which is very similar to Javascript.
First you should define some constants for your 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
Let's now loop through our range rows and columns to apply the logic:
The .getBackgrounds()
method returns a multidimensional array in the form 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
}
}
}
Reference
Please take a look at the documentation for further reading and method specifications
Google Apps Script Spreadsheet Service
Range Class
.getBackgrounds()
.getRange(row,column)