我的排序过程在第一张纸上运行,但不在另一张纸上

时间:2019-04-25 11:17:49

标签: excel vba

必须将排序过程应用于具有不同内容的多个工作表。因此,我选择了“针对工作表中的每个sh ...”的解决方案。 此排序过程非常适合于第一个选定的工作表。 在第二张纸上,尽管不同的变量显示正确的值,但在Apply指令上仍显示消息“运行时错误1004排序参考无效”。 参照“ '1004': "The sort reference is not valid."”,我将“ With sh.Sort”更改为“ With sh.Range(startcell,lastcell).Sort”,从而产生错误“无法获取范围类的排序属性”。 论坛成员可以帮助我解决这个问题吗? 预先谢谢你

此排序过程在第一张纸上运行,而不在其他纸上。

Sub sortData()
Dim startcell As Range, lastcell As Range
Dim sh As Worksheet
Dim x_Birth As Long, lastcell_Birth As Long
For Each sh In Worksheets
With sh
        If Left(sh.Name, 2) = "B_" Then
            .Columns(5).Insert
            .Cells(1, 5) = "Y_Birth"
            lastcell_Birth = sh.Cells(Rows.count, "A").End(xlUp).Row
            For x_Birth = 2 To lastcell_Birth
                .Cells(x_Birth, 5) = Right(.Cells(x_Birth, 4), 4)
            Next
            Set startcell = Range(.Cells(1, 1), .Cells(1, 1))
            Set lastcell = Range(.Cells(lastcell_Birth, 7), .Cells(lastcell_Birth, 7))
            With sh.Sort
                 .SortFields.Add Key:=sh.Range("F1"), Order:=xlAscending
                 .SortFields.Add Key:=sh.Range("E1"), Order:=xlAscending
                 .SetRange Range(startcell, lastcell)
                 .Header = xlYes
                 .Apply
            End With
            sh.Columns("E:E").Select
            Selection.Columns.EntireColumn.Delete
        End If
End With
Next
End Sub

1 个答案:

答案 0 :(得分:0)

您可以尝试:

Option Explicit
Sub sortData()

    Dim startcell As Range, lastcell As Range
    Dim sh As Worksheet
    Dim x_Birth As Long, lastcell_Birth As Long

    For Each sh In Worksheets

        With sh

            If Left(.Name, 2) = "B_" Then

                .Columns(5).Insert
                .Cells(1, 5) = "Y_Birth"

                lastcell_Birth = .Cells(Rows.Count, "A").End(xlUp).Row

                    For x_Birth = 2 To lastcell_Birth
                        .Cells(x_Birth, 5).Value = Right(.Cells(x_Birth, 4).Value, 4)
                    Next

                Set startcell = .Range(.Cells(1, 1), .Cells(1, 1))

                Set lastcell = .Range(.Cells(lastcell_Birth, 7), .Cells(lastcell_Birth, 7))

                .Sort.SortFields.Clear

                With .Sort
                    .SortFields.Add Key:=sh.Range("E1"), Order:=xlAscending
                    .SortFields.Add Key:=sh.Range("F1"), Order:=xlAscending
                    .SetRange sh.Range(startcell, lastcell)
                    .Header = xlYes
                    .Apply
                End With

                .Columns("E:E").Columns.EntireColumn.Delete

            End If

        End With

    Next

End Sub