Павел
Павел

Reputation: 3

Can't write data from array to selected range

I'm a newbie at Google Apps Script and trying to make a simple script: it should multiply numbers in selected range by three:

function myfunction(){
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var dataArray = sheet.getActiveRange().getValues(); 
  for (i=0; i<dataArray.length; i++){
    dataArray[i] = dataArray[i] * 3;  
  };
  Logger.log (dataArray);
  sheet.getActiveRange().setValues([dataArray]);  
};

When I try to run this script, it gives me next error: "The number of rows in the array doesn't match the number of rows in the range." The problem is in this line:

sheet.getActiveRange().setValues([dataArray]); 

And I can't find and figure out, where is my mistake.

Upvotes: 0

Views: 43

Answers (1)

Cooper
Cooper

Reputation: 64082

Try this:

function myfunction(){
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var dataArray = sheet.getActiveRange().getValues(); 
  for (i=0; i<dataArray.length; i++){
    for(var j=0;j<dataArray[i].length;j++) {
      dataArray[i][j] = dataArray[i][j] * 3;  
    }
  }
  Logger.log (dataArray);
  sheet.getActiveRange().setValues(dataArray);  
}

Upvotes: 1

Related Questions