What are the steps to conduct a roll call using Google App Script?

After conducting some research on how to execute a row call using Google Apps Script, I have encountered a slight challenge and would greatly appreciate any assistance with this matter.

This script examines the values in the first column and uses them to rename new tabs.


function newSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var templateSheet = ss.getActiveSheet();
    var sheet1 = ss.getSheetByName("main");
    var getNames = sheet1.getRange("A2:A").getValues().filter(String).toString().split(",");

    for (var i = 0; i < getNames.length; i++) {
        var copy = ss.getSheetByName(getNames[i]);
        if (copy) {
            Logger.log("Sheet already exists");
        } else {
            templateSheet.copyTo(ss).setName(getNames[i]);
            ss.setActiveSheet(ss.getSheetByName(getNames[i]));
            ss.moveActiveSheet(ss.getNumSheets());
        }
    }
}

The image of the sheet can be found here:

https://i.sstatic.net/5CNCb.png

My current challenge lies in copying only the rows with specific data to the newly created tabs/sheets. For example, when creating a tab named Levi, I want only the row containing Levi's data to be copied to that sheet.

Currently, my code duplicates the entire source sheet onto the new tabs/sheets. Any help with refining this functionality will be highly appreciated.

Answer №1

Proposed solution:

To create a new sheet based on a main template, use the function .copyTo in order to copy all content from the main sheet. Retrieve the entire row corresponding to the specified name index.

Approach

Additional filtering is required to obtain the accurate row values for the new sheet. Filter the name column (column A) and iterate through the names to get their respective indices.

(Considering the possibility of gaps in the data, the for loop's index alone may not suffice).

After finding the correct index, increment it by one as Google Spreadsheets start row indexing at 1.

Use the function

.getRange(row, column, numRows, numColumns)
to easily retrieve the desired row. Determine the value for numColumns using the function .getLastColumn().

Subsequently, utilize .appendRow() to insert the row into the newly created sheet with .insertSheet().

Sample Code:

function newSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var templateSheet = ss.getActiveSheet();
    var sheet1 = ss.getSheetByName("main")
    var getNames = sheet1.getRange("A2:A").getValues().filter(String).toString().split(",");

    for (var i = 0; i < getNames.length; i++) {
        var copy = ss.getSheetByName(getNames[i]);
        if (copy) {
            Logger.log("Sheet already exists");
        } else {
            //The copyTo function will copy the entire sheet
            //templateSheet.copyTo(ss).setName(getNames[i]);

            var rowIndex = sheet1.getRange("A:A").getValues().flatMap(value => value[0]).indexOf(getNames[i]) + 1;
            var rowValues = sheet1.getRange(rowIndex, 1, 1, sheet1.getLastColumn()).getValues();
            ss.insertSheet(getNames[i]).appendRow(rowValues[0]);

            ss.setActiveSheet(ss.getSheetByName(getNames[i]));
            ss.moveActiveSheet(ss.getNumSheets());
        }
    }
}

Edit

If there are duplicated names, filter the column and extract the relevant indexes.

Create a set for the getNames variable to eliminate repetitions.

var getNames = [...new Set(sheet1.getRange("A2:A").getValues().filter(String).toString().split(","))];

Map the row indexes to the respective names in column A. Filter by the unique names to obtain the row indexes, then append these rows to the new sheet.

var rowIndexes = sheet1.getRange("A:A").getValues()
                                       .map((value, index) => [value[0], (index + 1)])
                                       .filter(value => value[0] === getNames[i]);
var namedSheet = ss.insertSheet(getNames[i]);
rowIndexes.map(index => {
                 var rowValues = sheet1.getRange(index[1], 1, 1, sheet1.getLastColumn()).getValues();
                 namedSheet.appendRow(rowValues[0]);
});

References:

Class Sheet

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for displaying a list of all files within a folder?

I'm currently working on a project where I have a 'products' directory located in the same folder as my index.html file. My goal is to develop a script that can tally all the jpg files within the 'products' folder and then generate ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Issue with local dependency not being loaded until after a hard refresh in Vue/Vue Router

I'm currently developing a Vue application that utilizes Vue router. I've been attempting to integrate the jscolor script found at here. Essentially, you just need to include the script and apply the jscolor class to an HTML element. I am working ...

Refreshing the current window with the ``Window.location.reload()`` function

I have integrated a map that displays clients using markers. The map I am utilizing is Leaflet with an AngularJS directive. The issue I am facing is that when I initially access the map, it functions correctly. However, when I change routes, all the marke ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

Guidelines for calculating the CRC of binary data using JQuery, javascript, and HTML5

Can you please assist me with the following issue? Issue: I am currently reading file content using the HTML5 FileReaderAPI's ReadAsArrayBuffer function. After storing this buffer in a variable, I now need to compute the CRC (Cyclic Redundancy Check) ...

Sending JSON Data with Javascript Post Request

I've been attempting to send a JSON payload via a JavaScript script, but my webhooks don't seem to recognize the payload no matter what I try. Here is the code that I compiled from various online resources: let xhr = new XMLHttpRequest(); ...

jQuery plugin for uploading multiple files with validation for checking if they are empty or not

I recently downloaded the JQuery Multiple file uploader plugin from this website Before submitting the form, I need to verify whether the file input field is empty or not. <form onsubmit="return validate();"> <input type="file" name="File" class ...

Tips for managing the return value of a PHP function in AJAX requests

Looking for some help with inserting HTML form data using PHP and Ajax. Below is the code I've written: <!DOCTYPE HTML> <html lang="en"> <head><title>Ajax Test</title> <meta charset="utf-8" name="viewport" con ...

CodeIgniter throwing an error with converting Array to String?

Here is the code snippet: Controller File public function view_resume($id) { $this->load->model('ORB_Model'); $data['get_masterData'] = $this->ORB_Model->get_masterData($id); } Model File: public function get_ed ...

Improving User Experience with HTML Form Currency Field: Automatically Formatting Currency to 2 Decimal Places and Setting Maximum Length

Hello there, I am currently facing an issue with the currency auto-formatting in a deposit field on my form. The formatting adds 2 decimal places (for example, when a user types 2500, the field displays 25.00). However, the script I wrote does not seem to ...

Flawed Java Gzip decompression process on .NET platform

I am currently attempting to replicate in .NET an algorithm that was originally coded in Java. However, I am encountering difficulties with the GZIP decompression process. At the end of this post, I have included a hexadecimal string which is converted in ...

AngularJS: Trouble with directive recognizing attribute

I am currently working with a directive called ngAvatar: app.directive('ngAvatar', function() { return { restrict: 'E', replace: true, template: '<img class="avatar-medium" ng-src="{{url}}" />', link: ...

What is the best way to automate a website that has identical buttons with the same class, but different HTML onlick functions?

One of the buttons reads <button class="btn bid-hotel-btn" type="button" onclick="buyNow(0,false)">Beli Sekarang</button> while the other button is <button class="btn bid-hotel-btn" type="button" onclick="buyNow(1,false)">Beli Sekarang ...

The challenge of navigating through $scope

In my Angular view/form, I have an input file element that is being utilized with ng-upload. The code snippet looks like this: <input id="img" type="file" name="image" onchange="angular.element(this).scope().setFile(this)"> <input id="imgname" ty ...

Having trouble with the pagination feature while filtering the list on the vue-paginate node

In my current project, I have integrated pagination using the vue-paginate node. Additionally, I have also implemented filtering functionality using vue-pagination, which is working seamlessly. Everything works as expected when I enter a search term that d ...

Creating a table header that displays the next and previous days using JavaScript

I am currently working on creating a dynamic HTML header using JavaScript to display all week days with dates for the upcoming and previous weeks. When a button is clicked for the next week, the table header should change from this week to next week; simil ...

A React component will consistently display the most recent value of the props passed to

Child Component export class MultiSelectDrawer extends React.Component { componentDidMount(){ window.onpopstate = ()=>{ console.log(this.props.id); } } render() { const {input, id, label, showActionDrawer, toggleActionDrawer, i ...

The function of modal in JavaScript is not working properly

I am encountering a problem with my web page that is running on Wildfly 12. It is a simple Java EE project that I developed in Eclipse Neon. The issue arises when I try to use Bootstrap modals, as every time I attempt to open or use the methods in a JavaSc ...

What is the best way to omit a field from my query if the associated variable is empty?

I need help creating a dynamic MongoDB query function that can handle multiple field values, including cases where some fields may be empty strings. In these instances, I want MongoDB to disregard those parts of the query. Here is my current query functio ...