在电子表格中重新执行所有匹配的功能

时间:2017-03-17 19:54:49

标签: google-apps-script

我有一个非常简单的脚本来提取给定的标签名称:

{{1}}

但是当我更改标签的名称时,这不会更新。是否有任何脚本可以写入"重新执行" sheetName(),函数,在电子表格中找到的所有地方?很想只是弹出一个按钮,可以在任何地方重新运行sheetName(),以便选项卡名称'参考文献保持最新状态。

我确实看到了一些关于此问题的旧问题(〜4年),但很难找到最新的东西。如果这是重复的,请道歉!

2 个答案:

答案 0 :(得分:1)

您可以安装一个触发器来运行" On change"我尝试编辑工作表标签,代码确实运行了。

select pc.title, month(pl.tdate), pt.profit, sum(si.qty) 
from product_category pc
inner join sold_items si on si.product_category_id = pc.id
inner join profit_table pt on pt.invoiceid = si.invoiceid
inner join product_log pl on pl.invoiceid = pt.invoiceid
where si.product_id = pl.product_id  
group by pc.title,pl.tdate
order by month(pl.tdate) asc ; 

不幸的是,在这篇文章的时候,触发器有点儿麻烦。如果您安装了触发器并且它没有运行,则您需要删除触发器,关闭窗口,然后再次完成该过程并保存。

我将函数的名称更改为function checkForValidUrl(tabId, changeInfo, tab) { if(typeof tab != "undefined" && typeof tab != "null" ) { // If the tabs URL contains "specificsite.com"... //This would work in the same way as *specificsite.com*, with 0 or more characters surrounding the URL. if (/specificsite[.]com/.test(tab.url)) { // ... show the page action. chrome.pageAction.show(tabId); } } }; // Listen for any changes to the URL of any tab. chrome.tabs.onUpdated.addListener(checkForValidUrl); 我在触发器运行时遇到了很多麻烦。我不得不删除触发器并重新安装。

答案 1 :(得分:0)

保持您的工作表名称相同

如果你想保持你的工作表名称相同,这里只是一个脚本。它利用了我最近一直在努力的一些脚本,允许您在文件中保存数组和关联数组,而不是使用PropertiesService。它可能不是100%没有bug ......但是它是什么?

Code.gs

function onOpen()
{
  SpreadsheetApp.getUi().createMenu('My Tools')
      .addItem('SaveSheetNames', 'SaveSheetNames')
      .addToUi();
}

function SaveSheetNames()
{
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var shts = ss.getSheets();
   var s = 'SheetNames:::DICT|***|';
   for(var i = 0; i<shts.length;i++)
   {
     if(i>0){s += '~~~';}
     s += shts[i].getSheetId() + '^^^' + shts[i].getSheetName();
   }
   saveFile(s);
}

function KeepSheetNames()
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var shts = ss.getSheets();
  var SheetNamesA = getArrayByName('SheetNames');
  for(var i = 0; i<shts.length;i++)
  {
      if(shts[i].getName() !== SheetNamesA[shts[i].getSheetId()])
      {
        shts[i].setName(SheetNamesA[shts[i].getSheetId()]);
      }
  }
}

ArrayFileStorage.gs

 //A segment is either an Array or an Associative Array obtain by splitting the data string inside the data file with this delimeter |@@@|
    //It returns an actual Associative Array 
    function getAssociativeArray(segment)
    {
      var segment = (typeof(segment))?segment:null;
      var C = [];
      var br = '<br />';
      if(segment)
      {
        var A = segment.split('~~~');//Array of key^^^value strings [key^^^value,key^^^value,key^^^value...]
        for(var i = 0;i<A.length;i++)
        {
          B=A[i].split('^^^');//KeyValueArray[key,val]
          C[B[0]]=B[1];//Dictionary or Associative Array {key:'value',key:'value',key:'value'...}
        }
      }
      return C;
    }

    //A segment is either an Array or an Associative Array obtain by splitting the data string inside the data file with this delimeter |@@@|
    //It returns an actual Array 
    function getArray(segment)
    {
      var segment = (typeof(segment))?segment:null;
      var br = '<br />';
      if(segment)
      {
        var A=segment.split('~~~');
      }
      return A;
    }

    //The above functions are used within this function so that it can return either type of array object requested
    function getArrayByName(name)
    {
      var name = (typeof(name) !== 'undefined')? name : null;
      var br = '<br />';
      if(name)
      {
        var data = loadFile('KeepSheetNames').split('|@@@|');//Array Data String two different forms possible
        for(var i=0;i<data.length;i++)
        {
          var A = data[i].split('|***|');
          var B = A[0];
          var segment = A[1];
          var nametype = B.split(':::');
          if(nametype[0]==name)
          {
            if(nametype[1]=='DICT')
            {
              var obj = getAssociativeArray(segment)
            }
            if(nametype[1]=='ARRAY')
            {
              var obj = getArray(segment);
            }
            break;
          }
        }
      }
      return obj;
    }

    //This function just displays the data stored within the default data file by splitting it with |@@@|
    function displayData()
    {
      s='';
      var data = loadFile('KeepSheetNames').split('|@@@|');
      for(var i=0;i<data.length;i++)
      {
        if(i>0)s+='<br />';
        s+=data[i];
      }
      s += '<br /><input type="button" value="Exit" onClick="google.script.host.close();" />'
      dispStatus('Display Data for Default File',s,1000,400);
    }

    //This function uses the saveFile function in Utility.gs to save data into default file.
    //This function will also add a new array to the end
    function saveArray(name,type,array)
    {
      var name = (typeof(name) !== 'undefined')? name : null;
      var type = (typeof(type) !== 'undefined')? type : null;
      var array = (typeof(array) !== 'undefined')? array : null;
      var types = ['DICT','ARRAY'];
      var isSaved = false;
      var isAValidType = false;
      for(var i=0;i<types.length;i++)
      {
        if(type == types[i])
        {
          isAValidType=true;
          break;
        }
      }
      if(name && isAValidType && array)
      {
        var data = loadFile('KeepSheetNames').split('|@@@|');
        var datstr = '';
        var idx = getIndexOf(name);
        var str = convertArrayToString(name,type,array);
        if(idx>-1)
        {
          data[idx]=str;
        }
        else
        {
          data.push(str);
        }
        for(var i = 0;i<data.length;i++)
        {
          if(i>0){datstr += '|@@@|';}
          datstr += data[i];
        }
        isSaved=saveFile(datstr);
      }
      else
      {
        SpreadsheetApp.getUi().alert('Invalid Input: Check your parameters in function saveArray().');
      }
      return isSaved;
    }

    //This function gets the index of the requested named data array
    function getIndexOf(name)
    {
      var name = (typeof(name) !== 'undefined')? name : null;
      var idx = -1;
      if(name)
      {
        var data = loadFile('KeepSheetNames').split('|@@@|');
        for(var i=0;i<data.length;i++)
        {
          var nametype = data[i].split(':::');
          if(name==nametype[0])
          {
            idx = i;
            break;
          }
        }
      }
      return idx;
    }

    //Takes the real arrays and converts them to strings so that they can be saved.
    function convertArrayToString(name,type,array)
    {
      var name = (typeof(name) !== 'undefined')? name : null;
      var type = (typeof(type) !== 'undefined')? type : null;
      var array = (typeof(array) !== 'undefined')? array : null;
      var types = ['DICT','ARRAY'];
      var ConvertedString='';
      var isAValidType = false;
      for(var i=0;i<types.length;i++)
      {
        if(type == types[i])
        {
          isAValidType=true;
          break;
        }
      }
      if(name && array && isAValidType)
      {
        ConvertedString += name + ':::' + type + '|***|';
        switch(type)
        {
          case 'ARRAY':

            for(var i=0;i<array.length;i++)
            {
              if(i>0){ConvertedString += '~~~';}
              ConvertedString += array[i];
            }
             break;
          case 'DICT':
            var firstTime = true;
            for(var key in array)
            {
              if(!firstTime){ConvertedString += '~~~';}
              ConvertedString += key + '^^^' + array[key];
              firstTime=false;
            }
             break;
        }
      }
      else
      {
        SpreadsheetApp.getUi().alert('Invalid Input: Check your parameters in function saveArray().');
      } 
      return ConvertedString;
    }

    //deletes a current data array
    function deleteArrayByName(name)
    {
      var name = (typeof(name) !== 'undefined')? name : null;
      var br = '<br />';
      var isSaved = false;
      if(name)
      {
        var delidx = getIndexOf(name);
        if(delidx > -1)
        {
          var datstr = '';
          var data = loadFile('KeepSheetNames').split('|@@@|');//Array Data String two different forms possible
          for(var i=0;i<data.length;i++)
          {
            if(delidx !== i)
            {
              if(i>0){datstr += '|@@@|';}
              datstr += data[i];
            }
          }
          isSaved=saveFile(datstr);
        }
      return isSaved;
      }
    }

    function dispFile(filename,folderID)
    {
      var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
      var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
      var file = loadFile();
      if(file)
      {
        dispStatus('Displaying File: ' + filename, file, 800, 500);
      }
      else
      {
        SpreadsheetApp.getUi().alert('File "' + filename + '" not found in function dispFile.');
      }
    }

    function loadFile(filename,folderID)
    {
      var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
      var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
      var fldr = DriveApp.getFolderById(folderID);
      var file = fldr.getFilesByName(filename);
      var s = '';
      while(file.hasNext())
      {
        var fi = file.next();
        var target = fi.getName();
        if(target == filename)
        {
          s = fi.getBlob().getDataAsString();
        }
      }
      return s;
    }

    function delFile(filename,folderID)
    {
      var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
      var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
      var fldr = DriveApp.getFolderById(folderID)
      var file = fldr.getFilesByName(filename);
      var targetFound = false;
      while(file.hasNext())
      {
        var fi = file.next();
        var target = fi.getName();
        if(target == filename)
        {
          targetFound = true;
          fldr.removeFile(fi);
          SpreadsheetApp.getUi().alert('File: ' + filename + ' was removed from: ' + fldr.getName() + '/' + target);
        }
      }
      return targetFound;
    }

    function saveFile(datstr,filename)
    {
      var filename = (typeof(filename) !== 'undefined')? filename : 'KeepSheetNames';
      var folderID = (typeof(folderID) !== 'undefined')? folderID : '';
      var fldr = DriveApp.getFolderById(folderID);
      var file = fldr.getFilesByName(filename);
      var targetFound = false;
      while(file.hasNext())
      {
        var fi = file.next();
        var target = fi.getName();
        if(target == filename)
        {
          targetFound = true;
          fi.setContent(datstr);
        }
        return targetFound;
      }
    }

Utility.gs

// Display a modeless dialog box with custom HtmlService content.
function dispStatus(title,html,width,height,modal)
{
  var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
  var width = typeof(width) !== 'undefined' ? width : 400;
  var height = typeof(height) !== 'undefined' ? height : 300;
  var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
  var modal = typeof(modal) !== 'undefined' ? modal : false;
  var htmlOutput = HtmlService
     .createHtmlOutput(html)
     .setWidth(width)
     .setHeight(height);
 if(!modal)
 {
   SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
 }
 else
 {
   SpreadsheetApp.getUi().showModalDialog(htmlOutput, title);
 }
} 

您必须设置一个onEdit触发器来调用KeepSheetNames(),并且应该这样做。我玩了一下它似乎工作正常。如果您发现任何问题,请随时修复它。此外,您还必须添加数据文件夹的ID。我决定发布它可能不是一个好主意。