Excel的VBA运行时错误1004
问题描述:
我使用VBA的Excel 2010和随机收到以下错误:Excel的VBA运行时错误1004
Run-time error '1004': "The sort reference is not valid. Make sure it's within the data you want to sort, and the first Sort By box isn't the same or blank."
这是代码
'Sort the active rows
With ActiveWorkbook.Worksheets("Product Backlog").Sort
.SetRange Range("A4:F51")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
答
排序由框为空,即是你的问题。我从来没有像你这样使用过一个Sort对象,但是我可以看到你没有定义一个关键字或者一个排序范围,只是要排序的范围。应该定义一个键,如Range(“A4”)或其他。我在这看着它,它应该.sortfields.add(范围),如:
'Sort the active rows
With ActiveWorkbook.Worksheets("Product Backlog").Sort
.SetRange Range("A4:F51")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.SortFields.Add Key:=Range("A4:F51").Columns(1), SortOn:=xlSortOnValues, _
Order:=xlDescending, DataOption:=xlSortNormal
.Apply
End With
我使用排序功能如下:
ActiveWorkbook.Worksheets("Product Backlog").Range("A4:F51").Sort _
Key1:= ActiveWorkbook.Worksheets("Product Backlog").Range("A4:F51").Columns(1), _
Header:= xlYes, _
Orientation:=xlSortColumns, _
MatchCase:=False, _
SortMethod:=xlPinYin
最可能的原因是你是不是在所需的工作表中。不要使用'ActiveWorkbook',使用'Sheets(“xxxxx”)'。 – 2011-12-30 17:48:51