通过在每次循环找到下一个最小值时删除最小值来按递增顺序排序

时间:2016-11-23 21:48:11

标签: vba

我目前正在尝试在VBA上创建一个代码,以便按递增顺序对我的值进行排序。在我的程序找到最小值并将其添加到另一列后,该列" B" ,我想让最小的单元格消失,以找到我的新的最小值并将其输入到列#B;#34; B"在初始值下。这是我的代码。由于某种原因,它不会删除单元格,并给我一个"对象所需的错误" 。请帮忙

Option Explicit
Sub decreasing()
Dim a As Range, b As Range
Dim i As Integer
Dim n As Long
Dim minimum As Long

n = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

i = 1

While Cells(i, "A") <> ""
i = i + 1
For i = 1 To n

  Set a = Range(Cells(1, "A"), Cells(n, "A"))

Cells(i, "B") = Application.WorksheetFunction.Min(a)

Application.Min(a).Cells.Delete



   Next i
Wend


End Sub

2 个答案:

答案 0 :(得分:1)

Min()返回一个值,而不是范围对象。您需要使用Find()Match()来定位具有最小值的单元格,然后将其删除。您可能会发现在循环中使用Application.Small(a, i)更容易:那么您就不需要删除已经复制的单元格

Sub decreasing()

    Dim a As Range, b As Range
    Dim i As Integer
    Dim n As Long
    Dim minimum As Long

    n = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
    Set a = Sheet1.Range(Sheet1.Cells(1, "A"), Sheet1.Cells(n, "A"))

    For i = 1 To Application.Count(a)
        Sheet1.Cells(i, "B").Value = Application.Small(a, i)
    Next i

End Sub

答案 1 :(得分:0)

因为你正在排序不要重新发明轮子并使用Range对象的Sort()方法:

Sub decreasing2()        
    With Sheet1
        With .Range("A1", .Cells(Rows.COUNT, 1).End(xlUp))
            .Offset(, 1).Value = .Value
            .Offset(, 1).Sort key1:=Range("B1"), order1:=xlAscending, Header:=xlYes '
        End With
    End With
End Sub