A script designed to dynamically change font styles based on date ends up unintentionally wiping out existing formulas in cells

In order to keep my spreadsheet organized for scheduling purposes, I have implemented a script that changes the font style of rows based on the date. If the date has already passed, the font is changed to italics, greyed out, and with a line-through effect. While the script works well, it unfortunately overrides all formulas in the spreadsheet when applied. Is there a way to modify the formula so that it does not impact specific cells? For example, I do not want it to affect rows that are designated for dates in the future.

Below is the script I am currently using:

function formatOnDate() {
  var sh = SpreadsheetApp.getActive().getActiveSheet();
  var range = sh.getDataRange();
  var data = range.getValues();
  var color = '#AAA';// value you want
  var style = 'italic';// value you want
  var line = 'line-through';// value you want
  var fontColors = range.getFontColors();// get all font colors
  var fontLines = range.getFontLines();// lines
  var fontStyles = range.getFontStyles();//style
  var today = new Date();// include today in sheet

  //var today = new Date(new Date().setDate(new Date().getDate()-1));// exclude today... uncomment the one you use
  for(var n=1 ; n<data.length ; n++){ // start on row 2 so that headers are not changed
    if(data[n][0] < today){
      for(var c in data[0]){
        fontColors[n][c]=color;//set format
        fontLines[n][c]=line;//set format
        fontStyles[n][c]=style;//set format

      }
    }
  }
  //sh.getRange(1,1,data.length,data[0].length).clear();
  // now update sheet with new data and style
  sh.getRange(1,1,data.length,data[0].length).setValues(data).setFontColors(fontColors).setFontLines(fontLines).setFontStyles(fontStyles);
}

Is there a way to adjust the font styles without interfering with cell formulas? Can we ensure that only past dates are affected, leaving future dates untouched? Alternatively, is there a method to exclude certain columns from this formatting? (Columns N-Q contain formulas)

Answer №1

Your code remains unchanged with the exception of FontColors, FontLines, and FontStyles being applied to the range. This adjustment ensures that the data is not overwritten and only specific styling elements are affected.

Original Code :

sh.getRange(1,1,data.length,data[0].length).setValues(data).setFontColors(fontColors).setFontLines(fontLines).setFontStyles(fontStyles);

Updated Code :

range.setFontColors(fontColors).setFontLines(fontLines).setFontStyles(fontStyles);

If there was any misinterpretation on my part, I apologize.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can DataTables (JQuery) filter multiple columns using a text box with data stored in an array?

I've been attempting to create a multi-column filter similar to what's shown on this page () using an array containing all the data (referred to as 'my_array_data'). However, I'm facing issues with displaying those filter text boxe ...

Command in Selenium Webdriver for initiating a mouse click

Currently, I am in the process of writing tests for a Java application that has been created with the Vaadin framework. To conduct these tests, I have opted to utilize the Robot Framework. In certain instances, I must implement robot framework commands suc ...

Adjust the header image as you scroll

Currently, I have a static image in the header of the page. I'm looking to have the image change to a different one when half the page has been scrolled. Do I need to utilize JavaScript for this functionality or is it achievable with CSS alone? bo ...

What is the best way to extract and process CSV data from a JavaScript array of strings to incorporate into d3 visualizations?

I am looking to utilize data stored in a JavaScript array of strings to create a d3 graph that showcases a time series of timestamp (t), receive (rx), and transmit (tx) counters. Each element in the array represents one line of time, rx, tx data with comma ...

Exploring the possibilities of integrating JSONP with Framework7

I've been attempting to retrieve images from the Instagram public API using ajax and JSONP: var target = https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1?callback=?'; $$.ajax({ ty ...

Fiddler is indicating that my JavaScript file cannot be found, despite the fact that it is present and functioning correctly as anticipated

In Default.aspx, I have added the following line to my javascript file: <script type="text/javascript" src="../../MyFiles/JavaScript/JavaScript.js" ></script> When testing the website using Fiddler, I repeatedly receive a 404 error indicatin ...

jQuery Issue: Submission Count Doubling with Each POST Request

My current issue involves using jQuery to send data to a PHP file, but I've noticed that each time I submit the form, the data gets duplicated. Initially, it posts once when I press the submit button. However, upon returning to update the form and sub ...

Should you construct a fresh element using JavaScript, or opt to reveal a concealed one using CSS?

What are the benefits of using the following approach: var target = document.getElementById( "target" ); var newElement = document.createElement( "div" ); $( target ).after( newElement ); compared to just hiding the newElement div with CSS and showing ...

Having trouble locating an element, Sammy?

I am encountering an issue while using Sammy for my SPA. The error message I receive is: [Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get / Error: 404 Not Found get / at Sammy.Application.error (sammy-latest ...

Ways to retrieve information from a component using a function

Hello! I'm currently facing a challenge with the following scenario: I am developing a Vue application with multiple components. One of these components utilizes vee-validate for validation purposes. I need to modify a data element within the compone ...

Issue with Transparency in Background Loading of FBX Files using Three.js

I am currently exploring three.js and have encountered an issue with transparency not working as expected. Despite trying various settings, I cannot seem to achieve a transparent background - it always defaults to black or interprets the values as an RGB v ...

The document does not contain any serialized JavaScript files

Hey there, I'm facing an issue with my Codeigniter and JavaScript file upload and insertion into the database. I'm not getting any response, so could you please take a look at my code and share some valuable ideas? Below are the codes for the vie ...

There is no overload that matches this call. The previous overload resulted in an error stating that type 'text' cannot be assigned to type 'json'

I am attempting to retrieve an HTML page from my API using Angular and including JWT tokens in the header. However, when I do not specify the response type as text, the compiler returns a parsing error (as it initially tries to parse the HTML as JSON), so ...

Animate a lone div once and for all

I'm attempting to create a vertical category menu similar to the one on . I've successfully implemented the vertical menu with transition effects. However, my issue is that I only want the transition to occur the first time a category is clicked. ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

jQuery parallax effect enhances scrolling experience with background images

My website features a parallax design, with beautiful high-resolution images in the background that dominate the page. Upon loading the site, the landing page showcases a striking, large background image alongside a small navigation table ('about&apos ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

How can we ensure that paragraphs are validated correctly in a multiline Textbox using JavaScript?

Currently, I am attempting to validate text (paragraphs) in JavaScript for a multiline textbox. The requirement is that after entering text into the textbox, the very first letter should be changed to a capital letter while the rest should remain in lowerc ...

Difficulty with Horizontal Mousewheel Scrolling

Struggling to implement a horizontal scrolling feature (via mousewheel) for both containers in the code below. I want this feature to be easily applied to any future container creations as well. <body> <style> #container { display: flex ...

Is there a way to execute a node script via command line sans the need for installation and external packages?

Is there a way to execute a node script from the command line during development without actually installing anything, but still having access to installed packages using npm install <...>? When I try node ./bin/my_script.js, the script does not reco ...