按一列排序,然后在第二列中分组相同的值?

时间:2020-02-09 18:24:19

标签: excel vba

我的电子表格中有2列,序列号和日期。我已经将“日期”列按升序排序,这将产生如下结果:

Serial Number     Date
22222             02/09/2020
11111             02/10/2020
33333             02/11/2020
11111             02/12/2020
22222             02/13/2020
44444             02/14/2020

我想使用2016 VBA从这里开始,是将所有相同的序列号组合在一起,每个序列号的最早日期是第一个,例如:

Serial Number     Date
22222             02/09/2020
22222             02/13/2020
11111             02/10/2020
11111             02/12/2020
33333             02/11/2020
44444             02/14/2020

所以我最后要得到的是首先是最快日期的电子表格,但是如果有多个序列号相同,则将它们放在列表中并按序列号分组,但要保持日期升序以及其他序列号。

我希望能得到比for循环更好的东西,但是我的伪代码想法是这样的:

For Each cel in Range(Serial Number column)
    If vLookup cel in Range(Serial Number column) = True Then
        Get Row Number of the Match, Cut entire row, and Insert it below cels row (ie. cel.offset(1,0))
    Else
        Do Nothing
    End If
Next cel

这将对新插入的序列号重复此过程,以寻找另一个匹配项,以防列表中还有另一个匹配项,它将被捕获。如果有人可以帮我编程这个东西,或者如果他们有一个更好的主意,我会很高兴。

谢谢!将于今晚晚些时候进行审核。

1 个答案:

答案 0 :(得分:-1)

请使用下一个代码,

Sub SortTwoColumns()
  Dim sh As Worksheet
  Set sh = ActiveSheet 'use here your worksheet

   sh.Columns("A:B").Sort key1:=sh.Range("A1"), _
      order1:=xlAscending, Key2:=sh.Range("B1"), order2:=xlAscending, Header:=xlYes
End Sub
相关问题