循环遍历列

时间:2015-10-04 19:27:06

标签: excel vba excel-vba sorting range

我有一张包含订单和时间戳的工作表。

我想根据右侧列中的时间戳对这些行进行排序,但我希望保持其分组位置。就像我想要排序的第4行但保留在第4行的第4行,然后我想对第8行和第9行进行排序,但让它们留在那里。

我已设法选择两个范围,并省略了#34;中间",但除非关键单元格在一个范围内,否则.sort方法将无效。所以我想如果我循环遍历列中的不同范围或类似的东西。

以下是我现在的代码,我想我不会认为它会有所作为。

    Dim LR As Long, cell As Range, rng As Range
    With Sheets("Ark1")
    Dim start As Range
    Set start = Range("N16")

    LR = .Range("N" & Rows.Count).End(xlUp).Row
    For Each cell In .Range("N16:N" & LR)
        If cell.value <> "" Then
            If rng Is Nothing Then
                Set rng = cell
            Else
                Set rng = Union(rng, cell)
            End If
        End If
    Next cell
        rng.Sort key1:=start, order1:=xlAscending, Header:=xlGuess
    End With

2 个答案:

答案 0 :(得分:1)

嗯,实现目标的最简单方法是按自定义顺序重新计算行数。例如,您将数字#1分配给第一组行,#2分配给第二组,依此类推。然后,您只需将所有范围按两列排序,首先是您的自定义“订单”和第二个时间戳。 :)

答案 1 :(得分:0)

假设每个块在列N中用空白值分隔,并且您想要为每个块排序整个行,这里是我建议的代码:

Public Sub testSort()
    Dim firstRow As Long
    Dim lastRow As Long
    Dim blockStart As Long
    Dim blockEnd As Long
    Dim rng As Range

    firstRow = 3
    lastRow = Cells(Rows.Count, 14).End(xlUp).Row
    blockStart = firstRow

    Do
        If Cells(blockStart + 1, 14) <> "" Then
            blockEnd = Cells(blockStart, 14).End(xlDown).Row
        Else
            blockEnd = blockStart
        End If
        Set rng = Range(Rows(blockStart), Rows(blockEnd))
        rng.Sort Key1:=rng.Cells(, 14), Order1:=xlAscending, Header:=xlNo
        blockStart = Cells(blockEnd, 14).End(xlDown).Row
    Loop Until blockEnd >= lastRow

End Sub
相关问题