google-sheetsgoogle-apps-script

Google script to dynamically addressing a cell in google sheet


I create code as follow

for (var i = 1; i <= numOfCopy-1; i++){
          
          var DestCell = "C" & String(22 + (i * 4) );
          SpreadsheetApp.getUi().alert(DestCell);
          spreadsheet.getRange(DestCell).activate();
          spreadsheet.getRange('C22:E25').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
        
        }

To allow copy and paste a range for number of times that defined by user.

I expect the line var DestCell = "C" & String(22 + (i * 4) );

Will construct dynamic destination cell address. But it returns 0.

So that line spreadsheet.getRange(DestCell).activate(); gives error message, "Range not found"


Solution

  • String concatenation in JavaScript

    The issue within your code is that you are using & to combine strings, which is not a valid operator in JavaScript. Instead, you should use the + operator for string concatenation.

    Try this modified code:

    function myFunction() {
      var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
      var numOfCopy = 3; // ensure that this is an integer not as string (e.g. "3")
    
      for (var i = 1; i <= numOfCopy - 1; i++) {
        var DestCell = "C" + String(22 + (i * 4));
        Logger.log("Destination cell:" + DestCell);
        Logger.log(typeof DestCell);
        SpreadsheetApp.getUi().alert(DestCell); 
        spreadsheet.getRange(DestCell).activate(); 
        spreadsheet.getRange('C22:E25').copyTo(spreadsheet.getActiveRange(),
        SpreadsheetApp.CopyPasteType.PASTE_NORMAL,false
        ); 
      }
    }
    

    Sample Output:

    Sample1 Data1 Test1
    Sample2 Data2 Test2
    Sample3 Data3 Test3
    Sample4 Data4 Test4
    Sample1 Data1 Test1
    Sample2 Data2 Test2
    Sample3 Data3 Test3
    Sample4 Data4 Test4
    Sample1 Data1 Test1
    Sample2 Data2 Test2
    Sample3 Data3 Test3
    Sample4 Data4 Test4

    Reference: