代码之家  ›  专栏  ›  技术社区  ›  Michael

排序范围时需要对象

  •  0
  • Michael  · 技术社区  · 6 年前

    我试图按列对一个范围进行排序:

    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
    

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

    选定的单元格是范围对象。

    1 回复  |  直到 5 年前
        1
  •  0
  •   Storax    6 年前

    如果选定的单元格是一个区域,则必须使用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