【发布时间】:2019-04-25 21:09:24
【问题描述】:
必须将排序过程应用于具有不同内容的多个工作表。所以我选择了“针对工作表中的每个 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
【问题讨论】:
-
你想要排序的范围是多少,根据行中的哪一列有标题?
-
您好,范围随每张纸而变化。它由变量“Startcell”=工作表的第一个单元格和“Lastcell”=包含数据的最后一个单元格确定。所有列都有标题,但没有行。我想提醒一下,该程序适用于第一张纸,但不适用于其他纸。吉姆