I’m looking for an efficient method to copy data from one cell and paste it into another cell within Google Sheets using Apps Script. My spreadsheet layout is fixed, so I don’t need to handle dynamic rows or columns.
I attempted using getCell() function similar to how getLastColumn() works, but it appears getCell() is not a recognized function in the API.
Here’s my current script:
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = event.source.getActiveSheet();
var range = event.source.getActiveRange();
if(sheet.getName() == "Data" && range.getColumn() == 10 && range.getValue() == "EXECUTE") {
var currentRow = range.getRow();
var totalColumns = sheet.getLastColumn();
var destinationSheet = spreadsheet.getSheetByName("Data");
spreadsheet.getSheets()[0].getRange("B25:B25").copyTo(spreadsheet.getSheets()[1].getRange("C5:C5"), {contentsOnly:true});
}
What’s the proper way to move cell contents programmatically?
Indeed, using getRange().setValue() is effective. However, when dealing with dates or currency, consider using getDisplayValue() to preserve the formatting. If you anticipate needing to expand your script, think about employing batch operations with getValues() and setValues() to handle multiple cells efficiently while maintaining consistency. Additionally, since you’re using “EXECUTE” as a trigger, remember to clear that cell after execution. This prevents unintended re-runs if nearby cells are edited; simply use range.setValue("") at the end of your condition block.
just grab the cell content with sheet.getRange('B25').getValue() and drop it where you need it using destinationSheet.getRange('C5').setValue(value). way cleaner than copyTo and won’t give you weird bugs. also, you’ve already got the destination sheet variable - use that instead of getSheets()[1].
Your copyTo() approach works fine, but there’s an easier way. Use getValue() and setValue() instead - they’re usually faster for single cells.
Replace your copyTo() line with this:
var sourceValue = spreadsheet.getSheets()[0].getRange("B25").getValue();
spreadsheet.getSheets()[1].getRange("C5").setValue(sourceValue);
This gives you better control and avoids formatting issues. I use it when I need to tweak data before pasting or when formulas might break during copy operations. You’ll notice the speed difference if you’re transferring multiple cells in one script.