运行时错误1004排序函数VBA

时间:2014-11-21 06:11:11

标签: excel vba excel-vba

当我运行这段代码时,我似乎得到了大约一半的错误1004,而且我完全不确定原因:

Dim ranged As Range
Set ranged = Range("AJ2")
Set ranged = Range(ranged, ranged.End(xlDown))


Sheets(i).Select
ActiveWorkbook.Worksheets(i).Sort.SortFields.Add Key:=ranged, _
    SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets(i).Sort
    .SetRange ranged
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply

End With

代码正在一系列工作表上运行,并且AJ列中的范围在每张工作表上的大小不同,因此开始时的范围定义是必要的。目的是扭转范围的顺序。任何人都可以帮助解决这里的错误吗?

1 个答案:

答案 0 :(得分:0)

  1. 在大多数情况下,您不需要选择工作表。您可能希望查看THIS

  2. 请勿使用xlDown来构建范围。使用xlUp通过查找包含数据的最后一行来执行此操作。您可能希望查看THIS

  3. 结合上述两种情况,您的代码可能如下所示。请试一试。 (的 UNTESTED

    Dim ranged As Range
    Dim lRow As Long
    
    '
    '~~> Rest of the code
    '
    
    With ThisWorkbook.Sheets(i)
        '~~> Find Last row in Col AJ which has data
        lRow = .Range("AJ" & .Rows.Count).End(xlUp).Row
    
        '~~> Construct your range
        Set ranged = .Range("AJ2:AJ" & lRow)
    
        '~~> Sort
        .Sort.SortFields.Add Key:=ranged, _
                             SortOn:=xlSortOnValues, _
                             Order:=xlDescending, _
                             DataOption:=xlSortNormal
        With .Sort
            .SetRange ranged
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    End With
    
    '
    '~~> Rest of the code
    '
    

    测试和测试版本

    Sub Sample()
        Dim ranged As Range
        Dim lRow As Long, i As Long
    
        For i = 1 To ThisWorkbook.Sheets.Count
            '
            '~~> Rest of the code
            '
    
            With ThisWorkbook.Sheets(i)
                '~~> Find Last row in Col AJ which has data
                lRow = .Range("AJ" & .Rows.Count).End(xlUp).Row
    
                '~~> Construct your range
                Set ranged = .Range("AJ2:AJ" & lRow)
    
                '~~> Sort
                .Sort.SortFields.Add Key:=ranged, _
                                     SortOn:=xlSortOnValues, _
                                     Order:=xlDescending, _
                                     DataOption:=xlSortNormal
                With .Sort
                    .SetRange ranged
                    .Header = xlNo
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With
            End With
    
            '
            '~~> Rest of the code
            '
        Next i
    End Sub