简体   繁体   中英

Modify Code - lookup 2nd Last letter of data in a cell. Google Apps Script / Google Sheets

If data in a cell in Column B has a A or B as the 2nd last letter ONLY - (example of Location G08B1) - Copy that row to another sheet.

I use a modified version of copy row if certain cell has certain word, so not sure how to modify this to what I need.

  function CopyAorBLocation() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
  if(s.getName() == "FORKLIFT" && r.getColumn() == 7 && r.getValue() == copy AorB if 2nd last letter - if not ignore) 
 {
  var row = r.getRow();
  var numColumns = s.getLastColumn();
  var targetSS = 
  SpreadsheetApp.openById("");
  s = SpreadsheetApp.getActiveSheet();
  var tempSheet = s.copyTo(targetSS);
  var targetSheet = targetSS.getSheetByName("ONLINERELOCATION");
  var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
  tempSheet.getRange(row, 4, 1, 3).copyTo(target);

Hoping this is not too complicated to achieve.

Thanks in Advance

  • The input and output sample values are the column "B" and the columns "C:D", respectively.
  • You want to put the values of column "B" to the column "C" and "D" by the 2nd last character of each value of the column "B".
    • Put the values ###A# and ###B# to the column "C".
    • Put the values ###C# and ###D# to the column "D".
  • You want to achieve this using Google Apps Script.

I could understand like above. If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

In this answer, the 2nd last character of each value is retrieved by substring() .

Sample script:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");
  var srcValues = sheet.getRange(2, 2, sheet.getLastRow() - 1, 1).getValues();
  var dstValues = srcValues.map(function([b]) {
    var len = b.length;
    var s = b.substring(len - 2, len - 1).toUpperCase();
    return (s == "A" || s == "B") ? [b, ""] : (s == "C" || s == "D") ? ["", b] : ["", ""];
  });
  sheet.getRange(2, 3, dstValues.length, 2).setValues(dstValues);
}
  • In this sample script, Sheet1 is used.

Note:

  • This sample script is for your shared Spreadsheet. If the format is different from your shared Spreadsheet, the script might not work. Please be careful this.

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM