范围排序时需要对象

时间:2018-08-05 11:17:28

标签: excel vba

我正在尝试按列对范围进行排序:

Private Sub sort_all_by_group()
    Dim last_row As Integer
    Dim selected_cells
    Dim sort_criterion
    last_row = find_last_row()

    With Worksheets(MAIN_SHEET)
        selected_cells = Range(.Cells(2, 1), .Cells(last_row, LAST_COL))
        sort_criterion = Range(.Cells(2, 2), .Cells(last_row, LAST_COL))

        ' Run-time error 424: Object required.
        selected_cells.Sort key1:=sort_criterion, order1:=xlAscending, Header:=xlNo 

    End With

End Sub

在注释中,我指定了错误所在。

Selected_cells是一个范围对象。

1 个答案:

答案 0 :(得分:0)

如果selected_cells是范围,则必须使用set关键字。然后最好适当清除它

Private Sub sort_all_by_group()
    Dim last_row As Integer
    Dim selected_cells As Range
    Dim sort_criterion As Range
    last_row = find_last_row()

    With Worksheets(MAIN_SHEET)
        Set selected_cells = .Range(.Cells(2, 1), .Cells(last_row, LAST_COL))
        Set sort_criterion = .Range(.Cells(2, 2), .Cells(last_row, LAST_COL))
        selected_cells.Sort key1:=sort_criterion, order1:=xlAscending, Header:=xlNo 
    End With

End Sub