Excel:将列转置为行,并根据新行过滤表

时间:2018-12-20 14:06:54

标签: excel vba excel-vba excel-formula

我有下表

A     B     C     D
-------------------
sa  s21    os   v12  
sa  s21    hs   v14  
rd  s22    ft   v16  
zt  s23    pq   v13  
zt  s23    et   v15  
hp  s26    zu   v17

A列:存在重复值

C列:有唯一的

我想将“ A”列作为其他工作表(帮助器)中的列标题转置到新行(唯一值),然后按如下所示进行过滤:

sa    rd     zt    hp
----------------------
os    ft     pq    zu
hs    -      et    -

有什么解决办法吗?作为制定者还是VBA?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

Option Explicit

Sub test()

    Dim LastColumn2 As Long, LastRow1 As Long, LastRow2 As Long, i As Long, j As Long
    Dim Code1 As String, Code2 As String
    Dim Excist As Boolean

    LastRow1 = Sheet1.Cells(Sheet1.Rows.Count, "A").End(xlUp).Row

    For i = 1 To LastRow1
        Code1 = Sheet1.Range("A" & i).Value
        LastColumn2 = Sheet2.Cells(1, Sheet2.Columns.Count).End(xlToLeft).Column
        Excist = True
            For j = 1 To LastColumn2
                Code2 = Sheet2.Cells(1, j).Value
                If Code1 = Code2 Then
                    LastRow2 = Sheet2.Cells(Sheet2.Rows.Count, j).End(xlUp).Row
                    Sheet2.Cells(LastRow2 + 1, j).Value = Sheet1.Range("A" & i).Offset(0, 2).Value
                    Excist = True
                    Exit For
                Else
                    Excist = False
                End If
            Next j

            If Excist = False Then
                If LastColumn2 = 1 And Sheet2.Range("A1").Value = "" Then
                    Sheet2.Cells(1, 1).Value = Sheet1.Range("A" & i).Value
                    Sheet2.Cells(2, 1).Value = Sheet1.Range("A" & i).Offset(0, 2).Value
                Else
                    Sheet2.Cells(1, LastColumn2 + 1).Value = Sheet1.Range("A" & i).Value
                    Sheet2.Cells(2, LastColumn2 + 1).Value = Sheet1.Range("A" & i).Offset(0, 2).Value
                End If
            End If
    Next i
End Sub

数据出现在工作表1中:

enter image description here

并在工作表2中导出:

enter image description here