2

为什么我的脚本不起作用?它不搜索数据。消息显示已完成,但床单看起来没有变化。我可以帮助谁?

function SearchReplaceInFormula() { //begin work

 var pattern = Browser.inputBox("Enter the search string:"); //text on label
 var replacement = Browser.inputBox("Enter the replacement string:"); //text on label
  if (pattern == "" && replacement == "") // empty 
 {
 Browser.msgBox("Nothing to search and or replace"); 
 return;
  }
//
  var formula = SpreadsheetApp.getActiveRange().getValues(); //get a data all range
  var range = SpreadsheetApp.getActiveRange(); //get range
  var crows = range.getNumRows(); //last rows
  var ccols = range.getNumColumns(); //last columns
  var row = 0; //
  for (row = 1; row <= crows; row++)//
  {
  for (col=1; col <= ccols; col++) //
  {
 var cell = range.getCell(row, col);
 var formula = cell.getValues(); //may be getValue
 var updated = formula; //update
 while(-1 != updated.indexOf(pattern)) //what -1
 {
   updated = updated.replace(pattern, replacement); //replace before update
 }
 if (formula != updated)
 {
   cell.setFormula(updated) //set vales?
 }
  }
 }   
  Browser.msgBox("Done replacing " + pattern + " with " + replacement); //shows always
  }
4

1 回答 1

0

我重新编写了您的代码并添加了一个菜单选项,以便可以轻松访问它。

更新:2013年 9 月 1 日添加了一段额外的代码来检查是否有更改(数组比较)。
还包括电子表格的一个工作示例:在谷歌电子表格中搜索和替换数据

function onOpen() {
  // get active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // create menu
  var menu = [{name: "Searh/Replace", functionName: "SearchReplaceInFormula"}];

  // add to menu
  ss.addMenu("Extra's", menu);  
}

function SearchReplaceInFormula() {
  // set parameters
  var pattern = Browser.inputBox("Enter search string:"); 
  var replacement = Browser.inputBox("Enter replacement string:"); 

  // inform user if nothing was entered
  if(pattern == "" && replacement == "") {
    Browser.msgBox("Nothing to search and or replace");
    return;
  }

  // get ranges and data
  var dataRange = SpreadsheetApp.getActiveRange().getValues();
  var copyRange = dataRange;
  var range = SpreadsheetApp.getActiveRange(); 
  var ccols = dataRange[0].length, crows = dataRange.length; 

  // itterate through data
  for (var i=0; i<crows; i++) { 
    for (var j=0; j<ccols; j++) {      
      if(copyRange[i][j].indexOf(pattern) != -1) {
        copyRange[i][j] = copyRange[i][j].replace(pattern, replacement);
      }
    }
  }

  // set changed values
  range.setValues(dataRange);

  // check if array's are equal
  var equal = arraysEqual(copyRange, dataRange);

  // inform user what happend
  if(equal == true) {
    Browser.msgBox("No matches found...");
  } else {
    Browser.msgBox("Done replacing " + pattern + " with " + replacement); 
  }
}

function arraysEqual(arr1, arr2) {
  if(arr1.length !== arr2.length)
    return false;

  for(var i = arr1.length; i--;) {
    if(arr1[i] !== arr2[i])
      return false;
  }
  return true;
}
于 2013-01-08T20:19:40.943 回答