Check only a range of checkboxes - excel

I have this code with works brilliantly for me. I just need a small alteration to be able to select a range of cells as well, meaning:
Either H15-H17 or H22 or H26 in the attached image.enter image description here
the code I have is the following:
var CHECKBOX_CELLS = ["H15", "H22", "H26"];
function onEdit(e) {
var range = e.range;
var checkboxIndex = CHECKBOX_CELLS.indexOf(range.getA1Notation());
if (checkboxIndex > -1 && range.getValue() == true) {
var sheet = range.getSheet();
for (var i=0; i<CHECKBOX_CELLS.length; i++) {
if (i==checkboxIndex) continue;
sheet.getRange(CHECKBOX_CELLS[i]).setValue(false);
}
}
}

Related

How can i read a specified value of cell and convert a file from excel into spreadsheet?

In here I am trying to make a checking where if the "STATUS" column is 'NEW FILE', then i would like to perform a file conversation from excel to spreadsheet.
For the "STATUS" column i created an IF-ELSE statement,
if (row[0] === "last week file") {
newValues.push(['OLD FILE'])
}
else{
newValues.push(['NEW FILE'])
ConvertFiles()
return
}
Therefore, I am making a check through the "STATUS", if the status column is empty it will be written as 'NEW FILE', and then it will perform an file conversion from excel to spreadsheet since i already called the method inside it.
Here is the EDITED version code of the file conversion:
function ConvertFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 5); // get A2:E6 range
var data = range.getValues(); // get A2:E6 data
for(var i = 0; i < data.length; i++){
if(data[i][2] == " "){
for( var r= 2;r < sheet.getLastRow()+1; r++){
var fileId = sheet.getRange(r,1).getValue();
var folderID = sheet.getRange(r,2).getValue(); //for destination folder
var files = DriveApp.getFileById(fileId);
var name = files.getName().split('.')[0];
var blob = files.getBlob();
var newFile = {
title: name.replace('_converted','') + '_converted',
parents: [{id: folderID}] };
var destinationFolderId = DriveApp.getFolderById(folderID);
var existingFiles = destinationFolderId.getFilesByName(newFile.title);
while(existingFiles.hasNext()) {
var oldConvertedFileWithSameNameID = existingFiles.next().getId();
Drive.Files.remove(oldConvertedFileWithSameNameID,{supportsAllDrives: true});
}
var newFileID = Drive.Files.insert(newFile, blob, { convert: true,supportsAllDrives: true }).id;
Logger.log(newFileID);
var Url = "https://drive.google.com/open?id=" + newFileID;
//sheet.getRange(r,4).setValue(newFileID);
//sheet.getRange(r,5).setValue(Url);
}
sheet.getRange(i+2,4).setValue(newFileID); //set value in column D
sheet.getRange(i+2,5).setValue(Url); //set value in column E
}
}
}
The error that i am facing is, when i call the method ConvertFiles() inside the if statement, the conversion happens from row 2 until 6 CONTINOUSLY without stopping as shown in sample in red circle.
I only wanted to make conversion on the "NEW FILES" only which will be on row 5 and 6.
How can i make a conversion on the selected/specified row?
It would be more efficient if you obtain all the values in your Sheet, loop the 2D array the getValues() method will return and add an if statement that will only process new files.
Example:
Here in my example below I created a script that will only process rows that have a blank value for the status column.
Code:
function ConvertFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 5); // get A2:E6 range
var data = range.getValues(); // get A2:E6 data
/*the content of data is 2D array,
each sub array represent rows in your table*/
for(var i = 0; i < data.length; i++){
if(data[i][2] == ""){ //the 2 in [i][2] represent the value of C column in sheet
//Add your file conversion code here
sheet.getRange(i+2,4).setValue("Test only"); //set value in column D
sheet.getRange(i+2,5).setValue("Test only"); //set value in column E
}
}
}
Data:
Output:
References:
Sheet.getRange(row, column, numRows, numColumns)
Range.getValues()
Range.setValue(value)
EDIT:
The value of data variable in the code below is a 2D array containing all the data in the range provided. In your example, it is the data of A2:E6.
Example output:
[
[fileId1,folderId1,Status1,,],
[fileId2,folderId2,Status2,,],
[fileId3,folderId3,Status3,,],
[fileId4,folderId4,,,],
[fileId5,folderId5,,,],
]
The for loop will access each sub array per iteration and since we already knew the position of our target data (fileID and folderID) we don't need to create another for loop to access it, instead we just specify the index on which the data is located. data[i][0] for file id and data[i][1] for folder id. The if(data[i][2] == "") is added to check if the column C of each row is empty and ignore the one with data.
Code:
function ConvertFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 5);
var data = range.getValues();
for(var i = 0; i < data.length; i++){
if(data[i][2] == ""){
var fileId = data[i][0];
var folderID = data[i][1];
var files = DriveApp.getFileById(fileId);
var name = files.getName().split('.')[0];
var blob = files.getBlob();
var newFile = {
title: name.replace('_converted','') + '_converted',
parents: [{id: folderID}] };
var destinationFolderId = DriveApp.getFolderById(folderID);
var existingFiles = destinationFolderId.getFilesByName(newFile.title);
while(existingFiles.hasNext()) {
var oldConvertedFileWithSameNameID = existingFiles.next().getId();
Drive.Files.remove(oldConvertedFileWithSameNameID,{supportsAllDrives: true});
}
var newFileID = Drive.Files.insert(newFile, blob, { convert: true,supportsAllDrives: true }).id;
var Url = "https://drive.google.com/open?id=" + newFileID;
sheet.getRange(i+2,4).setValue(newFileID);
sheet.getRange(i+2,5).setValue(Url);
}
}
}

Google Sheet custom function not returning string

I am new to Google Sheet scripting.
I am writing a code to strip the sixth components from a long text that is based on a naming convention. The text have 6 parts all separated by an underscore. However, my code is not returning anything
function RetailerStrip(account) {
var count = 0;
var retname = "";
var retcount = 0;
for(var i = 0, len = account.length; i < len; i++) {
if (account[i] =="_") {
++count;
}
if (count == 5) {
retname[retcount]= account[i];
++retcount;
}
}
return retname;
}
I then call this function from sheet as below
=RetailerStrip("abc_def_ghi_jkl_mno_pqr")
When I tried to declare 'retname' as an array the function did return the required text (fifth component) but the text was spread across multiple cells with on character in each cell, and not as a single string in one cell
var retname = [];
Please help
You could try this:
function RetailerStrip(str) { return str.split('_')[5]; }
The split() method creates an array.
But if you prefer to stick with the string-iteration method, you could use this:
function RetailerStrip(account) {
var count = 0;
var retname = []; // Array
var retcount = 0;
for (var i = 0, len = account.length; i < len; i++) {
if (account[i] =="_") {
++count;
}
if (count == 4) {
retname[retcount]= account[i];
++retcount;
}
}
retname.shift(); // To get rid of the underscore from the array
var retnameString = retname.join(''); // To convert the array to a string
return retnameString;
}

Table search on a filtered table?

I have a search function that searches a table with 3 columns. I have now implemented a dropdown that filters the table based on a place but when using the search function, it searches the whole table not the items that are left from the dropdown. Below is my function to filter the table but is there anything I can add to filter based on what is being shown and not what the table has as a whole?
Using HTML + JS
function filterTable(event) {
var filter = event.target.value;
var rows = document.querySelector("#rosterTable tbody").rows;
for (var i = 0; i < rows.length; i++) {
var firstCol = rows[i].cells[0].textContent;
var fourthCol = rows[i].cells[3].textContent;
var fifthCol = rows[i].cells[4].textContent;
if (firstCol.indexOf(filter) > -1 || fourthCol.indexOf(filter) > -1 || fifthCol.indexOf(filter) > -1) {
rows[i].style.display = "";
} else {
rows[i].style.display = "none";
}
}
}
document.querySelector('#myInput').addEventListener('keyup', filterTable, false);

Get filename from url google sheet

I have a problem.
How to get the filename from the url?
enter image description here
I wouldn't normally do this since you haven't shown us what you've tried, but I'm feeling generous.
This function should work for you. (Note that you'll need to grant permissions for it to run.)
function getFileNames() {
var sheet = SpreadsheetApp.getActive().getSheetByName("Get_File_Name");
var links = sheet.getRange("A2:A").getValues();
var filenames = [];
for (var i = 0; i < links.length; i++) {
var url = links[i][0];
if (url != "") {
var filename = SpreadsheetApp.openByUrl(links[i][0]).getName();
filenames.push([filename]);
}
}
var startRow = 2; // print in row 2 since row 1 is the header row
var fileNameColumn = 2; // Column B = column 2
var destination = sheet.getRange(startRow, fileNameColumn, filenames.length, filenames[0].length);
destination.setValues(filenames);
}
Another way
function getFileNames() {
var driveApp = DriveApp;
// SET THE SHEET HERE
var sheet = SpreadsheetApp.getActive().getSheetByName("Sheet1");
//SET THE URL LINK COLUMN HERE : From row 2 since row 1 is the header row till last row
var links = sheet.getRange("P2:P").getValues();
var filenames = [];
for (var i = 0; i < links.length; i++) {
var fileId = getIdFromUrl(links[i][0]);
if (fileId != "" && fileId != null) {
var getfile = DriveApp.getFileById(fileId);
var filename = getfile.getName();
Logger.log(filename);
filenames.push([filename]);
} else {
filenames.push([""]);
}
}
// SET STARTING ROW TO PRINT: From row 2 since row 1 is the header row
var startRow = 2;
// SET WHICH COLUMN TO PRINT : Column A = column 1 / Column B = column 2
// MAKE SURE THE SHEET LAST COLUMN HEADER IS FILLED + 1 (next column)
var fileNameColumn = sheet.getLastColumn() + 1;
var destination = sheet.getRange(startRow, fileNameColumn, filenames.length, filenames[0].length);
destination.setValues(filenames);
}
function getIdFromUrl(url) { return url.match(/[-\w]{25,}/); }
You can create a custom function in spreadsheets like this.
function getSSName(name) {
var ss = SpreadsheetApp.openByUrl(url);
return ss.getName();
}

Creating a attachment from Google sheet in ms Excel format via Google script

Is it possible to create an Excel format file from a Google sheet using Google script, so that it can be added as an attachment to an email?
I've got a code that takes columns with certain names (e.g. A, C, F) and turns them into a new sheet (on createCustomStatusTable() function).
https://docs.google.com/spreadsheets/d/1fZ0JMYjoIrfPIxFBVgDNU0x5X0ll201ZCU-lcaTwwcI/edit?usp=sharing
var expected = ['A','C','F'];
var newSpreadSheet = SpreadsheetApp.getActiveSheet();
var tableLastRow = newSpreadSheet.getLastRow();
var tablelastColumn = newSpreadSheet.getLastColumn();
var values = newSpreadSheet.getRange(1, 1, tableLastRow, tablelastColumn).getValues();
var rangeToCopy = [];
function in_array(value, array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == value) return true;
}
return false;;
};
function columnsCount() {
var count = 1;
for (var i = 0; i < SpreadsheetApp.getActiveSheet().getLastColumn(); i++) {
if (in_array(values[0][i],expected))
count++;
}
return count;
};
function returnRange() {
for (var i = 1; i < SpreadsheetApp.getActiveSheet().getLastColumn()+1; i++) {
if (in_array(values[0][i-1],expected)) {
rangeToCopy.push(newSpreadSheet.getRange(1, i, newSpreadSheet.getMaxRows()));
};
};
return rangeToCopy;
};
function createCustomStatusTable() {
var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Target');
for (var i = 1; i < columnsCount(); i++) {
returnRange()[i-1].copyTo(targetSheet.getRange(1,i));
};
};
Thank you in advance for any help
You can create an EXCEL type file with DriveApp:
The problem is, that the content must be a string. And I haven't tested for a way to make that work.
I know this doesn't answer your question. Hopefully someone knows for sure how to create an EXCEL file from a Google Sheet.

Resources