Ask Your Question
4

Using app script, how can I move each cell to a new sheet when there is a match with another sheet's cell?

asked 2023-05-03 11:32:46 +0000

plato gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-03 11:38:02 +0000

lalupa gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-03 11:32:46 +0000

Seen: 13 times

Last updated: May 03 '23