在Excel中,如何重新排列列中的名称以及相邻列中的匹配名称?

时间:2016-06-13 19:28:18

标签: excel vba macros

例如,如果我有这样的数据:

06/10       |      06/11
========================
andrew      |     julia

julia       |     brian

zack        |     andrew

brian       |     amber

phillip     |

amber       |

jess        |

如何获得以下结果或关闭版本?

06/10        06/11
---------------------
andrew    |   andrew     

julia     |   julia

zack      |       

brian     |   brian    

phillip   |

amber     |   amber

jess      |

1 个答案:

答案 0 :(得分:1)

假设主列为“A”,您可以如下所示:

Option Explicit

Sub main()
    Dim myArr() As Variant
    Dim cell As Range

    With Worksheets("mysheetname") '<--| change "mysheetname" with your actual sheet name
        With .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row) '<--| change "A2:A" and "A" with proper first relevant row of the first data column
            ReDim myArr(1 To .Rows.Count)
            For Each cell In .Cells
                myArr(cell.Row - .Rows(1).Row + 1) =  Iif(.Offset(, 1).Find(what:=cell.Value, lookat:=xlWhole, LookIn:=xlValues) Is Nothing, cell.Offset(,1).Value, cell.Value)
            Next cell
            .Offset(, 1).Value = Application.Transpose(myArr)
        End With
    End With

End Sub