Pasted below is my script. I am copying a particular range of values from a sheet called "TalukaName" and copying it into "UserInterface!I2:I" cells. When I try to copy the values from the array into a Range, i get the error
Cannot convert Array to Object
at the line where I setValues of the Range. All my values that need to be copied into the Range are String values. Hence I added double quotes while creating array. Can anybody please help as to what is going wrong?
function test(){
var spreadsheet = SpreadsheetApp.getActive();
var ss = spreadsheet.setActiveSheet(spreadsheet.getSheetByName('UserInterface'), true);
var count = ss.getRange("H2").setFormula('=countif(TalukaName!B:B,UserInterface!C2)').getValue();
var DistrictName = ss.getRange('C2').getValue();
var matchindex = ss.getRange('H3').setFormula('=match(C2,TalukaName!B:B,0)').getValue();
var indexvalue = ss.getRange('H4').setFormula('=index(TalukaName!B:B,H3)').getValue();
var array = [];
var ssTaluka = spreadsheet.setActiveSheet(spreadsheet.getSheetByName('TalukaName'), true);
var range = ssTaluka.getDataRange();
var data = range.getValues();
for (var i = 0; i < count; i++) {
array[i]= '"' + data[i+matchindex-1][0] + '"';
}
ss.getRange('I2:I').setValues(array);
}
Related
I want to move filtered data from one sheet to a different sheet.
I can do this for a single filtered value ex: Money but I want to filter on multiple values from an array ex: ["Money", "Society", "Impacts"]
I can not figure out how to loop through the filterValues array and collect all the values from the different filterValues.
I just get the filtered values of rawData for the last value in filterValues
I can do this a different way but I am trying to get a better understanding of filtering
function myFunction() {
var filterValues = ["Money", "Society"]; //filter values.
var col = 5; // column "E".
var sheetName = "Elements";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getSheetByName(sheetName);
var rng = sht.getDataRange();
var rawData = rng.getDisplayValues();
var out = rawData.filter(dataFilter);
function dataFilter(arr) {
return arr[col-1]== filterValues;
}
const osh=SpreadsheetApp.getActive().getSheetByName("A");
osh.clear();
osh.getRange(1,1,out.length,out[0].length).setValues(out);
};
tried this
for (var i = 0; i <= filterValues.length-1; i++) {
var out = rawData.filter(dataFilter);
function dataFilter(arr) {
return arr[col-1]== filterValues[i];
}
}
You can use array.includes() to check if the current row column e value is listed in your filterValues for your array filter function.
Sample code:
function myFunction() {
var filterValues = ["Money", "Society"]; //filter values.
var col = 5; // column "E".
var sheetName = "Elements";
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sht = ss.getSheetByName(sheetName);
var rng = sht.getDataRange();
var rawData = rng.getDisplayValues();
var out = rawData.filter(dataFilter);
function dataFilter(arr) {
return filterValues.includes(arr[col-1]);
}
Logger.log(out);
const osh=SpreadsheetApp.getActive().getSheetByName("A");
osh.clear();
osh.getRange(1,1,out.length,out[0].length).setValues(out);
};
What it does?
Get the data range values
Filter the 2-d array values if column E value was found in your filterValues array.
Write the filtered array on the destination sheet.
Output:
Source Sheet: Elements
Destination Sheet: A
You can just use a basic filter function combined with array syntax like you'd use in SumProduct. Example: =filter(List!A:A,(List!A:A="Society")+(List!A:A="Money")).
I don't think you'd need to use Google App Scripts. See this spreadsheet
I've got this working code that gets the lat/long combo from an address.
function testgeocode(){
var responses = SpreadsheetApp.openById('###').getSheetByName('Form Responses');
var range = responses.getRange('AD2:AD');
var addresses = range.getValues();
var row = range.getRow();
var column = range.getColumn();
var destination = new Array();
destination[0] = 31; // column + 1;
destination[1] = 32; // column + 2;
var geocoder = Maps.newGeocoder();
var count = range.getHeight();
for(i in addresses) {
var location = geocoder.geocode(addresses[i]).results[0].geometry.location;
responses.getRange(row, destination[0]).setValue(location.lat);
responses.getRange(row++, destination[1]).setValue(location.lng);
Utilities.sleep(200);
}
}
I'm having difficulty modifying it so that the lat/long combo is outputted into one column with the format 'lat,long'.
Explanation / Issues:
First of all, your code is quite inefficient. The reason for that is because you are using getRange and setValue inside a for loop but also two times per iteration. As it is explained in the best practices, the proper way to achieve your goal is to store the values into an empty array and then use setValues outside the for loop to set them to your sheet.
The other modification is already mentioned in the other answer. You want to concatenate location.lat, location.lng separated by a comma.
Solution:
function testgeocode(){
var responses = SpreadsheetApp.openById('###').getSheetByName('Form Responses');
var range = responses.getRange('AD2:AD');
var addresses = range.getValues();
var row = range.getRow();
var column = range.getColumn();
var destination = new Array();
destination[0] = 31; // column + 1;
destination[1] = 32; // column + 2;
var geocoder = Maps.newGeocoder();
var count = range.getHeight();
var data = [];
for(i in addresses) {
var location = geocoder.geocode(addresses[i]).results[0].geometry.location;
data.push([location.lat + ',' + location.lng]) // new code
Utilities.sleep(200);
}
responses.getRange(2,destination[0],data.length,1).setValues(data); // new code
}
From what I understood, currently you're getting the latitude and longitude values and writing them to different cells, but you want to have them both in a single cell, separated by a comma.
If that's the case, then you can make the following changes.
From:
var location = geocoder.geocode(addresses[i]).results[0].geometry.location;
responses.getRange(row, destination[0]).setValue(location.lat);
responses.getRange(row++, destination[1]).setValue(location.lng);
To:
var location = geocoder.geocode(addresses[i]).results[0].geometry.location;
responses.getRange(row, destination[0]).setValue(location.lat + ',' + location.lng);
You can adjust the parameters of getRange() if you want to write it to a different cell.
Hello I made this script to export the data from a column to a .txt on my google drive
function createOrAppendFile() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var range = sheet.getRange('G3:G50');
var rows = range.getValues();
var fileName="test.txt";
var folderName="Videos";
var data = rows.splice(0);
var str = data.map(function(e) {return e.join()}).join("\n");
var content = str;
// get list of folders with matching name
var folderList = DriveApp.getFoldersByName(folderName);
if (folderList.hasNext()) {
// found matching folder
var folder = folderList.next();
// search for files with matching name
var fileList = folder.getFilesByName(fileName);
if (fileList.hasNext()) {
// found matching file - append text
var file = fileList.next();
var combinedContent = content;
file.setContent(combinedContent);
}
else {
// file not found - create new
folder.createFile(fileName, content);
}
}
}
The problem is that when I export the data its exporting with the empty lines and on the .txt shows up empty lines that i dont want to have, how i can make it? So I only export the lines that have content.
This is what the .txt looks like https://i.stack.imgur.com/wplZL.png
I think that the reason of your issue might be due to sheet.getRange('G3:G50'). In this case, even when the empty rows are included below the data range in the range of G3:G50, range.getValues() retrieves all rows of G3:G50. If you want to retrieve the values with the data range, how about the following modification?
From:
var range = sheet.getRange('G3:G50');
To:
var range = sheet.getRange('G3:G' + sheet.getLastRow());
And, when you want to remove all empty rows of the column "G", you can also use the following modification.
From:
var range = sheet.getRange('G3:G50');
var rows = range.getValues();
To:
var range = sheet.getRange('G3:G' + sheet.getLastRow());
var values = range.getValues().filter(([g]) => g.toString() != "");
References:
getLastRow()
filter()
Trying to copy a range (L2:L9) to another spreadsheet based on a data validation selection (ID #) in a specific cell (G11) on the source spreadsheet.
The ID#s are all in alphanumeric order on the target spreadsheet along row 5, so all I need is to get the column number that corresponds to the choice made in the data validation field.
Before I had to convert the ID#s to Alphanumeric values, I simply had numeric values and the script worked fine. Now I'm having trouble converting the script to work with this modification.
function Submit() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // ss = source spreadsheet
var source_sheet = ss.getActiveSheet();
if (source_sheet.getName() == "Pre-Season CC") {
var SRange = source_sheet.getRange('L2:L9');
var A1Range = SRange.getA1Notation();
var SData = SRange.getValues();
var target = SpreadsheetApp.openById('1MpKdxFyBrVQT3EumePQvtCZpgzcDW5xlYe4B1DKZCA8');
var target_sheet = target.getSheetByName('Pre-Season');
var idNumber = source_sheet.getRange('Pre-Season CC!G11').getValue();
for (var i = 0; i < idNumber.length; i++) {
for (var j = 0; j < idNumber.length;j++){
if (target_sheet[4][j] == idNumber){
Logger.log((j+1))
return j+1;
target_sheet.getRange('B6:B13').offset(0,valueA1 = ss.getRange('Pre-Season!G11').getValue(idNumber)+1).setValues(SData);
}
}
}
}
At that point, I need the data copied from source spreadsheet onto the target spreadsheet in it's designated column, according to the ID#. Please help!
Try below code.
function Submit() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // ss = source spreadsheet
var source_sheet = ss.getActiveSheet();
if (source_sheet.getName() == 'Pre-Season CC') {
// source sheet items
var SData = source_sheet.getRange('L2:L9').getValues();
var idNumber = source_sheet.getRange('Pre-Season CC!G11').getValue();
// target sheet items
var targetSS = SpreadsheetApp.openById('1MpKdxFyBrVQT3EumePQvtCZpgzcDW5xlYe4B1DKZCA8');
var target_sheet = targetSS.getSheetByName('Pre-Season');
// 5 = row where IDs are
var TData = target_sheet.getRange(5, 1, 1, target_sheet.getLastColumn()).getValues()[0];
// column index of #ID in target sheet
var colIndex = TData.indexOf(idNumber) + 1;
// write data in that column, rows from 6 to 13
target_sheet.getRange(6, colIndex, SData.length, 1).setValues(SData);
}
}
I want to execute some code based on the entered value in a cell being in a named range.
I've tried something similar to this but it doesn't seem to be working:
function onEdit() {
var aSheet = SpreadsheetApp.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
var aDatarange = aSheet.getRange(aCell.getRow(),aColumn);
var aData = aDatarange.getValue();
var SomeRange = aSheet.getRangeByName('RangeName');
if (aData in 'SomeRange') {
execute some code
}
}
I'm guessing its the if statement I'm doing incorrectly but I've tried var in range and var = range and neither seem to work.
You need to get the data out of the range, so that the value from the cell can be searched for in the range data. I've added a couple of new variables to your code, and included comments about the new lines of code.
function onEdit() {
var dataAsString,rangeData;
var aSheet = SpreadsheetApp.getActiveSheet();
var aCell = aSheet.getActiveCell();
var aColumn = aCell.getColumn();
var aDatarange = aSheet.getRange(aCell.getRow(),aColumn);
var aData = aDatarange.getValue();
var SomeRange = aSheet.getRangeByName('RangeName');
rangeData = SomeRange.getValues();//Get the values out of the range
dataAsString= rangeData.toString();//Convert the 2D array to a a comma seperated string of values
if (dataAsString.indexOf(aData) !== -1) {//The value of "aData" was found in the data string
//execute some code
}
}