Search code examples
google-apps-scriptgoogle-sheets

Google AppScript rowIndex variable is not passed to function


I have "source" google sheet and want to move some selected data to "target" google sheet. function is move data.

I'm searching data in first column of "source" google sheet by providing "keyword". Then, row data of that "keyword" available will displayed. Then, move button clicked to move that data to Target sheet.

see following codes.

code.gs


function searchData(keyword) {
  var sourceSheet = SpreadsheetApp.openById('SOURCE_SHEETID').getSheetByName('dataSource');
  var data = sourceSheet.getDataRange().getValues();
  var matchingRows = [];

  for (var i = 0; i < data.length; i++) {
    if (data[i][0] === keyword) { // Assuming keyword is in the first column
      matchingRows.push(data[i]);
    }
  }

  return matchingRows;
}

function moveData(rowIndex) {
 if (rowIndex >= 0 && rowIndex < sourceSheet.getLastRow()) { 
  console.log('Moving data from rowIndex:', rowIndex);
  var sourceSpreadsheetId = 'SOURCE_SHEETID';
  var targetSpreadsheetId = 'TARGET_SHEETID';
  var sourceSheetName = 'dataSource';
  var targetSheetName = 'dataTarget';

  // Open the source and target spreadsheets
  var sourceSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetId);
  var targetSpreadsheet = SpreadsheetApp.openById(targetSpreadsheetId);

  // Get the source and target sheets
  var sourceSheet = sourceSpreadsheet.getSheetByName(sourceSheetName);
  var targetSheet = targetSpreadsheet.getSheetByName(targetSheetName);

  // Get the data to move based on rowIndex
  var dataToMove = sourceSheet.getRange(rowIndex + 1, 1, 1, sourceSheet.getLastColumn()).getValues();

  // Append the data to the target sheet
  targetSheet.appendRow(dataToMove[0]);

  // Delete the source row
  sourceSheet.deleteRow(rowIndex + 1); // Adjust the row number as needed
}
else {
    console.log('Invalid rowIndex:', rowIndex);
  }
}

index.html

    function searchAndMoveData() {
      var keyword = document.getElementById('keyword').value;
      google.script.run.withSuccessHandler(displaySearchResults).searchData(keyword);
    }

    function displaySearchResults(data) {
      var searchResultsDiv = document.getElementById('searchResults');
      searchResultsDiv.innerHTML = ''; // Clear previous results

      if (data.length === 0) {
        searchResultsDiv.innerHTML = 'No matching data found.';
      } else {
        var table = '<table>';
        for (var i = 0; i < data.length; i++) {
          table += '<tr><td>' + data[i].join('</td><td>') + '</td><td><input type="button" value="Move" onclick="confirmMove(' + i + ')"></td></tr>';
        }  
        table += '</table>';
        searchResultsDiv.innerHTML = table;
      }
    }

    function confirmMove(rowIndex) {
      if (confirm('Are you sure you want to move this data?')) {
        google.script.run.moveData(rowIndex);
      }
    }

Issue was when I click move button, SELECTED ROW DATA not moving to Target sheet. First row of Source Sheet moving to Target sheet.

I understood that the error is with the "rowIndex" I tried to find the error using console log. result: Invalid rowIndex: undefined

I think the issue is rowIndex variable is not being passed correctly to the moveData function, and it's undefined when the function is called. Need help to resolve the issue here.

Here I added the sample sheets. Source sheet here and Target sheet here


Solution

  • Modification points:

    • In your script, the row index is retrieved from the row values of matchingRows as confirmMove(' + i + '). In this case, when all rows are retrieved, this can be used. But, in your situation, I'm worried that the correct row index is not used because the row values are retrieved from not all rows. I think that this is the 1st issue.
    • In the function moveData(rowIndex), sourceSheet of if (rowIndex >= 0 && rowIndex < sourceSheet.getLastRow()) { is not declared. In your script, sourceSheet is declared in the if statement. I think that this is the 2nd issue.

    When these issues are modified, how about the following modification?

    Google Apps Script side:

    Please replace SOURCE_SHEETID and TARGET_SHEETID with your values.

    function searchData(keyword) {
      var sourceSheet = SpreadsheetApp.openById('SOURCE_SHEETID').getSheetByName('dataSource');
      var data = sourceSheet.getDataRange().getValues();
      var matchingRows = [];
      for (var i = 0; i < data.length; i++) {
        if (data[i][0] === keyword) {
          matchingRows.push({ data: data[i], rowIndex: i });
        }
      }
      return matchingRows;
    }
    
    function moveData(rowIndex) {
      var sourceSpreadsheetId = 'SOURCE_SHEETID';
      var sourceSheetName = 'dataSource';
      var sourceSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetId);
      var sourceSheet = sourceSpreadsheet.getSheetByName(sourceSheetName);
      if (rowIndex >= 0 && rowIndex < sourceSheet.getLastRow()) {
        console.log('Moving data from rowIndex:', rowIndex);
        var targetSpreadsheetId = 'TARGET_SHEETID';
        var targetSheetName = 'dataTarget';
        var targetSpreadsheet = SpreadsheetApp.openById(targetSpreadsheetId);
        var targetSheet = targetSpreadsheet.getSheetByName(targetSheetName);
        var dataToMove = sourceSheet.getRange(rowIndex + 1, 1, 1, sourceSheet.getLastColumn()).getValues();
        targetSheet.appendRow(dataToMove[0]);
        sourceSheet.deleteRow(rowIndex + 1);
      } else {
        console.log('Invalid rowIndex:', rowIndex);
      }
    }
    

    Javascript side:

    Although I'm not sure about your function confirm('Are you sure you want to move this data?'). So, in this modification, it is supposed that this function works fine. Please be careful about this.

    function searchAndMoveData() {
      var keyword = document.getElementById('keyword').value;
      google.script.run.withSuccessHandler(displaySearchResults).searchData(keyword);
    }
    
    function displaySearchResults(data) {
      var searchResultsDiv = document.getElementById('searchResults');
      searchResultsDiv.innerHTML = '';
      if (data.length === 0) {
        searchResultsDiv.innerHTML = 'No matching data found.';
      } else {
        var table = '<table>';
        for (var i = 0; i < data.length; i++) {
          table += '<tr><td>' + data[i].data.join('</td><td>') + '</td><td><input type="button" value="Move" onclick="confirmMove(' + data[i].rowIndex + ')"></td></tr>';
        }
        table += '</table>';
        searchResultsDiv.innerHTML = table;
      }
    }
    
    function confirmMove(rowIndex) {
      if (confirm('Are you sure you want to move this data?')) {
        google.script.run.moveData(rowIndex);
      }
    }
    

    Note:

    • Unfortunately, I cannot know your actual situation. When you use your script as the Web Apps, please reflect the latest script to the Web Apps. Please be careful about this.

    • When I tested this modified script using a simple Spreadsheet, I confirmed that the script worked. But, if the script is not correctly run with your actual Spreadsheet, can you provide a sample Spreadsheet? By this, I would like to confirm it.