0

I'm having truoble setting this piece of code.

I need to make a script that take these data from table (A25:C38) and save into a table (like single record). I never used a FOR cicle before and I'm pretty noob about java, could you please help me?

enter image description here

I tried to write somethings but of course it doesnt work. Could you help me?

function savecCost() {
//var data = fieldRangeCost.getValues()

for (var i = 26; i = 38; i++ ) {
  var fieldRangeCost = ss.getDataRange("A"&[i],"B"&[i])
   console.log(fieldRangeCost)
  const fieldvaluesCost = fieldRangeCost.map(f => formws.getRange(f).getValue())
  console.log(fieldvaluesCost) 
   }

}

I tried to make the code working but didnt work

  • 2
    Can you provide your expected value when your sample Spreadsheet is used? And, can I ask you about the detail of `but didnt work`? Because, in your script, `ss` and `formws` are not declared. So, I'm worried that you might have miscopied your script. How about this? First, I would like to correctly understand your question. By the way, `for (var i = 26; i = 38; i++ ) {` is not correct. In this case, [this thread](https://stackoverflow.com/q/9329446) might be useful. – Tanaike May 16 '23 at 07:51
  • `DO NOT post images of code, data, error messages, etc.—copy or type the text into the question.` [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – Tedinoz May 19 '23 at 05:05

1 Answers1

0

You have a multi-row range that has data fields and a checkbox on each row.

If the checkbox is checked, then you want to copy the data to another part of the spreadsheet.


function savecCost() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sourceSheet = ss.getSheetByName("Sheet1")
  var dataRange = sourceSheet.getRange(26,1,13,3)
  // Logger.log("DEBUG: the data range = "+dataRange.getA1Notation())
  var data = dataRange.getValues()
  

  // create a temprary array to save the speadsheet data
  var tempArray = new Array

  // loop through each row in the range
  for (var i = 0; i<data.length; i++ ) {
    // test if checkbox is ticked
    if (data[i][2] == true){
      // Logger.log("DEBUG: i="+i+ ", value = true")
      // checkbox is ticked
      // push row values onto the temporary Array
      tempArray.push([data[i][0],data[i][1]])
    }
    else{
      // Logger.log("DEBUG: i="+i+", value = false")
    }
  }

  // check if there is any data in the temporary Array
  // paste the contents of the temporary array into the spreadsheet
  if (tempArray.length >=1){
    var targetSheet =  ss.getSheetByName("Sheet2")
    var targetLR = targetSheet.getLastRow()
    var row = targetLR == 0 ? 1 : targetLR
    var targetRange = targetSheet.getRange(row,1,tempArray.length,2)
    // Logger.log("DEBUG: the target range = "+targetRange.getA1Notation())
    targetRange.setValues(tempArray)
  } 
}

Tedinoz
  • 5,911
  • 3
  • 25
  • 35