簡體   English   中英

根據Google工作表中的缺失數據創建表單

[英]Creating a form based upon missing data from google sheet

我在Google表格中有一個數據集,該數據集在某些字段中缺少一些信息。 在某些標題下,所有數據都是統一的,並且都具有唯一的ID值。 我創建了一個驗證表單,該表單提取缺少字段的相應唯一ID值及其列標題,以了解缺少哪些項目,但是我想創建一個基於這些丟失值創建的Google表單。

缺少單元格的數量將是驗證表中產生的唯一ID的數量。

Google表格表格說明:

原始數據就是這樣。

ValidationSheet清除所有填充的單元格並在A列中提供相應的ID

Non-Blank(Query)Non-Blank(Formula)都壓縮ValidationSheet數據(兩者都做同樣的事情,只是一個具有公式而其他用途是查詢)

Unpivot是Non-Blank表的未透視結果。

目的是基於Unpivoted值創建一個表單,在該表單中填充了唯一ID的表單,缺少該字段作為問題,要求他們填寫空白。

我嘗試的代碼僅完成了一半,因為我不確定以下步驟

function createForm() {

  var item = "Missing Data"

  var form = FormApp.Create(item)
  .setTitle(item);

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(ResponseSheet);
  var data = sheet.getDataRange().getValues();
  var responses = form.getResponses();


  item = (Define item to be the missing value)
  form.addTextItem()
     .setTitle(<insert missing value here & add more text saying "missing value">)
     .setRequired(true);

提供您的驗證表如下所示:

在此處輸入圖片說明

這是您可以根據丟失的數據創建表單的方法:

function createForm() {

  var title = "Missing Data";  //changed
  var ResponseSheet="Sheet1"; //replace with your sheet name
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(ResponseSheet);
  var data = sheet.getDataRange().getValues();
  var headings=data[0];  //provided that your headings are stored in the first row
  for(var i=1; i<data.length;i++){
    var item=[];
    for (var j=1; j<headings.length;j++){
      if(data[i][j]==""||data[i][j]==" "){
        item[j]=headings[j];
      } 
    } 
    if(!item.length == 0){
      var form = FormApp.create(headings[0])  //Careful! It's create and not Create
       .setTitle("Form submission "+data[i][0]+" "+ title);
      item.forEach(function(element) {
      form.addTextItem()
      .setTitle(element+" missing value")
      .setRequired(true);
      })               
      Logger.log("Form submission "+data[i][0]+": "+form.getPublishedUrl());
    }
  }
}

該方法基於以下假設:您有多個表單提交的數據缺失,因此將針對每個提交的缺少數據的表單創建一個新的“缺少數據”表單。

理念:

您遍歷一行的所有單元格,如果找到至少一個空單元格,則為該行創建一個表單,並將與空單元格對應的列標題作為表單項追加到表單中。

結果:

在此處輸入圖片說明在此處輸入圖片說明

Google腳本中通常有很多處理方法-這種情況也不例外。 請認為這僅僅是實現結果的一種方法。

該代碼在電子表格附帶的腳本編輯器中編寫。

總覽
Google表單,可從電子表格中的數據中更新ListItem的下拉選項。
下拉選項位於問題1中,並且每個項目都會基於電子表格數據自動鏈接到相關的頁面/問題。 該設計假定每個下拉菜單僅包含一個后續問題(盡管可以構建更復雜的系統)。

該代碼包含多個功能,但它可以作為一個系統使用。 因此,啟動和管理表格需要采取許多具體步驟。

這些是:
A-創建電子表格和表格-一個手動過程。

  • 創建電子表格,或使用現有的電子表格包含有關丟失的信息。
  • 在所選的雲端硬盤文件夾中創建一個表單,並使用適當的文件名(以后可以根據需要更改這些表單)。 最好創建一個新表單,以便所有更改都由代碼驅動。

B-將代碼復制到電子表格-手動過程。

  • 打開電子表格腳本編輯器。
  • 如果尚不存在,請創建一個合適的項目名稱。
  • 創建一個新的腳本文件(使用適當的名稱)。
  • 將下面包含的所有代碼復制到腳本文件中。
  • 保存腳本文件。

C-更新全局變量-手動過程。
在電子表格腳本編輯器中,更新腳本文件頂部的全局變量。

  • 輸入電子表格ID =“插入電子表格ID”
  • 輸入表單ID =“插入表單ID”
  • 輸入工作表(標簽)名稱(不是文件/電子表格的名稱),將在其中記錄缺少的字段信息
  • 保存腳本文件。

D-更新電子表格。

  • 如果工作表尚不存在,請創建它。
  • 輸入/確認工作表的列標題
    //標頭應位於第1行; 從第2行開始的數據
    //列標題為:
    //列A-唯一ID
    // B列-標簽號
    // C列-缺少數據字段
    //僅供參考:“可能”字段的當前列表為:房間號,類型標記,描述,標記,制造商,型號,保修終止日期,安裝日期,維護。
    //如果創建了新字段,或刪除/更改了現有字段,則還需要手動更新信息。

E-安裝可觸發的觸發器

在電子表格腳本編輯器中,單擊“時鍾”圖標以安裝“可安裝”觸發器。

  • 添加觸發器。
  • 要運行的函數=“ sheetOpen”
  • 在Deployment =“ Head”時運行(默認)
  • 選擇事件源=電子表格(默認)
  • 選擇事件類型=打開時
  • 單擊保存。 可能會要求您確認權限,照常完成此操作。
  • 關閉電子表格,然后再次打開-現在有一個自定義菜單“缺少字段表單”

自定義菜單(“缺少字段表格”)
1-初始設置(可重復)
2-添加缺少的字段部分和問題(僅一次)
3-創建表單目標(可重復)
4-構建特定ID和缺失字段的內容(可重復)

最初設定
從自定義菜單中,選擇“初始設置”
這將更新以下值:

  • 標題
  • 描述
  • 確認訊息
  • 允許用戶編輯他們的回復:否
  • 啟用表單以接受響應:True

您可以根據需要修改初始設置設置並運行此功能。 它還會創建一個新的下拉問題。 如果下拉列表存在,則不會創建第二個副本; 如果該下拉列表不存在,則將創建它。

添加缺少的字段和問題(僅一次)
這將為每個領域的可能性添加一個新的部分和問題。

創建表格目的地
從自定義菜單中,選擇“創建新的表單目標”,這將在電子表格中為表單響應創建一個新的目標表單。

建立特定ID和缺失字段的內容
這將從電子表格中獲取唯一ID及其缺失字段,並將其添加到下拉列表中。 每個項目都會自動鏈接到相關頁面。 該過程可以完全重復,並且可以按照用戶希望的次數進行多次。 表格中的任何/所有ID和字段都將被電子表格中的數據覆蓋。


// This code is designed to manage a form for collecting information about missing fields in a Plant Register.
// This version of the code is designed for the scenario where there is only ONE missing data field per equipment item record

// Global variables

// Record the ID of the spreadsheet
var ssID = "1-DDTt_dEV2LLtGwhZ6qBtGHrz07EJ4Ef4yxxuZKaEF8";
// Record the ID of the form
var formID = "1MJYof24YrUubpdFBlxT63LSVpvshh4eFKaUQGITlBms";
// Record the sheet (tab) name where the missing data will be recorded (starting in cell A1
// column headings for that sheet are:
// Column A - Unique ID
// Column B - Tag Number
// Column C - MIssing data field
var sheetname = "form_input_single";
// open the spreadsheet
var wsData = SpreadsheetApp.openById(ssID).getSheetByName(sheetname);
// open the form
var form = FormApp.openById(formID);


/*
///////////////////////////////////////////////////////////////////////////////
*/


    // The onOpen function is executed automatically every time a Spreadsheet is loaded    
    // Add a custom menu to the active spreadsheet, including a separator and a sub-menu.    
    // Adds the custom menu to the active spreadsheet.
    function sheetOpen() {

      SpreadsheetApp.getUi()
        .createMenu('Missing Fields Form')
        .addSubMenu(SpreadsheetApp.getUi().createMenu('Setup')
          .addItem('1: Inital Setup (repeatable)', 'formsetup')
          .addItem(
            '2: Add Missing Field Sections and Questions (once only)',
            'addMissingfieldsandPagebreaks')
          .addItem('3. Create new Form Destination (repeatable)',
            'setFormdestination'))
        .addSeparator()
        .addSubMenu(SpreadsheetApp.getUi().createMenu(
            'Update Missing Fields')
          .addItem(
            '4. Build the content for specific PLANT IDs and respective missing fields (repeatable)',
            'UpdateDropDownItems'))
        .addToUi();
    }


    /*
    ///////////////////////////////////////////////////////////////////////////////
    */

    //Step#1
    function formsetup() {
      // Update form properties via chaining.
      form.setTitle('Equipment Register Update')
        .setDescription(
          'This form is used to complete missing fields in the Equipment Register'
          )
        .setConfirmationMessage('Thanks for responding!')
        .setAllowResponseEdits(false)
        .setAcceptingResponses(true);

      // Build the initial Drop-down question
      buildInitialDropdownQuestion();

      // Add the Missing field drop-downs items ands links
      //addDropDownItems();
    }

    function buildInitialDropdownQuestion() {

      // Build
      // list ListItems
      var listitems = form.getItems(FormApp.ItemType.LIST);
      if (listitems.length != 0) {
        Logger.log("DEBUG: These are the list items");
        for (var i = 0; i < listitems.length; i++) {
          Logger.log("DEBUG:" + listitems[i].getTitle() + ", ID= " +
            listitems[i].getId());
        }
      } else {
        Logger.log("DEBUG: there are no list items");
        // add opening list item and Title
        var item = form.addListItem();
        item.setTitle('Tag/Equipment Number');
        item.setRequired(true);
      }
    }

    /*
    ///////////////////////////////////////////////////////////////////////////////
    */
    // Step#2  
    function addMissingfieldsandPagebreaks() {

      // add all the potential missing fields and relevant questions
      // as built, this is intended to run once only. 
      // If this function is run more than once, it will duplicate the existing pages and questions

      // Equipment - Mark
      var mark = form.addPageBreakItem().setTitle(
        "The Mark on the equipment?").setHelpText(
        'Updating identifying marks on equipment').setGoToPage(FormApp
        .PageNavigationType.SUBMIT);;
      form.addTextItem().setTitle("Mark").setHelpText(
        '(an identifying mark on the equipment)').setRequired(true);

      // Room Number
      var roomnumber = form.addPageBreakItem().setTitle(
        "The Rooom number?").setHelpText(
        'Updating the room number for this equipment').setGoToPage(
        FormApp.PageNavigationType.SUBMIT);;
      form.addTextItem().setTitle("Room Number").setHelpText(
        '(format XX-ZZZZ)').setRequired(true);

      // Maintenance
      var maintenance = form.addPageBreakItem().setTitle(
        "Maintenance Schedule").setHelpText(
        'Updating the maintenance schedule').setGoToPage(FormApp
        .PageNavigationType.SUBMIT);;
      form.addMultipleChoiceItem()
        .setTitle('Maintenance')
        .setChoiceValues(['6 monthly', '12 Monthly', 'As required',
          'N/A'])
        .showOtherOption(false)
        .setRequired(true);

      // Equipment - Type Mark
      var typemark = form.addPageBreakItem().setTitle(
        "The Type Mark on the equipment?").setHelpText(
        'Updating equipment type marks').setGoToPage(FormApp
        .PageNavigationType.SUBMIT);;
      form.addTextItem().setTitle("Type Mark").setHelpText(
        '(an identifying Type Mark on the equipment)').setRequired(true);

      // Equipment - Description
      var description = form.addPageBreakItem().setTitle(
        "Describe the equipment").setHelpText(
        'Updating the description of an item of equipment').setGoToPage(
        FormApp.PageNavigationType.SUBMIT);;
      form.addTextItem().setTitle("Description").setHelpText(
        '(Equipment type and specification)').setRequired(true);

      // Equipment - Manufacturer
      var manufacturer = form.addPageBreakItem().setTitle(
          "Name of the Manufacturer").setHelpText(
          'Updating the manufacturer name for an item of equipment')
        .setGoToPage(FormApp.PageNavigationType.SUBMIT);;
      form.addTextItem().setTitle("Manufacturer").setHelpText('(Name)')
        .setRequired(true);

      // Equipment - Model
      var model = form.addPageBreakItem().setTitle("Model Name")
        .setHelpText('Updating the Model Number for an item of equipment')
        .setGoToPage(FormApp.PageNavigationType.SUBMIT);;
      form.addTextItem().setTitle("Model").setHelpText('(Name)')
        .setRequired(true);

      // Equipment - Warranty End Date
      var warrantyenddate = form.addPageBreakItem().setTitle(
          "Warranty End Date").setHelpText(
          'Updating the Warranty End-Date for an item of equipment')
        .setGoToPage(FormApp.PageNavigationType.SUBMIT);;
      form.addDateItem().setTitle("Warranty End Date").setHelpText(
        '(dd/mm/yyyy)').setRequired(true);

      // Equipment - Date Installed
      var dateinstalled = form.addPageBreakItem().setTitle(
          "Installation date").setHelpText(
          'Updating the Installation date for an item of equipment')
        .setGoToPage(FormApp.PageNavigationType.SUBMIT);;
      form.addDateItem().setTitle("Date Installed").setHelpText(
        '(dd/mm/yyyy)').setRequired(true);

    }

    /*
    ///////////////////////////////////////////////////////////////////////////////
    */
    // Step#3
    function setFormdestination() {

      // Update the form's response destination.
      form.setDestination(FormApp.DestinationType.SPREADSHEET, ssID);
    }
    /*
    ///////////////////////////////////////////////////////////////////////////////
    */

    // Step#4
    function UpdateDropDownItems() {

      // build the content of the Drop-down item, together with links to relevant questions/pages
      // This can be run as many times as neccessary.

      var ddid = getdropdownid(); // as an integer
      var plantList = form.getItemById(ddid).asListItem();

      var pagebreaks = form.getItems(FormApp.ItemType.PAGE_BREAK);

      var LR = wsData.getLastRow();
      var dataRange = wsData.getRange(2, 1, LR - 1, 3);
      var values = dataRange.getValues();
      var valLen = values.length;


      var newchoices = [];;

      for (var v = 0; v < valLen; v++) {
        //Logger.log("DEBUG: v:"+v+", field: "+values[v][2]);
        var pb = getpbid(values[v][2]); //as an integer
        // Logger.log(values[v][2]+" = "+pb);

        var pbitem = form.getItemById(pb).asPageBreakItem();

        var dropdown = values[v][0] + " - " + values[v][
        1]; //Concatenate the Unique ID and the Equipment Number
        newchoices.push(plantList.createChoice(dropdown,
        pbitem)); // push create choice onto array

      }
      plantList.setChoices(newchoices);

    }

    function getdropdownid() {
      // Utility
      // get the ID for the Listitem 
      // called by UpdateDropDownItems()

      // list List Items
      var listitems = form.getItems(FormApp.ItemType.LIST);
      var item = listitems[0];
      var listitemid = item.getId().toString();
      //Logger.log(listitemid)
      //Logger.log(item.getId().toString());
      return listitemid;

    }

    function getpbid(title) {

      // Utility
      // get the page break ID; called by UpdateDropDownItems()
      //Logger.log("DEBUG: getpbid - title attribute:"+title) 
      var pagebreaks = form.getItems(FormApp.ItemType.PAGE_BREAK);
      var titles = pagebreaks.map(function(pagebreak) {
        return pagebreak.getTitle();
      });
      //Logger.log("DEBUG: titles = "+titles)
      var pos = titles.indexOf(title);
      //Logger.log("DEBUG: posn = "+pos);
      var pagebreak = pagebreaks[pos];
      //Logger.log("DEBUG: pagebreak:"+pagebreak);
      var pagebreakID = pagebreak.getId();
      //Logger.log("DEBUG: pagebreakID:"+pagebreakID);
      return pagebreakID;

    }

電子表格布局
電子表格截圖


顯示頁面鏈接的下拉菜單
顯示頁面鏈接的下拉菜單


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM