首页 > 解决方案 > 如何通过单击按钮从谷歌表格中的单元格打开网站?

问题描述

我正在谷歌表格中制作电子表格,其中有几个链接指向预先填写的谷歌表格https://docs.google.com/forms 。我在电子表格中添加了一个“按钮”,当您单击它时,它会导航到包含指向预填充表单的正确链接的单元格(当前活动单元格右侧的 16 个单元格),如下所示;

function GoToSite(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Returns the active cell
var cell = sheet.getActiveCell();
cell.offset(0,16).activate();
};  

但是,我无法让电子表格打开此链接。我知道在普通的 excel 文件中,你会使用类似的东西;

Sub openwebpage ()
... 
End Sub

您可以使用“FollowHyperlink”/“创建 IE 对象”/“.Navigate”甚至“Sendkeys”(如果在选择包含预填充链接的单元格时输入 alt+enter,则会打开网页)。但是所有这些选项都与 sub .. end sub 结合使用,我无法管理宏来识别这一点。它似乎只适用于

function example (){
...
};

也许我做错了什么。是否有人知道如何使用宏打开单元格中的链接?或者如何在谷歌表格中使用“Sub ... End Sub”?

谢谢

标签: google-apps-scriptgoogle-sheets

解决方案


您可以将以下代码粘贴到您的脚本编辑器中,并通过 aurl作为其参数。

/**
 * Open a URL in a new tab.
 */
function openUrl( url ){
  var html = HtmlService.createHtmlOutput('<html><script>'
  +'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
  +'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
  +'if(document.createEvent){'
  +'  var event=document.createEvent("MouseEvents");'
  +'  if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'                          
  +'  event.initEvent("click",true,true); a.dispatchEvent(event);'
  +'}else{ a.click() }'
  +'close();'
  +'</script>'
  // Offer URL as clickable link in case above code fails.
  +'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. <a href="'+url+'" target="_blank" onclick="window.close()">Click here to proceed</a>.</body>'
  +'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
  +'</html>')
  .setWidth( 90 ).setHeight( 1 );
  SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}

该解决方案的作者指出,您将无法直接在脚本编辑器中运行此代码,您需要将脚本分配给绘图或按钮。

用于打开 URL 的 Google Apps 脚本


推荐阅读