Excel VBA 运行时错误 1004

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8681990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 14:48:17  来源:igfitidea点击:

Excel VBA Run-Time Error 1004

excel-vbavbaexcel

提问by Aaron

I am using VBA for Excel 2010 and randomly receiving the following error:

我在 Excel 2010 中使用 VBA 并随机收到以下错误:

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."

运行时错误“1004”:“排序引用无效。请确保它在您要排序的数据内,并且第一个排序依据框不相同或不为空。”

This is the code

这是代码

'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

采纳答案by Motes

The sort by box is blank, that is your problem. I never have used a Sort object like your doing, but I can see that you have not defined a key, or a range to sort by, just the range to be sorted. A key should be defined such as Range("A4") or something. I looked it up, it should have .sortfields.add (range) in it, such as:

sort by 框是空白的,那是你的问题。我从未像您那样使用过 Sort 对象,但我可以看到您没有定义键或要排序的范围,只是要排序的范围。应该定义一个键,例如 Range("A4") 或其他东西。我查了一下,里面应该有 .sortfields.add (range) ,比如:

'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

I use the Sort function as follows:

我使用 Sort 函数如下:

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