必须对具有不同内容的多个工作表应用排序过程。所以我选择了“为工作表中的每个sh ......”解决方案。此排序过程完美地针对第一个选定的工作表运行。在第二张纸上,尽管不同的变量显示正确的值,但应用指令上会显示消息“运行时错误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
你可以尝试:
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