Для начала, вот мой лист, который дает два примера наборов данных и желаемых результатов для каждого.
https://docs.google.com/spreadsheets/d/1MPppt2yztfPtz2iSssSfIuBoYccxQ4gs7PZdygdz1Z8/edit?usp=sharing
Вот код, который у меня есть сейчас,Это не в рабочем состоянии, но, кажется, близко.Буду редактировать, как я экспериментирую с разными решениями.
// on open, add menu and bttons to test functions
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Analyze and flip data selection', functionName: 'flipSelection'},
{name: 'Check for first empty cell', functionName: 'firstEmptyCell'}
];
spreadsheet.addMenu('Scripts', menuItems);
}
// put data from a column into a row. on a blank line, write to new row
function flipSelection() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var testSheet = ss.getSheetByName("test");
var sheet = ss.getSheetByName("main");
var range = sheet.getActiveRange();
var numRows = range.getNumRows();
var numCols = range.getNumColumns();
var data = [];
// check active range(current selection) for values and store them in data array
for (var i = 1; i < numRows; i++){
for (var j = 1; j < numCols; j++) {
var currentValue = range.getCell(i,j).getValue();
data.push(currentValue);
}
}
// log array to verify accurate data
for (var k = 0; k < data.length; k++){
ss.toast(data[k].toString());
Logger.log(data[k].toString());
}
// for each string in data array, write to next cell. if the string is blank, go to next row and write to next cell (recursion??)
for (var n = 0; n < data.length; n++) {
// Do we have data? If not, move on
if (data[n] == "") {
//target next empty row (need help here!)
continue;
}
const colA = testSheet.getRange('A:A').getValues().join().split(",");
const rowIndex = colA.indexOf('');
const colIndex = firstEmptyCell(rowIndex); // assuming firstEmptyCell works correctly
const targetCell = testSheet.getRange(rowIndex, colIndex);
targetCell.setValue(data[n]);
}
}
// a way to find first empty cell
function firstEmptyCell (emptyRow) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var testSheet = ss.getSheetByName("test");
var range = testSheet.getRange(emptyRow, 1, 1, testSheet.getMaxColumns());
var vals = range.getValues();
// Get the index of the first empty cell from the waarden array of values
var emptyCell = vals[0].indexOf("");
// log the index of empty cell
ss.toast("The index of the first empty cell is: " + emptyCell.toString());
Logger.log("The index of the first empty cell is: %s", emptyCell);
return emptyCell;
}