首页 > 解决方案 > 关闭我制作的发票模板时,我需要代码在 Google 表格中自动保存副本 -

问题描述

关闭我制作的发票模板时,我需要代码在 Google 表格中自动保存副本 - 根据发票编号保存它并重新打开发票编号增加 1 的新发票

我包括一个指向工作表的链接 https://docs.google.com/spreadsheets/d/1b4saYo1ruVfpUbUsGVd0Vf3NmjwQo78riuMyWi0OFcg/edit?usp=sharing

表格中有一些不应更改的公式。

我只需要能够获得一个按钮的代码,我可以单击它并关闭当前工作表,同时将其保存为在线位置的 pdf,当我重新打开时,发票编号增加了 1

标签: google-sheetsgoogle-sheets-api

解决方案


你有什么:

  • 每张纸都是一张带有编号的发票

你想要什么:

  • 触发出现新的空白发票
    • 这张新发票需要有唯一编号 = previous number+ 1

为此,您必须:

  • 获取当前工作表(当前发票)
  • 复制工作表
    • 我建议将其重命名为发票编号以便于查找
  • 更新当前发票编号。
  • 删除原始表(以前称为当前表)上的旧发票内容

一步步

初步设置

我已根据您提供的表格制作了一份副本。我做了一些修改,比如删除额外的列和行以使生活更轻松。

基于此副本,让我们将有关工作表的一些信息存储到变量中。

在该工作表的 Apps 脚本代码中,让我们编写:

const fieldsA1 = {
  invoiceNumber : "F5",
  salesperson : "A14" //As an example of a field we want to clear later
};


function generateNewInvoice() {
}

获取当前工作表

var spreadsheet = SpreadsheetApp.getActive(); //Gets the current spreadsheet file
var currentInvoice = SpreadsheetApp.getActiveSheet(); //Get the open Sheet (the current invoice)

复制工作表

var copyInvoice = spreadsheet.duplicateActiveSheet(); //Creates a copy of currentInvoice and assign it to copyInvoice

重命名新工作表并设置样式

在这种情况下,我选择按以下格式设置新工作表的样式:

示例输出

copyInvoice.setName("Invoice " + currentInvoice.getRange(fieldsA1.invoiceNumber).getValue());
copyInvoice.setTabColor("red"); //For example, to highlight the tab

更新当前发票编号

var newInvoiceNumber = Number(currentInvoice.getRange(fieldsA1.invoiceNumber).getValue())+1; //Gets a new invoice number by adding 1 to the current Invoice Number
currentInvoice.getRange(fieldsA1.invoiceNumber).setValue(newInvoiceNumber);

从原始工作表中删除旧内容

//Other operations that might be interesting for your invoice
currentInvoice.getRange(fieldsA1.salesperson).clear(); //Reset salesperson

最后结果

const fieldsA1 = {
  invoiceNumber : "F5",
  salesperson : "A14" //As an example of a field we want to clear later
};


function generateNewInvoice() {
  var spreadsheet = SpreadsheetApp.getActive(); //Gets the current spreadsheet file
  var currentInvoice = SpreadsheetApp.getActiveSheet(); //Get the open Sheet (the current invoice)
  var copyInvoice = spreadsheet.duplicateActiveSheet(); //Creates a copy of currentInvoice and assign it to copyInvoice
  copyInvoice.setName("Invoice " + currentInvoice.getRange(fieldsA1.invoiceNumber).getValue());
  copyInvoice.setTabColor("red"); //For example, to highlight the tab

  var newInvoiceNumber = Number(currentInvoice.getRange(fieldsA1.invoiceNumber).getValue())+1; //Gets a new invoice number by adding 1 to the current Invoice Number
  currentInvoice.getRange(fieldsA1.invoiceNumber).setValue(newInvoiceNumber);


  //Other operations that might be interesting for your invoice
  currentInvoice.getRange(fieldsA1.salesperson).clear(); //Reset salesperson
}

现在只需generatedNewInvoice从工作表中触发功能即可。例如,您可以使用工具栏操作来执行此操作。


推荐阅读