Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here's a sample code that you can use to move cells to a new sheet when there is a match with another sheet's cell in Google Sheets using Apps Script:

function moveCellsToNewSheet() {
  // Set the source and destination sheets
  var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var destinationSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");

  // Get the data range of the source sheet
  var sourceRange = sourceSheet.getDataRange();
  var sourceValues = sourceRange.getValues();

  // Loop through each cell in the data range of the source sheet
  for (var i = 0; i < sourceValues.length; i++) {
    for (var j = 0; j < sourceValues[i].length; j++) {
      var value = sourceValues[i][j];

      // Check if the cell value matches a cell value in the destination sheet
      var destinationRange = destinationSheet.getDataRange();
      var destinationValues = destinationRange.getValues();
      for (var k = 0; k < destinationValues.length; k++) {
        for (var l = 0; l < destinationValues[k].length; l++) {
          var destinationValue = destinationValues[k][l];

          if (value == destinationValue) {
            // If there's a match, move the current cell to the destination sheet
            var rangeToMove = sourceSheet.getRange(i+1, j+1);
            rangeToMove.moveTo(destinationSheet.getRange(k+1, l+1));
          }
        }
      }
    }
  }
}

In this code, we first set the source sheet and the destination sheet. We then get the data range of the source sheet and loop through every cell in the data range. For each cell, we check if it matches any cell value in the destination sheet. If there is a match, we use the moveTo() method to move the cell to the corresponding cell location in the destination sheet.

Note that this code only works for single-cell matches, so any cells with multiple matches will not be moved. You can modify the code to handle multiple matches as needed.