Search code examples
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

  • Never mind, I reconstruct my code to be as follow:

    var rowAddr = spreadsheet.getRange('F21');
    
    for (var i = 1; i <= numOfCopy-1; i++){
    
              
    
              var DestCell = 22 + (i * 4);
              rowAddr.setValue(DestCell);
              DestCell=spreadsheet.getRange('F22').getValue()
              //SpreadsheetApp.getUi().alert(DestCell);
              spreadsheet.getRange(DestCell).activate();
              spreadsheet.getRange('C22:E25').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
            
            }
    

    So I use Cells in Google sheet to process the concatenation, put the next row address value to google sheet. And it works.