JavaScript - Separa texto delimitado por barras de columnas y asociarlas

 
Vista:
sin imagen de perfil
Val: 6
Ha aumentado su posición en 4 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Separa texto delimitado por barras de columnas y asociarlas

Publicado por Salva (2 intervenciones) el 12/05/2021 20:44:54
Dispongo de una hoja de cálculo de Google, donde algunos textos podrían estar separados por barra diagonal (‘/’). (ver figura 1)

figura1

He adaptado el código de google apps script para que separe y escriba en otra hoja cada uno de los códigos de la primera columna en varias filas, tantas como códigos haya en cada celda, manteniendo los textos del resto de las columnas. Este seria el resultado (figura 2):


Figura2

Este es el código que lo hace posible:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function formatTest() {
// File
var ss = SpreadsheetApp.getActiveSpreadsheet();
 
// Get rawData sheet
var rawData = ss.getSheetByName('Hoja 1');
// Input data
var data = rawData.getRange("A1:C").getValues(); // Gets titles and options in a single call to the
sheet
// Initialise an array that will hold the output
var outputArray = [];
// Name a variable to hold the data from each set of options
var options;
 
// Start looping through the data
for (var row = 0; row < data.length; row++) {
// Split the options into an array: "Option1, Option2, Option3" ---> [Option1, Option2, Option3]
//options = data[row][0].split(","); // sin convertir datos en string
options = data[row][0].toString().split("/");
// Loop through the array of split options and place each of them in a new row
for (var element = 0; element < options.length; element++) {
//outputArray.push([options[element], data[row][1],data[row][2]]);  // options[element]=>>  Place the
title in a new row // resto =>> Place one option in the 2nd column of the row
    outputArray.push([options[element], data[row][1],data[row][2]]);
 
} // Options loop ends here
 
} // Data loop ends here
// Get processedData sheet
var processedData = ss.getSheetByName('Hoja 2');
// clear existing
processedData.clear()
// Get last row in processedData sheet
var lastRow = processedData.getLastRow();
 
 
// Post the outputArray to the sheet in a single call
processedData.getRange(lastRow + 1, 1, outputArray.length,
outputArray[0].length).setValues(outputArray);
}

Hasta ahí, todo ok. Ahora necesito que haga lo mismo, pero que considere también los textos separados de las segunda y tercera columna mediante barras diagonales y le asigne a cada fila, en el mismo orden que están escritas inicialmente, cada uno de los elementos. Por ejemplo, si la primera columna tenemos 111/555/5545 y en la segunda A/B/C, el código debe asignar a 111 el valor A, a 555 el valor B y a 5545 el valor C. Del mismo modo, asignarían para cada elemento de la segunda fila (112/2521/2541/555) los valores G, H, T y U, respectivamente. Los valores de la segunda columna y la tercera tendrán siempre 1 elemento o bien tantos como haya en la primera.
El resultado del nuevo código seria este:

ResultadoNuevoCodigo

¿Alguien me puede ayudar con esto? le estará enormemente agradecido.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 6
Ha aumentado su posición en 4 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Separa texto delimitado por barras de columnas y asociarlas

Publicado por Salva (2 intervenciones) el 15/05/2021 00:47:58
Conseguí hacer algo parecido con vba excel. Este es el código, Pero no sé adaptarlo a Google Apps script.Adjunto imagenes tambien del antes y después. Gracias

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Sub SepararBarras()
 
Application.ScreenUpdating = False
 
On Error Resume Next
Application.DisplayAlerts = False
Sheets("Separados").Delete
Application.DisplayAlerts = True
ActiveSheet.Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = "Separados"
On Error GoTo 0
 
Set Rango = Range("A:A").SpecialCells(2).Offset(1)
vct = Rango.Count
 
For Each cel In Rango.Resize(vct - 1)
If cel.Row <= vct Then
    vb = VBA.Split(cel, "/"): vsb = UBound(vb) + 1
    vb2 = VBA.Split(cel.Offset(, 4), "/")
    Cells(cel.Row, "D") = vsb
    cel.Resize(, 5).Interior.ColorIndex = 6
    If vsb > 1 Then
    For i = 0 To vsb - 1
        vuf = Range("A" & Rows.Count).End(xlUp).Row + 1
        Cells(vuf, "A") = vb(i)
        Cells(vuf, "B") = cel.Offset(, 1)
        Cells(vuf, "C") = cel.Offset(, 2)
        Cells(vuf, "E") = vb2(i)
    Next
    End If
End If
Next
 
With Range("A1").CurrentRegion
    .Sort .Offset(, 2).Resize(, 1), xlAscending, _
    .Offset(, 1).Resize(, 1), , xlAscending, _
    .Offset(, 3).Resize(, 1), xlDescending, xlYes
    .Borders.LineStyle = 1
    .BorderAround 1, xlMedium
End With
 
Set Rango = Nothing
Application.ScreenUpdating = True
 
End Sub

Antes:

EscelConBarras

Resultado:

ResultadoVBAeExcel
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar