Excel中的自定义macrosselect和sorting

我有一个大的Excel文件,其中包含大量需要sorting的数据。

第一行包含列标题,第二行包含一个位置,第三行以数据开始。 一旦每个位置的数据结束,就会有一个空白行,然后是下一行的位置名称,然后是数据。 这个过程重复18次。

我试图写一个macros,开始抓取数据在A3,这是包含数据的第一列,跨越到列G,然后下降,直到第一个空白行。 一旦findselect,它应该按列C,然后列B进行sorting。

我有整个第一次迭代书面和工作,但我不知道如何得到这个find下一个列的数据所在。

基本上在每一个空白行之后,有一行,然后是数据,这是我正在寻找的。

我正在写这个VBA。

Sub DataCleanup() 'Rows("1:3").EntireRow.Select 'Selection.Delete Shift:=xlUp For i = 1 To 18 Range("A3:G" & Range("A1").End(xlDown).Row).Select 'Sort the rows C, B Selection.Sort Key1:=Range("C1"), Order1:=xlAscending, Key2:=Range("B1") _ , Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:= _ False, Orientation:=xlTopToBottom Next End Sub 

也许这将工作。 我冒昧地删除了硬编码的假设,总会有18块数据。 这将循环访问尽可能多的块,并在到达工作簿底部时停止。 因此,我的假设是你没有一个低于第十八块的东西,你不希望被分类。

 Sub DataCleanup() Dim TopLeft As Range Dim SortRange As Range Set TopLeft = Range("A2") Do Set TopLeft = TopLeft.Offset(1, 0) Set SortRange = Range(Range(TopLeft, TopLeft.End(xlDown)), TopLeft.End(xlToRight)) SortRange.Select ' this line for show only, should be commented out SortRange.Sort Key1:=Range("C1"), Order1:=xlAscending, Key2:=Range("B1") _ , Order2:=xlAscending, Header:=xlGuess, OrderCustom:=1, MatchCase:= _ False, Orientation:=xlTopToBottom Set TopLeft = TopLeft.End(xlDown).End(xlDown) Loop Until TopLeft.Row = ActiveSheet.Rows.Count End Sub 

笔记:

  1. 我把起始位置改成$A$2 。 这只是适当地设置循环(假设至less有一个块进行sorting)。
  2. SortRange.Select可以安全地注释掉。 我只把它留在那里,以防你想要看到代码的工作。
  3. Protip:你可能想把Sort Header参数改为xlNo因为数据范围肯定不包含头部。
 "Essentially after each blank line, there is one row, then the data..." 

根据您提供的信息,下面的代码假定您不想在空白行之后对下一行进行sorting。

 Private Sub SortLocations() Dim firstAddress As String Dim lastRow As Long Dim Rng As Range Dim R As Range With ActiveSheet 'Set the entire range to work with. lastRow = Range("A:A").Find("*", searchdirection:=xlPrevious).Row Set Rng = .Range("A1:A" & lastRow) 'Sort the first group of locations. .Range("A3:G" & .Range("A1").End(xlDown).Row).Sort _ Key1:=.Range("C1"), Order1:=xlAscending, _ Key2:=.Range("B1"), Order2:=xlAscending, _ HEADER:=xlGuess, OrderCustom:=1, MatchCase:=False, _ Orientation:=xlTopToBottom Set R = Rng.Find(vbNullString) If Not R Is Nothing Then firstAddress = R.Address Do 'Sort each subsequent group locations. .Range(R.Offset(2, 0), .Range("G" & R.Offset(2, 0).Row).End(xlDown)).Sort _ Key1:=.Range("C" & R.Offset(2).Row), Order1:=xlAscending, _ Key2:=.Range("B" & R.Offset(2).Row), Order2:=xlAscending, _ HEADER:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom 'Find next empty cell Set R = Rng.FindNext(R) Loop While Not R Is Nothing And R.Address <> firstAddress End If End With End Sub 

供您参考: .FindNext