Excel Transpose - Jagged Array

时间:2016-03-04 03:09:03

标签: excel vba transpose jagged-arrays

我需要在excel中将锯齿状数组转置或转换为多个列,并且遇到一些困难。我的数据如下:

Round  A1 A2 A3 A4 A5
 1     1  2  3
 2        4     5
 3     6           7
 4        8     9

因此,我需要在每行检查中将其展平,并将每组序列号转换为单行序列号,每行只标记一列

SeqNum A1 A2 A3 A4 A5
 1     1 
 2        2 
 3           3
 4        4
 5             5
 6    6
 7                7
 8       8
 9            9

我已经编辑了示例中的数字以使其更清晰。基本上我想将每行有多个条目的第一个表格展平到第二个表格,每个表格每行只有1个条目。

我想在Excel中实现以下算法

int numOfTotalElements = 0;
List<int> flattened = new List<int>();
int numRows = matrix.length;
for(int i=0; i<matrix.length; i++){
  for(int j=0; j<matrix[i].length; j++){
     flattened.add(matrix[i][j])
  }//end cols
}// end rows

foreach( int i in flattened){
  System.Console.WriteLine(i);
}

1 个答案:

答案 0 :(得分:0)

See if one of these gets you where you are trying to go.

Option 1:

Sub expandFlatten()
    Dim c As Long, i As Long, j As Long
    Dim vals As Variant, nuvals As Variant

    With Worksheets("sheet2")
        With .Cells(1, 1).CurrentRegion
            vals = .Cells.Value2
        End With
        c = UBound(vals, 2) + 2
        .Cells(1, c).CurrentRegion.Clear
        .Cells(1, c).Resize(UBound(vals, 1), UBound(vals, 2)) = vals
        With .Cells(1, c).CurrentRegion
            .Cells(1, 1) = "SeqNum"
            .Offset(1, 1).ClearContents
            .Cells(2, 1).Resize(Application.Max(.Parent.Cells(1, 1).CurrentRegion), 1) _
                .DataSeries Rowcol:=xlColumns, Type:=xlLinear, Step:=1
        End With
        With .Cells(1, c).CurrentRegion
            ReDim nuvals(1 To .Rows.Count - 1, 1 To .Columns.Count - 1)
            For i = LBound(vals, 1) + 1 To UBound(vals, 1)
                For j = LBound(vals, 2) + 1 To UBound(vals, 2)
                    If Not IsEmpty(vals(i, j)) And IsNumeric(vals(i, j)) Then
                        nuvals(vals(i, j), j - 1) = vals(i, j)
                    End If
                Next j
            Next i
            .Offset(1, 1).Resize(UBound(nuvals, 1), UBound(nuvals, 2)) = nuvals

        End With
        .Activate
        .Cells(1, 1).Select
    End With
End Sub

Option 2:

After recreating the column header labels and a number sequence down the right side (up to MAX(B:F)), place this standard formula in P2,

=IFERROR(INDEX(B:B, MATCH($O2,B:B, 0)), "")

Fill both right and down.


    expandFlatten
                    original data                                expandFlatten()                            INDEX(..., MATCH(...