简体   繁体   中英

Script to copy and paste values to the first empty row in Google spreadsheets with zero in front of other numbers

So the code copies the content of Sheet1 B2:G2, B2 cell contains a code that often starts with multiple 0. Everything is okay in Sheet1, but once the script is executed and it is copied to Sheet2, the format changes to "Automatic and "000001" becomes just "1". I can't seem to find a away to make it instantyl format as plain text to keep the 0 in front. Also, the G cell contains €, so I don't want to set entire row as plain text, just the B column.

function moveValuesOnly() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getRange("Sheet1!B2:G2");
  var destSheet = ss.getSheetByName("Sheet2");
  destSheet.appendRow(source.getValues()[0]);
}

How about this modification? I think that there are several solutions for your situation. So please think of this as just one of them. In this modification, 2 lines were added to your script.

Modification point:

  • After appendRow() was run, the format of "Sheet1!B2:G2" is copied to the appended row. By this, "000001" is displayed.

Modified script:

function moveValuesOnly() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getRange("Sheet1!B2:G2");
  var destSheet = ss.getSheetByName("Sheet2");
  destSheet.appendRow(source.getValues()[0]);

  var destination = destSheet.getRange(destSheet.getLastRow(), 1); // Added
  source.copyTo(destination, SpreadsheetApp.CopyPasteType.PASTE_FORMAT) // Added
}

References:

If this was not the result you want, please tell me. I would like to modify it.

Thank you for this thread. I had a slightly different problem to solve but this gave me the inspiration to do it and thought I'd share. I wanted to update columns D:I with existing formulas from D7:I7 any time an edit was made to the spreadsheet. (In my case, that is most often just adding data to a new row A:C.) I only wanted it to fire if one particular Sheet was modified (not the other sheets).

This seems to do the trick nicely.

   function onEdit(e) {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sName = ss.getSheetName();
  Logger.log('Starting script...');

if (sName == 'Data'){
  Logger.log('We are editing the sheet name: "' + sName +'"'
            );
  var source = ss.getRange("Data!D7:I7");
  var destSheet = ss.getSheetByName("Data");
  var lastRow = destSheet.getLastRow();

  var destination = destSheet.getRange("D"+lastRow);
  destination.activate();
  source.copyTo(destination, SpreadsheetApp.CopyPasteType.PASTE_FORMULA)
  } else
  Logger.log('Nothing Done. Sheet name: "' + sName + '"' );
}

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