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

问题描述 投票:1回答:1

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

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

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

信息样本如下: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]);
}

我不是很懂代码,请帮忙。

javascript google-sheets google-sheets-formula
1个回答
0
投票

下面是一个代码,你放在一个定期运行的installable trigger上,迭代A列中每一行的值,然后尝试用管道符号拆分值,然后在列中写下这些拆分值。那一排。如果在过去已经完成此操作,则在尝试拆分值时函数将会出错,因为不存在管道符号,但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以帮助您更好地理解它们和上面的代码。

© www.soinside.com 2019 - 2024. All rights reserved.