EtzBetz
EtzBetz

Reputation: 25

"for" loop for Google Spreadsheet values not looping

I'm currently writing a statistic spreadsheet script for my guild, which reads out the class of one person and counts it on the statistic sheet.

For some reason the for loops aren't working. When I execute the script, it does nothing. Everything before the for loop seems to work. I have used the debugger, and set a debug point from the point of the for loop and the window is opening and closing after like 1 second.

This is my code as of now:

function addToStatistik() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();          

  var source_sheet = spreadsheet.getSheetByName("Raid Montag");       
  var source_range_names = source_sheet.getRange("C4:C13");
  var source_range_setup_boss1 = source_sheet.getRange("M4:M13");

  var target_sheet = spreadsheet.getSheetByName("Statistik");       
  var target_range_names = target_sheet.getRange("A4:A31");
  var target_range_boss1 = target_sheet.getRange("K4:S31");


  target_sheet.getRange(2,1).setValue("Debug1"); //testing stuff
  for (var i=0; i < source_range_names.length; i++) {
    for (var j=0; j < target_range_names.length; j++) {
      if (source_range_names[i][0] == target_range_names[j][0]) {
        if (source_range_setup_boss1[i][0].indexOf("War") > -1) {
          target_sheet.getRange(9,5).setValue("TEST");
        }
      }
    }
  }
}

Someone can find any errors in there? I can't find anything and google also isnt helping me.

Upvotes: 0

Views: 206

Answers (2)

user3075569
user3075569

Reputation:

Before you iterate you need to get the values of the range, to achieve this you need to use the method getValues() or getDisplayValues():

function leFunction() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();          
  var source_sheet = spreadsheet.getSheetByName("Raid Montag"); 
  var source_range_names = source_sheet.getRange("A1:C13");
  var values_range_names = source_range_names.getDisplayValues();

  Logger.log(values_range_names);

  for (var i=0; i < values_range_names.length; i++) {
    // Do Something
  }

}

Upvotes: 0

Alan Wells
Alan Wells

Reputation: 31300

You are getting the range, but not the values. This line:

var source_range_names = source_sheet.getRange("C4:C13");

gets a range, but not any values.

Should be:

var source_range_names = source_sheet.getRange("C4:C13").getValues();

The outer loop never loops. There is no length of a range.

for (var i=0; i < source_range_names.length; i++) {

You don't need to change the above line, but currently the variable source_range_names is a range, and not a 2D array of values.

Upvotes: 1

Related Questions