Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel 排序范围时需要对象_Excel_Vba - Fatal编程技术网

Excel 排序范围时需要对象

Excel 排序范围时需要对象,excel,vba,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, LA

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

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
在注释中,我指定了错误是什么


所选单元格是范围对象。

如果所选单元格是范围,则必须使用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