Home > Enterprise >  Moving contents of a cell with app script in Google sheets
Moving contents of a cell with app script in Google sheets

Time:03-27

Image of the lines of codeFor something I've been working on, it involves moving an image from one cell to another through appscript or functions. I've tried to figure out ways to do this, but had no luck. Does anybody have any suggestions? For example, I would need to move an image on A11 to A34.

CodePudding user response:

Sample script 1:

About For example, I would need to move an image on A11 to A34., if your image is put over the cell "A11", and you want to move it to the cell "A34", how about the following sample script?

function sample1() {
  const sheetName = "Sheet1"; // Please set the sheet name.
  const fromCell = "A11";
  const toCell = "A34";
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const image = sheet.getImages().filter(e => e.getAnchorCell().getA1Notation() == fromCell);
  if (image.length == 0) return;
  image[0].setAnchorCell(sheet.getRange(toCell));
}

Sample script 2:

About For example, I would need to move an image on A11 to A34., if your image is put into the cell "A11", and you want to move it to the cell "A34", how about the following sample script?

function sample2() {
  const sheetName = "Sheet1"; // Please set the sheet name.
  const fromCell = "A11";
  const toCell = "A34";
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  const srcRange = sheet.getRange(fromCell);
  srcRange.copyTo(sheet.getRange(toCell));
  srcRange.clearContent();
}

Note:

  • From your reply and provided sample Spreadsheet, I could understand that your image of I would need to move an image on A11 to A34. is put into a cell instead of over the cell. In this case, I think that my 2nd script can be used. When I tested your provided sample Spreadsheet using my proposed 2nd script, no error occurs. The image in the cell "A11" is moved to the cell "A34".
  • From your reply of The second sample script, when I attempt to run it, I get the message "TypeError: Cannot read property 'getRange' of null"., for example, as I mentioned Please set the sheet name., if the sheet name of your tested Spreadsheet is not "Sheet1", such error occurs. If my understanding is correct, please modify Sheet1 of const sheetName = "Sheet1"; to your actual sheet name and test it again.

References:

  • Related