简体   繁体   中英

Google Apps Script CopyPasteType.PASTE_VALUES keep returning blank values. Is this enum deprecated or something's wrong with my code?

I'm writing a simple code with the purpose of:

  1. Setup a formula on Column [x] referring to Column [n]
  2. Copy the formula (on the same column) to cover all the rows with data on Column [n]
  3. Copy back the result from Column[x] to Column [n] as value only using CopyPasteType.PASTE_VALUES

My code looks like this:

function Test() {
  
  var ss = SpreadsheetApp.getActive()
  var startingcell = ss.getActiveCell()
  ss.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate()
  var lastrow = ss.getActiveRange().getNumRows()

  // offset to create formula
  ss.getCurrentCell().offset(0, 1).activate()
  ss.getCurrentCell().setFormulaR1C1('IF(R[0]C1<>0,R[0]C1,12)')
    
  
  // set active range then copy down to cover all row with data on initial column
  ss.getCurrentCell().offset(0, 0, lastrow).activate()
  ss.getCurrentCell().copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false)

  // copy paste value back to initial column
  ss.getCurrentCell().offset(0, -1, lastrow).activate();
  ss.getCurrentCell().offset(0, 1, lastrow).copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
 

}

Let's just say my data is on Column A, with the offset I produce the formula on Column B, then tried to Copy-Paste Value back the result to Column A

But instead of the values, what I got in Column A is empty cells (the initial values got deleted)

Anything wrong with my code or the enum is deprecated?

Funny thing is when I use the enum CopyPasteType.PASTE_NORMAL instead, I get the expected result where the content, in this case formula, is copied to Column A (of course the pasted formula wont run due to circular dependency)

In your script, how about using SpreadsheetApp.flush() as follows?

From:

// copy paste value back to initial column
ss.getCurrentCell().offset(0, -1, lastrow).activate();
ss.getCurrentCell().offset(0, 1, lastrow).copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

To:

// copy paste value back to initial column
SpreadsheetApp.flush(); // Added
ss.getCurrentCell().offset(0, -1, lastrow).activate();
ss.getCurrentCell().offset(0, 1, lastrow).copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  • From your situation of Funny thing is when I use the enum CopyPasteType.PASTE_NORMAL instead, I get the expected result where the content, in this case formula, is copied to Column A (of course the pasted formula wont run due to circular dependency) , I thought that SpreadsheetApp.flush() might be required to be used.

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