authors are vetted experts in their fields and write on topics in which they have demonstrated experience. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.
Stefan Thelin的头像

Stefan Thelin

Stefan是Cargotec数据驱动洞察和分析总监, 领先的货物和装载解决方案提供商. 他还曾担任硕士&一个是董事,一个是创业公司的CFO, 并在苏格兰皇家银行担任杠杆融资经理,领导金融建模和分析.

Expertise

Previously At

Cargotec
Share

高效的管理者知道时间是限制因素, perhaps, 有效的管理者的区别在于他们对时间的温柔关怀.

Peter Drucker

时间是我们最宝贵的资源. 我们希望把它花在最有影响力和最有价值的活动上, 这不仅是因为它们通常具有最高的货币价值, 但也要不断挑战自我,最大限度地提高我们的工作满意度.

There are many ways to improve your efficiency and productivity in order to make better use of your time. 在之前的一篇关于 Google Sheets,我详细阐述了在线协作的力量如何成为提高生产力的关键之一.

在另一篇文章中,我演示了如何 Python 编程语言可以成为金融专业人士强大的分析和任务自动化工具.

受此启发,我现在想要呈现谷歌Apps Script教程. b谷歌Apps Script允许你用JavaScript编写脚本和程序来实现自动化, 连接和扩展b谷歌的G Suite中的产品, including Sheets, Docs, Slides, Gmail, Drive, 还有其他几个. 学习它需要投入时间, 编写脚本也是如此, 但是,生产力的提高和由此带来的额外机会使它非常值得.

作为第一步,让我们从一个熟悉的概念开始:宏.

在谷歌工作表中记录和使用宏

如果你花了大量的时间使用Excel, then you are bound to have come into contact with Excel’s VBA (Visual Basic for Applications) macro interface at some point. 你可以自己记录或写,也可以借鉴别人的作品.

宏是自动化重复和繁琐工作流程的好方法. VBA可能不是你花很多时间去学习的语言, but its beauty was that you didn’t really need to in order to become productive and create your own macros. 您可以简单地记录您想要自动化的工作流, 然后进入代码并进行任何需要的小更改,以使宏更通用.

In some ways, 关于如何向非技术人员介绍编码,VBA是一个很好的却被遗忘的课程. The way you could record actions and then have the code populated for later review is indeed a far more pragmatic way of learning over reading textbooks and passively watching tutorials.

谷歌Sheets中提供了VBA的相同录制功能. 下面是如何使用它的一个简单例子:

让我们从一些示例数据开始,使用 IMPORTHTML 查询导入表. 在这个例子中,我从维基百科下载了一份世界上最大的15家对冲基金的名单. 这是不言而喻的, but, this is an arbitrary example; the intention is for you to focus more on the application, over the subject.

用于导入表的样例数据.

The macro recording process is instigated via the following menu path: Tools > Macros > Record macro.

然后我们通过我们想要记录的动作(PC格式):

  1. 选择第一行
  2. 按Shift + Ctrl +向下箭头选择所有东西
  3. Ctrl + C复制
  4. Shift + F11创建一个新工作表
  5. 给表格起个新名字
  6. 按Shift + Control + V粘贴值

Once done, 按下底部宏窗口上的Save按钮, 给它一个名字和一个可选的键盘快捷键.

对于可以完全通过这些相同步骤复制的更简单的操作, 该过程将在这里结束,您可以立即开始使用宏. 但是,在这种情况下,我们需要在代码可用之前进行一些更改. 例如,我们复制到的工作表每次都需要有不同的名称. 我们来看看怎么做.

手动编写谷歌Apps脚本

Now we will see the bones of Google Apps Script for the first time; the programming platform that runs on Google’s servers. 这增强了我们的宏,并允许您创建非常复杂的工作流, and even add-ons, 对于应用程序本身. It can be used to automate not only spreadsheet work but actually almost anything interconnected within Google’s G Suite.

Apps Script的编程语言是 JavaScript, 最流行的编程语言之一, 这意味着对于任何想要广泛学习的人来说,那里有丰富的资源. But, just as with VBA, you don’t really need to: you can use the same Record functionality and simply do the steps you want to be able to repeat automatically. The output from the recording might look crude and most likely won’t match perfectly with what you want to get done, 但它将提供一个足够坚实的起点. 现在让我们对刚刚录制的脚本执行此操作.

When recording, it makes sense to be careful not to record any additional steps by accident that you don’t want to be captured in the final recording, but it’s sometimes difficult to avoid: something as simple as selecting a different cell before pressing the Stop Recording button will be captured and subsequently repeated every time you run the script. 编辑脚本的第一步是清理并删除任何此类步骤. Let’s dive in by going to Tools > Script editor in the file menu.

Script editor

如果你懂JavaScript, 你会立刻意识到这一点, and you might also be surprised to see the “var” keyword instead of “let” or “const” as you would see in modern JavaScript. 这反映了一个事实,JavaScript版本在Apps Script相当 old 并且不支持该语言的许多最新功能. Towards the end, 不过,对于那些想要使用最新语言特性的人,我将介绍一种变通方法.

当您第一次运行该脚本时,它将请求授权, 这是有道理的, 因为脚本可以修改(并可能删除)您的所有数据. 您很可能会从其他谷歌产品中识别授权过程.

现在我们可以开始修改代码了. 我们需要做的改动很小, 但如果你第一次这么做, 它可能仍然需要通过Sheets Apps Script进行一些快速搜索 documentation 和/或快速查找JavaScript概念,例如处理日期. Here the fact that JavaScript is such a widespread language comes in handy: A solution for whatever issue you face or functionality comes to mind can usually be found quickly if you phrase your search term in a straightforward way.

The changes made in this version of the script from the original recorded version are that instead of the hardcoded name for the new sheet that we create, 我们现在用今天的日期来命名它. 此外,我们还更改了末尾的复制路径,以引用此新表. 最后四行还演示了如何执行一些格式化操作, 例如更改单元格的值, 调整列的大小和隐藏网格线.

createSnapshot() {
  var spreadsheet =电子表格应用程序.getActive();
  var date = new date ().toISOString().slice(0,10);
  Var destination =电子表格.insertSheet(日期);
  
  spreadsheet.getRange('HTML!A1:F1').activate();
  spreadsheet.getSelection()
    .getNextDataRange (SpreadsheetApp.Direction.DOWN)
    .activate();
  
  spreadsheet.getActiveRange ()
    .copyTo (SpreadsheetApp.setActiveSheet(目的地)
    .getRange(1,1),
    SpreadsheetApp.CopyPasteType.PASTE_VALUES、假);
  
  电子表格.setActiveSheet(目的地)
  sheet.getRange("D1").setValue(“bn美元资产管理”)
  sheet.setHiddenGridlines(真正的);
  sheet.getRange (A1: D1).setFontWeight(“大胆”);
  sheet.autoResizeColumns (1,4);
};

Running the script now will show that the new sheet is indeed named with today’s date and contains the information copied as values (not formulas) from the main sheet.

现在可以通过使用相同的记录过程来添加图表可视化. 我用它创建了三个简单的图表.

图表可视化.

清理每个代码将看起来像这样:

createColumnChart() {
  var spreadsheet =电子表格应用程序.getActive();
  spreadsheet.getRange (C1: D16).activate();
  电子表格.getActiveSheet ();
  chart = sheet.newChart()
  .asColumnChart()
  .addRange(电子表格.getRange (B1: D16))
  .setMergeStrategy(图表.ChartMergeStrategy.MERGE_COLUMNS)
  .setTransposeRowsAndColumns(假)
  .setNumHeaders (1)
  .setHiddenDimensionStrategy(图表.ChartHiddenDimensionStrategy.IGNORE_BOTH)
  .setOption (useFirstColumnAsDomain,真的)
  .setOption(‘curveType’,‘没有’)
  .setOption(“domainAxis.direction', 1)
  .setOption(“isStacked”、“绝对”)
  .setOption('系列.0.颜色”、“# 0 b5394”)
  .setOption('系列.0.labelInLegend', 'AUM $十亿')
  .setPosition(19,6,15,5)
  .build();
  sheet.insertChart(图);
};

Again, 如果有些选项看起来令人困惑,不要担心:这些都是自动生成的, 您只需要足够的理解,以删除不必要的步骤,并可能在以后进行小的调整.

高级谷歌应用程序脚本示例:连接表到谷歌驱动器和幻灯片

现在一切都开始成形了, 但是,如果我们想要的实际输出不是电子表格而是演示文稿呢? 如果是这样的话, 那么从这里开始的大部分工作可能仍然是手工的, 如果我们需要重复做这个,我们并没有节省很多时间.

Let’s now explore what it might look like to automate the creation of a presentation using the example data from our spreadsheet.

这个练习现在变得更高级了,原因有二:

  1. We will need to familiarize ourselves with how to work with Google Slides (and Google Drive) in addition to Sheets.
  2. In Slides, 或者在G Suite应用程序之间工作时, 没有“记录宏”功能可用. 这意味着你需要对Apps Script有足够的了解(并且能够自如地导航) documentation (每个G Suite产品)从头开始编写脚本.

下一个示例旨在提供一些基本的构建块,帮助您入门和熟悉.

首先,让我们创建一个模板,稍后我们希望使用脚本填充内容. 下面是我整理的两张简单的幻灯片:

周报模板.

Next, 您将需要获得此模板的ID,因为您将不得不在脚本中引用它. 潜意识里,你会看到这个本我很多次,因为它是, in fact, 你在浏览器的URL中看到的随机的字符和数字序列:

http://docs.google.com/presentation/p/this_is_your_presentation_ID/edit#slide=id.p.

现在我们必须将以下代码行添加到原始脚本中. 这将再次提示授权,这次是访问谷歌驱动器.

函数createPresentation() {
  var templateId = "insert_your_template_presentation_id_here";
  var template = DriveApp . var.getFileById (templateId);
  Var copy = template.makeccopy(“周报”+日期).getId();
  var presentation = SlidesApp.openById(copy);
}

如果运行此代码片段,将不会看到任何即时的视觉反馈, but if you look in the folder of your Google Drive where you had stored the template you will find that a copy of it has indeed been created, 文件名里有今天的日期. 我们开了个好头!

现在让我们使用更多的构建块来开始填充内容, 通过编程而不是手工. 将以下行添加到同一函数中:

  presentation.getSlides()[0]
    .getPageElements () [0]
    .asShape()
    .getText()
    .setText(“周报”+日期);

现在事情变得更有趣了, 因为我们把第一页改成了今天的日期. In Slides, as in Sheets, 使用对象(由类表示),每个对象都有属性和方法(例如类).e. 附加功能). 这些是按层次结构组织的,有 SpreadsheetsApp, DriveApp or SlidesApp 成为顶级对象. 在上面的代码片段中, 我们需要一步一步地在这个层次结构中移动,以到达我们想要编辑的元素, 在本例中:文本框中的文本. 实际上,这意味着要深入了解 Presentation, Slide, PageElement, and Shape 对象,直到我们最终到达 TextRange 要编辑的对象.

Keeping track of which type of object you are dealing with can be confusing and the bugs that result from trying to apply an operation to the wrong object can be hard to solve. Unfortunately, the help functionality and error messages in the Script Editor itself don’t always provide a lot of guidance here, 幸运的是,这样的关注至少会改善您的质量控制实践.

创建了演示文稿并更新了标题, 现在是时候将我们的一个新图表插入其中了. 记住对象的层次结构,下面的代码现在应该是有意义的:

  var spreadsheet =电子表格应用程序.getActive();
  电子表格.getSheetByName(日期);
  图表.getCharts()[0];
  
  Var position ={左:25,顶:75};
  Var size ={宽度:480,高度:300};
  
  presentation.getSlides()[1]
    .insertSheetsChart(图表,
      position.left,
      position.top,
      size.width,
      size.height);

如果你运行完整的脚本,输出应该是这样的:

示例演示

Hopefully, this example illustrates the principles and provides inspiration to get you started with your own experimentation. 如果你仔细想想, I’m sure you can find at least a few examples of manual work done in your company today that really should be automated in this way. 用来腾出时间去思考, analyze, 并作出判断, 而不是机械地将数据从一种格式和/或位置转移到另一种格式和/或位置. 改善开发体验 如前所述, the JavaScript version supported in Google Apps Script is old and the functionality of the online Script Editor is very limited. 如果你只是记录一个宏或者写几十行代码,你不会注意到. If however, 你确实有雄心勃勃的计划,将每周或每月报告的各个方面自动化, 或者想要构建插件, 那你会很高兴知道有一个 命令行工具 这允许您使用自己喜欢的开发环境进行开发.

如果你达到了这样的熟练程度, then you’ll probably also want to take advantage of the most recent features that JavaScript has to offer, 甚至可能更多, 由于使用命令行工具,您还可以在 TypeScript.

使用Python进行谷歌表编程

如果你发现使用Apps脚本不是你的菜, 还有其他的选择, 取决于用例. 如果你想做更高级的数字运算, 连接api或数据库, 或者更喜欢Python编程语言而不是JavaScript, then Google’s Colaboratory 是无价之宝. It gives you a Jupyter notebook running on Google’s servers that allows you to write Python scripts that integrate 无缝地与您的谷歌驱动器文件,并通过 ‘gspread’ 库,可以轻松处理电子表格数据.

我在一篇文章中概述了Python的许多优点 article 关于如何将其用于财务功能, which also serves as a gentle introduction to working with Python and Jupyter notebooks in a business and financial context. 对我来说,一个非常重要的好处是,与Apps Script不同, 协作中的Python笔记本是交互式的, 因此,在执行每行或一小段代码后,您可以看到结果(或错误消息).

自动化容易上瘾

这个谷歌应用程序脚本教程展示了通过谷歌的编码语言可能实现的功能. 可能性实际上是无穷无尽的. However, 如果你没有技术背景, the code examples may look daunting and you might be thinking to yourself that the productivity gains earned from learning Google Apps Script might not be sufficient enough to outweigh the significant investment in terms of time needed to learn it.

This, of course, 取决于很多因素, 包括你的角色类型, 或者期望有, in the future. 但是,即使您不希望做任何类似于这里所示示例的事情, having an understanding of what is possible and roughly how much work it would take to implement can trigger thoughts and ideas around how to improve productivity in your company, for your clients, 或者你自己.

Personally, I can attest to the satisfaction of sitting back and hitting a button that completes an hour’s worth of tedious manual work in under a minute. After doing this for the 50th time you will be grateful for the couple of hours spent cobbling it all together in the first place, 这最终会让你腾出时间去追求更多的增值. 一段时间后,这些可扩展性的好处确实会让人上瘾.

了解基本知识

  • 我如何使用谷歌应用程序脚本?

    b谷歌Apps Script是通过谷歌软件产品的Script Editor功能访问的. 代码可以记录到跟随用户步骤,或者直接在脚本编辑器中编写/编辑.

就这一主题咨询作者或专家.
Schedule a call
Stefan Thelin的头像
Stefan Thelin

Located in Lund, Sweden

Member since 2017年9月20日

作者简介

Stefan是Cargotec数据驱动洞察和分析总监, 领先的货物和装载解决方案提供商. 他还曾担任硕士&一个是董事,一个是创业公司的CFO, 并在苏格兰皇家银行担任杠杆融资经理,领导金融建模和分析.

Toptalauthors are vetted experts in their fields and write on topics in which they have demonstrated experience. 我们所有的内容都经过同行评审,并由同一领域的Toptal专家验证.

Expertise

Previously At

Cargotec

世界级的文章,每周发一次.

订阅意味着同意我们的 privacy policy

世界级的文章,每周发一次.

订阅意味着同意我们的 privacy policy

金融专家

Join the Toptal® community.