自动分隔和分隔Google表格中的字符串

时间:2019-03-23 15:14:04

标签: javascript google-sheets google-sheets-formula

Google表格具有一个选项,可以在顶部菜单中选择该选项,以在指定字符时将文本分为几列。可以使用逗号或其他字符。

我正在寻找可以针对给定列自动执行此过程的脚本。有许多脚本可以执行此操作,但是我无法使用它们来完成任务。

我正在使用Android上的应用程序,该应用程序允许我扫描二维码并将信息字符串发送到Google表格。

信息样本将显示为:464839 | 362 | 2840 | 927 | 72 | 617

当信息发送到工作表时,我需要将此信息分成单独的列。该过程应该是自动的。

我有一段搜索代码,但是对我来说不起作用。

var range = SpreadsheetApp.getActiveRange();
var cell = range.getCell(1, 1); // Gets the cell A1 
var cellValue = cell.getValue(); // Gets the value of the cell A1

var cellArray = cellValue.split("|"); // Splits the cell value by ',' and  stores it in array.

//Iterate through the array
for(var i = 0; i < cellArray.length; i++){
    Logger.log(cellArray[i]);
}

我不太懂代码,请帮忙。

1 个答案:

答案 0 :(得分:0)

下面将是您放置在installable trigger上的代码,该代码每隔固定间隔运行一次,并遍历A列中的每一行的值,并尝试使用管道符号拆分该值,然后使用replace进行写入沿该行的列拆分的值。如果过去已经这样做,则该函数尝试拆分值时将出错,因为不存在管道符号,但是try / catch会捕获该错误并允许该函数继续循环。

    function myFunction() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("NameOFSheet"); //Change "NameOFSheet to the actual name of the sheet.
      var col1Values = sheet.getSheetValues(1, 1, sheet.getLastRow(), 1) //Gets 2d (2 dimensional) array of the Values in Column 1 (getSheetValues(startRow, startColumn, numRows, numColumns)_
      var splitVals = []; //Instantiate an empty 1d array variable
      //Iterate through the 2d array and set the values
      for(var i = 0; i < col1Values.length; i++){
        try{
          splitVals = col1Values[i][0].split("|"); //Creates a 1d array of values split at every occurrence of the pipe symbol ("|").
          //If there is no pipe symbol (which would be the case if this operation has already happened then the array will be blank because .split will throw an error which will get "caught" in the try catch and the row will be skipped

          //Iterate over the splitVals array and set the values of the columns along the row (i+1) that you are in.
          for(var col = 0; col < splitVals.length; col++){
            sheet.getRange(i+1, col+1).setValue(splitVals[col])
          }
        }catch(e){}

      }
    }

我评论了代码以进行解释。我建议阅读2 dimensional arrays,以帮助您更好地理解它们以及上面的代码。

相关问题