根据单元格值对动态范围进行排序

时间:2019-03-22 20:25:19

标签: excel vba sorting range

我只想对200美元以下的客户按客户代码(行B)对这些总计进行排序。我的代码不起作用,我的错误在哪里? (请记住,行数一直在变化,但列保持不变)

Excel sheet

Sub SortD()    
    Dim TotalRows As Long
    Dim i As Integer
    Dim rng1 As Range
    Dim rng2 As Range

    TotalRows = Application.CountA(Range("F:F"))

    For i = 3 To TotalRows
        If Cells(i, 6).Value >= 200 Then

           Set rng1 = Range(Cells(2, 1), Cells(i - 1, 9))
           Set rng2 = Range(Cells(3, 2), Cells(i - 1, 2))

            Exit Sub
        End If
    Next i

    Application.Goto rng1
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=rng2, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange rng1
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

0 个答案:

没有答案