如何获取一行并将该行和文本字符串合并为一个新行

How to Get a row and combine the row and a text string into one new row

本文关键字:合并 字符串 文本 一个 新行 何获取 获取 一行      更新时间:2023-09-26

我试图从一个工作表中获得一个范围,并添加范围加上一个字符串,以便在新工作表中创建一个新行。新工作表中的新行应该有字符串,然后是行。我想也许我可以用数组来做这个,但它不起作用。

      //tradeName is the name of the source file. The code is super long so i did not include it in this snippet.      
      var fileList = DriveApp.getFilesByName(tradeName); 
      var fileId = fileList.next().getId();
      var sheetCurrent = SpreadsheetApp.getActiveSheet();
      var source = SpreadsheetApp.openById(fileId);
      var source_range = source.getRange("A20:AE20");
      sheetCurrent.appendRow([tradeName,A20:AE20]);

不能将范围和字符串值混合使用。正如您所注意到的,appendRow中的参数必须是一个数组,因此正确的方法是在添加新行之前将字符串添加到数组中。另一方面,当您检索行值时,您将获得数组的数组(2D数组),因此我们必须只获取内部数组并使用unshift方法在其他元素之前添加元素。

代码可以像这样:

function myFunction() {
  var string = " ccccxxxx";
  var sheetCurrent = SpreadsheetApp.getActiveSheet();
  var source = SpreadsheetApp.openById(fileId);
  var source_range = source.getRange("A20:AE20");
  var source_rangeValue = source_range.getValues(); // 2D ARRAY   
  source_rangeValue[0].unshift(string);//add the string to the inner array
  sheetCurrent.appendRow(source_rangeValue[0]);
}