VBA:使用宏对工作表进行排序

时间:2018-11-20 17:02:06

标签: excel vba excel-vba sorting

如图所示

This is a picture of the error

我的排序语法错误,我不明白为什么。我收到运行时错误1004:“排序引用无效。请确保它在您要排序的数据中,并且第一个按框排序的名称不相同或为空白”

Sub Sort()
'
' Sort Macro

Dim rowNum As Variant

Dim columnNum As Variant
Dim sortField As Range
Dim keySort As Range

rowNum = Worksheets("Updated 1.0").Range("A1").End(xlDown).row
MsgBox (rowNum)

columnNum = Worksheets("Updated 1.0").Range("A1").End(xlToRight).column
MsgBox (columnNum)

With Worksheets("Updated 1.0")
    Set sortField = Range(.Cells(2, 1), .Cells(rowNum, columnNum))
    Set keySort = Range("A1")
    sortField.Sort Key1:=keySort, Order1:=xlDescending, MatchCase:=False, 
Orientation:=xlSortRows

End With

1 个答案:

答案 0 :(得分:2)

您在.内缺少了一些With,但我认为排序也不正确。

这对我有用:

Sub Sort()

    Dim sht As Worksheet
    Dim sortField As Range
    Dim keySort As Range

    Set sht = Worksheets("Updated 1.0")

    With sht
        Set sortField = .Range("A1").CurrentRegion
        Set keySort = .Range("A1")
        sortField.Sort Key1:=keySort, Order1:=xlDescending, MatchCase:=False, _
                       Orientation:=xlSortRows
    End With

End Sub