简体   繁体   中英

How to automatically copy/paste data using App Script in Google Sheets

I'm trying to write some code using App Scripts that will (via a daily trigger), copy/paste data from the cells F13:G13 to the first empty cell in column I. Here is my code:

    function TrackCurrentValues() 

      var spreadsheet = SpreadsheetApp.getActive();
      var sheet = spreadsheet.getSheets()[0];

      var lastRow = getLastRowInColumn(sheet, 'I:I');
      // Logger.log('I' + parseInt(lastRow + 1));

      var pasteRange = sheet.getRange('I' + parseInt(lastRow + 1) );
      pasteRange.activate();

      // now that we have the first empty cell in column I, paste the values we found from cells F13:G13
      spreadsheet.getRange('F13:G13').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

    };

function getLastRowInColumn(sheetObj, range) {
   return sheetObj.getRange(range)
            .getValues().filter (String).length + 1
}

When it runs, what happens is that the data is copied from the proper location, but it's always pasted to cell A1. Moreover, the number pasted appears is prefixed with the British pound sterling character (£).

What could be wrong? It (usually) works if I run it manually. The main thing is that it doesn't find the empty cell in I:I.

This code should do what you're looking for:

function TrackCurrentValues(){
      var sheet = SpreadsheetApp.getActive().getSheets()[0];
      var lastRow = getLastRowInColumn(sheet, 'I:I');
      var pasteRange = sheet.getRange(lastRow + 1,9,1,2);   
      var copyRange = sheet.getRange(13,6,1,2)
      pasteRange.setValues(copyRange.getValues())
    };

function getLastRowInColumn(sheetObj, range) {
   return sheetObj.getRange(range).getValues().filter(String).length
}

On your £ chracter question, that range is likely formatted to display that currency symbol. To update this, select the range, go to the toolbar and select Format > Number > Specify the format you would like

Additional Thoughts: i) You are adding one to lastRow variable twice (once in getLastRowInCOlumn function and again in pasteRange definition) ii) I would reocmmend not using "active ranges" to store a location, instead store that range in a variable iii) It seems your copy range was 2 columns wide but your pasteRange was only 1 column wide

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