我想在空格()上拆分文本,然后将它们粘贴到工作表2的不同列中。我还想删除" Hello"从文本中拆分文本之前/之后的文本。我成功使用
getValues.split(" ")
,但在目标范围(在sheet2中)粘贴新值时未成功。
输入:
输出:
我目前的代码:
function myFunction() {
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var lr = ss1.getLastRow();
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
for (var i = 2; i <= lr; i++) {
var title = ss1.getRange(i, 1).getValue().split(" ");
ss2.getRange(i, 2).setValue(title[0]);
}
}
任何提供的帮助都将受到高度赞赏。
答案 0 :(得分:0)
尝试以下代码。它并不包括你的标题,因为我不确定你究竟想做什么。它确实需要剥离&#34;你好&#34;你的字符串中的单词,并将每个单词放在其单独的列中。代码中的注释解释了我为什么要做的事情。
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Selects the spreadsheet
var ss1 = ss.getSheetByName("Sheet1"); // Selects sheet 1
var data = ss1.getDataRange().getValues(); // Gets all values in the sheet
var ss2 = ss.getSheetByName("Sheet2"); // Selects sheet 2
for (var i=0;i<data.length;i++) {
var words = data[i][0].split(" "); // Create an array of all words
if (words[0].toLowerCase().indexOf('hello') > -1) { // True when the first word of the sentence contains hello
words.splice(0, 1); // Remove 1 item, starting from position 0 - remove the word that contains hello
}
// Get range on Sheet2, same row number as sheet 1, starting from column 1, select 1 row, and the same amount of columns as the amount of words
// Because we set values for a range that can span multiple rows, we put the words array in another array (where the words array represents one row)
// We add 1 to variable i as the index of an array starts at 0 instead of 1.
ss2.getRange(i+1, 1, 1, words.length).setValues([words])
}
}