imagegoogle-apps-scriptgoogle-sheets

Apps Script Delete Image


I've got this script:

function testchartbuild() {  
  var sheet = SpreadsheetApp.getActiveSheet();
  var chart = sheet.newChart()
    .setChartType(Charts.ChartType.LINE)
    .asLineChart()
    .setOption("useFirstColumnAsDomain", false) 
    .addRange(sheet.getRange("BA24:BD231"))
    .setNumHeaders(1)
    .setPosition(5, 5, 0, 0)
    .setOption("legend", {position: "bottom"})
    .setOption("width", 690)
    .setOption("height", 195)
    .build();
  
  // create an image from that EmbeddedChart
  sheet.insertImage(chart.getBlob(),58,2);  // this works
};

It currently works great to create a chart, and display it as an image on my sheet. I am doing it this way because I can't create a chart above a locked row. Each time I run the script, it creates a new image on top of the old image (if the script was run previously). I would like to edit the script so that it looks to see if another image is already there first, deletes it, then replaces it with the new chart image. I've been looking everywhere to find a way to delete the old image first but can't figure it out. Any help would be great! Thanks


Solution

  • In your situation, in order to remove the existing image with the anchor cell "BF2", how about the following modification?

    From:

      .build();
    
    // create an image from that EmbeddedChart
    sheet.insertImage(chart.getBlob(),58,2);  // this works
    

    To:

      .build();
    
    sheet.getImages().forEach(e => {
      if (e.getAnchorCell().getA1Notation() == "BF2") {
        e.remove();
      }
    });
    
    // create an image from that EmbeddedChart
    sheet.insertImage(chart.getBlob(),58,2);  // this works
    

    Note:

    References: