onEdit runs only half of the script - if-statement

I need to use a script that sends data from one sheet to a different one and to clear the values after writing on a specific cell.
I've tried onEdit and it clears the values but doesn't insert them in the second sheet. This is the code I have so far:
function onEdit(e) {
if (e.range.getA1Notation() == "F6"){
//Copiar los datos originales
var ss1 = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss1.getSheetByName("Hoja 1");
var A = sheet1.getRange("B5").getValues();
var B = sheet1.getRange("F5").getValues();
var C = sheet1.getRange("A8:F22").getValues();
//Borrar valores de la hoja de origen después de copiar
var borrar = sheet1.getRange("B5").clearContent();
var borrar = sheet1.getRange("F6").clearContent();
var borrar = sheet1.getRange("A8:F22").clearContent();
//Spreadsheet en la que voy a copiar lo anterior
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1zF84h_gR0zHPqwobYyuOQlo50L2ktpZr2e4orMNtqE8/edit#gid=382646794');
var sheet = ss.getSheetByName("PEDIDOS SIN ORDENAR");
var lastRow = sheet.getLastRow() + 1;
//Insertar los valores
var destRange = sheet.getRange(lastRow, 1, A.length, A[0].length).setValues(A);
var destRange = sheet.getRange(lastRow, 2, B.length, B[0].length).setValues(B);
var destRange = sheet.getRange(lastRow, 3, C.length, C[0].length).setValues(C);
}}
If I change the name of the code and don't condition it to the content of cell F6, then the code runs completely. For that reason I tried to use a button, which works perfetly fine in PC but I need it to work also in mobile devices and buttons don't work with Android.
My last try was:
function Enviar() {
//if (e.range.getA1Notation() == "F6"){
//Copiar los datos originales
var ss1 = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss1.getSheetByName("Hoja 1");
var A = sheet1.getRange("B5").getValues();
var B = sheet1.getRange("F5").getValues();
var C = sheet1.getRange("A8:F22").getValues();
//Borrar valores de la hoja de origen después de copiar
var borrar = sheet1.getRange("B5").clearContent();
var borrar = sheet1.getRange("F6").clearContent();
var borrar = sheet1.getRange("A8:F22").clearContent();
var D = sheet1.getRange("F6").getValues()
if (D == "SI"){
//Spreadsheet en la que voy a copiar lo anterior
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1zF84h_gR0zHPqwobYyuOQlo50L2ktpZr2e4orMNtqE8/edit#gid=382646794');
var sheet = ss.getSheetByName("PEDIDOS SIN ORDENAR");
var lastRow = sheet.getLastRow() + 1;
//Insertar los valores
var destRange = sheet.getRange(lastRow, 1, A.length, A[0].length).setValues(A);
var destRange = sheet.getRange(lastRow, 2, B.length, B[0].length).setValues(B);
var destRange = sheet.getRange(lastRow, 3, C.length, C[0].length).setValues(C);
}}
This last try doesn't seem to do anything at all.
None of my tries shows error, the script runs but doesn't give the expected results.
I don't know what else I could do. Please I need some help.

function Enviar(e) {
//Currently this function runs for any edit of any sheet you should consider limiting it to only the sheet and cell range that you desire
var ss1=SpreadsheetApp.getActiveSpreadsheet();
var sh1=e.source.getSheetByName("Hoja 1");
var A=sh1.getRange("B5").getValue();//single value
var B=sh1.getRange("F5").getValue();//single value
var C=sh1.getRange("A8:F22").getValues();//2D array
var borrar=sh1.getRange("B5").clearContent();
var borrar=sh1.getRange("F6").clearContent();
var borrar=sh1.getRange("A8:F22").clearContent();
var D=sh1.getRange("F6").getValue()
if (D=="SI"){
var ss=SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1zF84h_gR0zHPqwobYyuOQlo50L2ktpZr2e4orMNtqE8/edit#gid=382646794');
var sh=ss.getSheetByName("PEDIDOS SIN ORDENAR");
var lastRow=sh.getLastRow() + 1;
var destRange=sh.getRange(lastRow,1).setValue(A);//single value
var destRange=sh.getRange(lastRow,2).setValue(B);//single value
var destRange=sh.getRange(lastRow, 3,C.length,C[0].length).setValues(C);//2D array
}
}

Related

How to display total correct in measure

I'm trying to compare difference between years in sales but I'm having the following issue:
I have this:
Valor Actual = -CALCULATE(SUM(Apuntes_Resultado[Total Valor]), Apuntes_Resultado[IDEscenario]=1)
Total Valor Previo =
VAR SubgrupoFilter = ISFILTERED(TCuentas[SubGrupo])
VAR TipoCuentaFilter = ISFILTERED(TTipoCuenta[IDTipoCuenta])
VAR Variablefilter = OR(SubgrupoFilter,TipoCuentaFilter)
VAR Resultado = IF(Variablefilter, [Valor Actual], [ActualAjust])
RETURN
Resultado
I use the above code to have this measure
`
Total Valor Final =
VAR IDVistaDetalle = SELECTEDVALUE(TTipoCuenta[Vista Detalle])
VAR IDDetalle = SELECTEDVALUE(TTipoCuenta[Detalle])
VAR IDDetalleVisible = ISFILTERED(TCuentas[SubGrupo])
VAR Resultado = SWITCH(TRUE(),IDDetalleVisible=TRUE() && IDDetalle = 0, BLANK(),
IDVistaDetalle = 1, [Total Valor Previo],
IDVistaDetalle = 2, [Valor Acumulado])
RETURN Resultado`
this works properly. But i'm trying to normalize this values with laboral day's between years.
To this I have created the following column in my date table:
`Laboral Day =
VAR EsFinDeSemana = Dates[Number Day] IN {7}
VAR EsFestivo =
RELATED(TablaFestivos[Fecha])
RETURN
IF (EsFestivo || EsFinDeSemana,0,1)`
It works fine. Shows properly laboral days and holidays
After that, I'm using the follow measure to calculate the values adjusted by year
`AdjustYear = var total =CALCULATE([Total Valor Final], SAMEPERIODLASTYEAR(Dates[Date]))
var LBCY= CALCULATE(SUMX(Dates,Dates[Laboral Day]))
var PYLB= CALCULATE(SUMX(Dates,Dates[Laboral Day]),SAMEPERIODLASTYEAR(Dates[Date]))
return - DIVIDE(total, PYLB)*LBCY //value from previousyear/PYlaboraldays * CYlaboraldays
`
This is a sample of the result:
as you can see, it is taking the same total for two columns but values are different in rows.....
Totals for 2022 and 2021 are ok, laboral days are okey but B 2021 ajus is taking the same total of A 2021
I'm using my date table to filter by months.
Any help?
myMeasure=
VAR myTbl =
Addcolumns(
Summarize(
Dates
,Dates[yearMonth]
)
,"total",[AdjustYear]
)
RETURN
SUMX(myTbl ,[total])
OR
myMeasure=
VAR myTbl =
Addcolumns(
VALUES(Dates[yearMonth])
,"total",[AdjustYear]
)
RETURN
SUMX(myTbl ,[total])
OR
myMeasure=
VAR myTbl =
Addcolumns(
VALUES(Dates[Month]) -- the same column that you use in the matrix
,"total",[AdjustYear]
)
RETURN
SUMX(myTbl ,[total])

Problem customize the height of column bar

The column bar is too small. And I couldn't adjust their height. The screen shot is attached here: https://prnt.sc/p09hj9.
I have tried all the methods of column series at https://www.amcharts.com/docs/v4/reference/columnseries/.
am4core.ready(function() {
// Create chart instance
var chart = am4core.create("historical_monthly_chart_range", am4charts.XYChart);
// Push data into the charts
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
var series = chart.series.push(new am4charts.LineSeries());
series.name = "Price Range";
valueAxis.title.text = 'Price (S$ psf)';
series.dataFields.dateX = "date";
series.dataFields.openValueY = "min";
series.dataFields.valueY = "max";
series.tooltipText = "{date} \n Maximum: {max} \n Average: {average} \n Minimum: {min} \n Volume: {value}";
// Setting the appearance
series.tooltip.background.cornerRadius = 20;
series.tooltip.background.strokeOpacity = 0;
series.tooltip.pointerOrientation = "vertical";
series.tooltip.label.minWidth = 40;
series.tooltip.label.minHeight = 40;
series.tooltip.label.textAlign = "left";
series.tooltip.label.textValign = "middle";
series.fillOpacity = 0.5;
series.tensionX = 0.8;
series.fill = am4core.color("#697e69");
var series2 = chart.series.push(new am4charts.LineSeries());
series2.name = "Minimum Price";
series2.dataFields.dateX = "date";
series2.dataFields.valueY = "min";
series2.stroke = am4core.color("#697e69");
series2.tensionX = 0.8;
var series_average = chart.series.push(new am4charts.LineSeries());
series_average.name = "Average Price";
series_average.dataFields.valueY = "average";
series_average.dataFields.dateX = "date";
series_average.stroke = am4core.color("#000");
/* Bar chart series */
var barSeries = chart.series.push(new am4charts.ColumnSeries());
barSeries.dataFields.valueY = "value";
barSeries.dataFields.dateX = "date";
barSeries.fill = am4core.color("#000");
barSeries.columns.width = am4core.percent(60);
chart.cursor = new am4charts.XYCursor();
chart.cursor.xAxis = dateAxis;
chart.legend = new am4charts.Legend();
});
There is a bounty on this issue from AM charts however one workaround can be using scrollbar in Y axis like this following:
chart.scrollbarY = new am4core.Scrollbar();
This is not the best solution i agree but you can use it to slightly zoom with the buttons and scale and see
let me know if it works!

Apex Interactive Grid how to retrieve a specific record

I am retrieving my grid data using:
var ig$ = apex.region("myGrid1").widget(),
view = ig$.interactiveGrid("getCurrentView");
Now I want to check for a specific record based on 2 columns: id1 and id2 where id1 = 1 and id2 = 7
How can I do that with javascript?
You can iterate for each record like this:
//"myGrid1" should be the static id of the IG region
var widget = apex.region('myGrid1').widget();
var grid = widget.interactiveGrid('getViews','grid');
var model = grid.model;
var results = [];
model.forEach(function(r) {
var record = r;
//the name of the columns should be ID1 and ID2, if not
//make the necessary changes using "_" to represent "space"
var value1 = model.getValue(record,'ID1');
var value2 = model.getValue(record,'ID2');
if(value1 == 1 && value2 == 7) {
results.push(record);
}
})
console.log(results);
To test this code, execute it on console.
To start the console on chrome just press F12
good luck.

iOS-Charts xAxis Labels cut off

I am using iOS-Charts to show a horizontal bar chart.
The x-Axis labels on the left are cut-off.
Only when I double tap on the chart, the correct sizing appears to happen and the labels are not cut off anymore.
Here's the code I'm using
func setChart(_ dataPoints: [(String,Int)], chart: HorizontalBarChartView) {
chart.noDataText = "No data available."
var dataEntries: [BarChartDataEntry] = []
let maxNumberEntries = dataPoints.count
var xAxisLabel: [String] = []
var counter:Int = maxNumberEntries-1
for _ in 0..<maxNumberEntries {
let dataEntry = BarChartDataEntry(x: Double(counter), yValues: [Double(dataPoints[counter].1)], label: dataPoints[counter].0)
dataEntries.append(dataEntry)
xAxisLabel.append(dataPoints[counter].0)
counter -= 1
}
xAxisLabel = xAxisLabel.reversed()
let chartDataSet = BarChartDataSet(values: dataEntries, label: "")
let chartData = BarChartData(dataSet: chartDataSet)
chart.data = chartData
chart.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
// disable zoom of chart
chart.pinchZoomEnabled = false
chart.scaleXEnabled = false
chart.scaleYEnabled = false
chart.chartDescription?.text = ""
chart.legend.enabled = false
// disable selection of bars
chartDataSet.highlightEnabled = false
chartDataSet.valueFont = NSUIFont.systemFont(ofSize: 10)
let numberFormatter = ValueFormatter()
chartData.setValueFormatter(numberFormatter)
// specify the width each bar should have
let barWidth = 0.8
chartData.barWidth = barWidth
let formato:BarChartFormatter = BarChartFormatter()
formato.strings = xAxisLabel
let xaxis:XAxis = XAxis()
_ = formato.stringForValue(Double(1), axis: xaxis)
xaxis.valueFormatter = formato
chart.xAxis.valueFormatter = xaxis.valueFormatter
let xAxis = chart.xAxis
xAxis.labelPosition = XAxis.LabelPosition.bottom // label at bottom
xAxis.drawGridLinesEnabled = false
xAxis.granularity = 1.0
xAxis.labelCount = maxNumberEntries
xAxis.labelRotationAngle = 0
// Don't show other axis
let leftAxis = chart.leftAxis
leftAxis.enabled = false
let rightAxis = chart.rightAxis
rightAxis.enabled = false
}
Any idea how to fix that?
Screenshots:
cut-off xAxis labels
after double tap the labels are not cut-off anymore
If you values are cut off even after notifyDataSetChanged, try offseting it like this:
mChart.extraTopOffset = 20
I solved this issue by calling
chart.fitScreen()
for every bar chart once all the data is passed.
HorizontalBarChart label cut issue solved you just only put this code in your chart setup:
chart.extraRightOffset = 30
If anyone has been struggling and answer did not help, once you set a chart with a new data, do not forget to call notifyDataSetChanged on chart, otherwise labels will be cut. That was my case.

Removing tabs and newlines with regular expressions issue

Regex: remove TAB \t tab var regex = /\s[A-Za-z]+/g do not work
selectFirstEmptyRow function () {
var ss = SpreadsheetApp.openByUrl ("https://docs.google.com/spreadsheets/d/---ID-----edit#gid=395019283");
var date = Utilities.formatDate(new Date() ss.getSpreadsheetTimeZone(), "d" + "- 0" + "M" + "-" + "y");
var sheet = ss.getSheetByName(date);
var regex = /[^0-9]*/g; // extract the string before digital channel
var doc = DocumentApp.getActiveDocument().getText()
var result = RegExp.exec(doc);
// * Extract white \ s match any white space character [\ r \ n \ t \ f]
var regex = /\s[A-Za-z]+/g; // extract the spaces in front of and behind "Name Surname"
RegExp.exec var result = (result);
sheet.setActiveSelection(sheet getRange ("B" + getFirstEmptyRowWholeRow())).setValue(result);
Logger.log(result.getText);
I can not remove a tab \t and newlines \n with the syntax
var regex = /\s[A-Za-z]+/g;
There remains a line preceding the string "Name Surname" when I insert it into the Spreadsheet.
After analysis it appears that the concerns are the tabs \t, it is not deleted.
I try to extract from a "text document" a string (which is always at the top of the document until the first numerical chain) and put in a "spreadsheet document 'Spreadsheet at the site of the first box vacuum column "B".
The handling of this string in the same "text document" did not cause me any problem for the update of age with the syntax
var regex = /[^0-9]*/g; // extract the string before a digit
The string from the document:
var str = '\n\n\n\Surname NAME\n34 Years\n\n......... .. "
Here is the complete script:
/// var result = result.replace(/^[\r\n]+|.|[\r\n]+$/g, "");// extrait les espaces devant et derriere Nom Prenom GAS D'ONT WORK
///// Facturer Acte ////
function FacturerActe() {
var regexp = /[^0-9]*/g ;// extrait la chaine de caractère avant la chaine numérique
var doc = DocumentApp.getActiveDocument().getText();
var result = regexp.exec(doc);
var PrenomNom = new RegExp(result,"gm");
Logger.log(PrenomNom.getText);
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
ss.setActiveSheet(sheet);
var cell = sheet.getRange("A40");
cell.setNote("Aujourd'hui est un nouveau jour ! Nous sommes le :"+date);
selectFirstEmptyRow(); // Place le curseur sur la premiere ligne Vide de la Colonne "B"
}
//* Placez le curseur de l'utilisateur actuel dans la première cellule de la première ligne vide.
//*
function selectFirstEmptyRow() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
var regexp = /[^0-9]*/g ;// extrait la chaine de caractère avant la chaine numérique
var doc = DocumentApp.getActiveDocument().getText();
var result = regexp.exec(doc);
var regexp = /\s[A-Z a-z]+/g ;// extrait les espaces devant et derriere Nom Prenom
//* Extrait les blancs
var result = regexp.exec(result);
/// var result = result.replace(/^[\r\n]+|\.|[\r\n]+$/g, "");// extrait les espaces devant et derriere Nom Prenom GAS D'ONT WORK
sheet . setActiveSelection (sheet.getRange("B" + getFirstEmptyRowWholeRow())).setValue(result);
Logger.log(result.getText);
}
/**
* " Trouve la première ligne vide la Colonne "B" " de checker de Mogsdad.
*/
function getFirstEmptyRowWholeRow () {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
var range = sheet.getDataRange();
var values = range.getValues();
var row = 1 ;
for (var row = 1; row < values.length; row ++) {
if (!values[ row ].join("")) break ;
}
return (row + 1);
}
///// Fin Facturer Acte ////
As per Using regular expressions to search for data in your spreadsheet, you can match any newline and tab using [\t\r\n] pattern. Since you have more than one at a stretch, you should add a quantificator +. Also, since you are looking to capture 2 lines, you should add the [\t\r\n]+ to the pattern, too.
This will let you capture the 2 lines with Name and Age in between the newlines:
[\r\n\t]+(.+[\r\n\t]+.+)[\t\r\n]+
And you can later remove the newline characters:
var result = str.replace(/[\r\n\t]+(.+[\r\n\t]+.+)[\t\r\n]+/, '$1');
Here is what it looks like on regex101.com.
alert("'" + "\n\t\n\nNew line\n\t\nSecond 34 line\n\t\n....".replace(/[\r\n\t]+(.+[\r\n\t]+.+)[\t\r\n]+/, '$1') + "'")