Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-macros

In Google Sheets how can I write a script to move a drawing to a specific location on the sheet?


I have a Google sheet with a drawing i.e. shape. What script would move the shape to a designated location on the sheet?

Here is a link to an example where I'd like to click on the blue rectangle and have the script move the green rectangle to cover cell A1.

https://drive.google.com/open?id=1eFCwDiY90ZM5SIMa6C0rSdhG_oC-SWgsk8vAvjIR34s

This is my first script in Google and I can't find a way to select the drawing.


Solution

  • I believe your goal as follows.

    • You want to move the drawing, which is the green rectangle, to the cell "A1" when the blue rectangle is clicked.

    For this, how about this answer?

    Usage:

    1. Set function name.

    At first, please set the function name of myFunction to "the blue rectangle". By this, when the blue rectangle is clicked, myFunction is run.

    2. Sample script.

    function myFunction() {
      // 1. Retrieve sheet.
      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
    
      // 2. Retrieve "the green rectangle".
      const drawing = sheet.getDrawings().filter(e => e.getOnAction() != "myFunction")[0];
    
      // 3. Move "the green rectangle".
      drawing.setPosition(1, 1, 0, 0);
    }
    
    • In this case, the blue rectangle has the function name of myFunction. So using this, the green rectangle is retrieved.
    • In order to run this script, please click the blue rectangle that myFunction was set. By this, the green rectangle is moved to the cell "A1".

    Note:

    • This is a sample script. So please modify this for your actual situation.

    Reference: