0

I am trying to write a script to copy contents of cell (in a2) and paste this into the 1st empty (of text and formulas) cell on row 2.

Ones that I have tried to copy and use are to do similar but finding the next row in a column. I have also tried functions that should do this but they find the first cell in the row that contains a formula, I need it to be empty of text and formulas.

Can anyone help please?

Thanks

Ben C
  • 49
  • 6

2 Answers2

0

Copy A2 to end of row2 + 1 col

function copy() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Your Sheet Name");
  const v = sh.getRange("A2").getValue();
  sh.getRange(2, getRowWidth(2,sh,ss) + 1).setValue(v);
}

function getRowWidth(row, sh, ss) {
  var ss = ss || SpreadsheetApp.getActive();
  var sh = sh || ss.getActiveSheet();
  var row = row || sh.getActiveCell().getRow();
  var rcA = [];
  if(sh.getLastColumn()){rcA = sh.getRange(row, 1, 1, sh.getLastColumn()).getValues().flat().reverse();}
  let s = 0;
  for (let i = 0; i < rcA.length; i++) {
    if (rcA[i].toString().length == 0) {
      s++;
    } else {
      break;
    }
  }
  return rcA.length - s;
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
0
  • Use getValues to check whether there's some text in your cells.
  • Use getFormulas to check whether there are formulas in your cells.

Code sample:

function copyToFirstEmptyCell() {
  const rowIndex = 2;
  const sheet = SpreadsheetApp.getActiveSheet();
  const row = sheet.getRange(`${rowIndex}:${rowIndex}`);
  const values = row.getValues()[0];
  const a2Value = values.shift();
  const formulas = row.getFormulas()[0];
  const columnIndex = values.findIndex((value,i) => !value.length && !formulas[i+1].length) + 2;
  const foundCell = sheet.getRange(rowIndex, columnIndex);
  foundCell.setValue(a2Value);
  foundCell.activate();
}
Iamblichus
  • 18,540
  • 2
  • 11
  • 27
  • Many thanks to both of you form coming back with these solutions. copyToFirstEmptyCell worked a treat but the other one did not for some reason (will look into that further). Is it possible to make the "found" cell active after pasting in the text please? Thanks again – Ben C Jun 28 '22 at 16:57
  • 1
    @BenC I updated my script to activate the found cell: `foundCell.activate()`. I hope this is helpful to you. – Iamblichus Jun 29 '22 at 07:02
  • Many Thanks for that lamblichus, very good of you. – Ben C Jun 29 '22 at 13:13