2014-07-18 40 views
1

示例單元格值爲「https://www.google.com/url?q=http://en.wikipedia.org/wiki/Boricua_College&sa=U&ei=mTTIU4fhEs_jsASNy4G4Dg&ved=0CBQQFjAAOAE&usg=AFQjCNEnOjYOji3mdwT3_FS0L1_NCFk7GQ」(儘管在電子表格中所有URL都以純文本格式),理想情況下我想用「http://en.wikipedia.org/wiki/Boricua_College」取代。當我在腳本編輯器中運行該程序時,電子表格會提示我輸入一個列字母,因爲它應該是這樣,但之後什麼都不做。它不會刪除#N/A值,也不會修剪任何網址。Google Spreadsheet - 在使用ImportXML()將Google搜索結果導入到單元格後,將單元格值,Google重定向URL轉換爲實際URL

function trimLink() { 
    var s = SpreadsheetApp.getActiveSheet(); 
    // set column to trim 
    var c = Browser.inputBox("Please", "Type in the column name (e.g.: A, B, etc.)", Browser.Buttons.OK_CANCEL); 
    if (c != "cancel") { 
    c = c.charCodeAt(0) - 64; 
    } 
    var r, v; 
    // set length to cut from beginning of string 
    var begLink = "https://www.google.com/url?q="; 
    var begLen = begLink.length; 
    var endLen; 
    try 
    { 
    if(c != "cancel") 
    { 
     r = 2; // first row is row two 
     while (r <= s.getLastRow()) { 
     v = s.getRange(r, c).getValue(); 
     // #N/A is the result of failed importXML 
     if (v != "" && v != "#N/A") { 
      // initialize variable to hold value of string 
      var link = String(v); 
      for (var k = 0; k < link.length; k++) { 
      // link must be trimmed at char & (&sa) 
      if (link.charAt(k) == '&') { 
       // set length to cut from end of string 
       endLen = k; 
       break; 
      } 
      } 
      v = link.substr(begLen, endLen - 1); 
     } 
     else { 
     v = ""; 
     } 
     r++; 
     } 
    } 
    } catch (e) {Browser.msgBox("Error Alert:", e.message, Browser.Buttons.OK);} 
} 

回答

0

主要問題是我沒有給單元賦值它的新值。最重要的是,我使用的是substr而不是substring,但直到我的程序成功地將單元格值更改爲其他值之後才意識到。

function trimLink() { 
    var s = SpreadsheetApp.getActiveSheet(); 
    // input relevant column 
    var c = Browser.inputBox("Please", "Type in the column name (e.g.: A, B, etc.)", Browser.Buttons.OK_CANCEL); 
    // represent letter input as column number 
    if (c != "cancel") { 
    c = c.charCodeAt(0) - 64; 
    } 
    var r, link; 
    // length to cut from beginning of string 
    var begLink = "https://www.google.com/url?q="; 
    var begLen = begLink.length; 
    var endLen = 0; 
    try 
    { 
    if(c != "cancel") 
    { 
     r = 2; // first row is row two 
     while (r <= s.getLastRow()) { 
     link = String(s.getRange(r, c).getValue()); 
     // #N/A is the result of failed importXML 
     if (link != "" && link != "#N/A") { 
      while (link.charAt(endLen) != '&') { 
      endLen++ 
      } 
      s.getRange(r,c).setValue(link.substring(begLen, endLen)); 
     } 
     else { 
      // clear cell if importxml (outside of this program) had failed to extract a g search url 
      s.getRange(r, c).setValue(""); 
     } 
     r++; 
     } 
    } 
    } catch (e) {Browser.msgBox("Error Alert:", e.message, Browser.Buttons.OK);} 
} 
相關問題