简体   繁体   中英

Google App script to clear cells values on the base of Font color of that cell

I have a google sheet with lot of values on it, is it possible to write a small function which can clear all the values from all cells which have red font color.

Explanation:

  • The first thing you need to do is to get the font colors of your data range. A straightforward way to get the data range is to use getDataRange() . To get the font colors of the data range you need to use getFontColors() . The latter gives the hexadecimal font color codes of your cells. Red in google sheets (second row second column in the color picker of the ui ) is #ff0000 .

  • Now that you have the color array, you need to iterate through every row and element and check whether the color is equal to #ff0000 . If it is, then use clearContent() to clear the content of that cell.

Solution:

Choose the name of your sheet instead of Sheet1 .

function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();  
  const sh = ss.getSheetByName('Sheet1');  
  const colors = sh.getDataRange().getFontColors();
  colors.forEach( (r,i) => {     
    r.forEach((c,j)=>{
    if (c=='#ff0000'){
    sh.getRange(i+1,j+1).clearContent();}
  })})
}

Limitations:

While this approach works perfectly fine for a fair amount of data, having two forEach loops where you execute getRange iteratively is not a good practice. But I hope it will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM