在研究中,我发现了一个公式,可以检查整个列并回答真假。 但这不是我需要完成的。
我想选择一列数字并运行一个宏,当数字不大于继续它的数字时停止。
我有一列 55000 据说按升序排列的订单号。 我需要挑出扬升中的错误。
谢谢
您可以使用此函数返回所有未排序的单元格地址:
Option Explicit
Function IsItSorted(rng As Range) As Variant
Dim vals As Variant
Dim nErrs As Long, iVal As Long
vals = Application.Transpose(rng.Value)
ReDim errs(LBound(vals) To UBound(vals)) As String
For iVal = LBound(vals) To UBound(vals) - 1
If vals(iVal) > vals(iVal + 1) Then
nErrs = nErrs + 1
errs(LBound(vals) - 1 + nErrs) = rng(LBound(vals) - 1 + iVal).address
End If
Next
If nErrs > 0 Then
ReDim Preserve errs(LBound(vals) To LBound(vals) - 1 + nErrs) As String
IsItSorted = "Errors at: " & Join(errs, ",")
Else
IsItSorted = "Sorting: OK"
End If
End Function
在您的主代码中用作:
Sub main()
MsgBox IsItSorted(Range("B2:B11"))
End Sub
您可以使用数组公式来做到这一点。如果您的列是"A"并且有 55000 行,请在任何单元格中输入此数组公式:
=AND(A1:A54999 <= A2:A55000)
这是一个数组公式,键入它并按 Ctrl+Shift+Enter
.如果您只是像普通公式一样按Enter
,它将不起作用。
编辑
因此,问题不仅在于知道是否存在错误,还在于发现它。这是一个VBA宏,它将Select
排序错误的第一个出现,否则它会通知您没有错误。它使用当前选定的单元格作为要检查的列中的第一个单元格。
Sub checkColumnSorting() ' <-- uses current selection as first cell in column
Dim firstCell As Range, lastCell As Range, i As Long, ar
Set firstCell = Selection
With firstCell.Parent
Set lastCell = .Cells(.Rows.Count, firstCell.Column).End(xlUp)
ar = Application.Transpose(.Range(firstCell, lastCell))
For i = LBound(ar) To UBound(ar) - 1
If ar(i) > ar(i + 1) Then
.Activate
.Cells(i + firstCell.Row, firstCell.Column).Select
msgBox "Error in ascending sorting at row " & i + firstCell.Row
Exit Sub
End If
Next
End With
msgBox "Ascending sorting is Ok"
End Sub