除了可在任何工作表上运行的当前代码外,还可以在VBA中对excel进行排序

时间:2018-12-04 19:34:50

标签: excel vba excel-vba sorting

我正在尝试从其他命令列表中添加此VBA,但是出现错误。请协助使用正确的语法进行排序。谢谢。

错误消息是:运行时错误'1004'应用程序定义的错误或对象定义的错误。

    Sub filter()
Dim N As Long
Dim wsName As String


For N = 1 To ThisWorkbook.Sheets.Count
    wsName = ThisWorkbook.Worksheets(N).Name

    If Len(wsName) = 3 Then

    Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=12, Criteria1:=">=365" _
        , Operator:=xlAnd
    Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=17, Criteria1:=">100" _
        , Operator:=xlAnd
    Sheets(wsName).Range("$A$1:$XFC$7606").AutoFilter Field:=20, SortOn:=xlSortOnValues, Order:=xlDescending _
        , Operator:=xlAnd
    With ActiveWorkbook.Worksheets("i_ULO").AutoFilter.sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With


    Else
end if 
next n
end sub

在下面添加此代码后。出现新错误。

Dim N As Long

将wsName设为字符串

对于N = 1到ThisWorkbook.Sheets.Count     wsName = ThisWorkbook.Worksheets(N).Name

If Len(wsName) = 3 Then
With .Cells(1, "A").CurrentRegion
     .Cells.sort Key1:=.Columns(20), Order1:=xlDescending, _
                 Orientation:=xlTopToBottom, Header:=xlYes
End With
End With

commitSync(offsets)

Compile Error

2 个答案:

答案 0 :(得分:0)

您可以使用此VBA排序代码对以T列为主要排序键的,从A1辐射出来的活动工作表的数据表进行排序。

Dim N As Long 
Dim wsName As String 

For N = 1 To ThisWorkbook.Sheets.Count 
    wsName = ThisWorkbook.Worksheets(N).Name 
    If Len(wsName) = 3 Then 

        with ThisWorkbook.Worksheets(N)
            with .cells(1, "A").currentregion
                 .Cells.Sort Key1:=.Columns(20), Order1:=xldescending, _
                             Orientation:=xlTopToBottom, Header:=xlyes
            end with
        end with

    end if
next n

答案 1 :(得分:0)

尝试以下方法:

Sub filter()

    Dim N As Long
    Dim wsName As String

    For N = 1 To ThisWorkbook.Sheets.Count
        wsName = ThisWorkbook.Worksheets(N).Name

        If Len(wsName) = 3 Then

            Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=12, Criteria1:=">=365" _
                , Operator:=xlAnd
            Sheets(wsName).Range("$A$1:$XFC$1104").AutoFilter Field:=17, Criteria1:=">100" _
                , Operator:=xlAnd
            Sheets(wsName).AutoFilter.Sort.SortFields.Add Key:=Range("T1:T7606"), SortOn:=xlSortOnValues, Order:=xlDescending

            With ActiveWorkbook.Worksheets("i_ULO").AutoFilter.Sort
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With

        End If

    Next N

End Sub