emm,来了来了,就是说,我的水平也就这样的代码了:
Sub SortAndCheckDuplicates()
Application.ScreenUpdating = False ' 禁用屏幕更新
Dim rng As Range
Dim sortedRng As Range
Dim i As Long
Dim j As Long
Dim temp As Variant
Dim cell As Range
Dim duplicates As Collection
' 创建一个集合来存储重复的数值
Set duplicates = New Collection
' 获取选定的区域
Set rng = Selection
' 检查是否有选中区域
If rng Is Nothing Then
MsgBox "请先选中要排序的区域!", vbExclamation
Exit Sub
End If
' 检查区域是否只包含数字
For Each cell In rng
If Not IsNumeric(cell.Value) Then
MsgBox "请选择只包含数字的区域!", vbExclamation
Exit Sub
End If
Next cell
' 排序整个数据区域
Set sortedRng = rng.CurrentRegion
' 使用气泡排序算法对整个数据区域进行排序
For i = 1 To sortedRng.Rows.Count * sortedRng.Columns.Count - 1
For j = 1 To sortedRng.Rows.Count * sortedRng.Columns.Count - i
If sortedRng.Cells(j) > sortedRng.Cells(j + 1) Then
temp = sortedRng.Cells(j).Value
sortedRng.Cells(j).Value = sortedRng.Cells(j + 1).Value
sortedRng.Cells(j + 1).Value = temp
End If
Next j
Next i
' 检查重复的数字
For Each cell In sortedRng
If Application.WorksheetFunction.CountIf(sortedRng, cell.Value) > 1 And Not IsInCollection(cell.Value, duplicates) Then
' 如果有重复的数字,并且尚未添加到集合中,将其添加到集合中
duplicates.Add cell.Value
End If
Next cell
' 显示提示框
If duplicates.Count > 0 Then
Dim dupl As Variant
Dim result As String
' 将集合中的数值添加到结果字符串中
For Each dupl In duplicates
result = result & dupl & ","
Next dupl
result = Left(result, Len(result) - 1)
MsgBox "排序已完成!重复出现的数值有:" & result & "。", vbInformation
Else
MsgBox "排序已完成!没有重复出现的数值。", vbInformation
End If
Application.ScreenUpdating = True ' 重新启用屏幕更新
End Sub
' 检查一个值是否已经存在于集合中
Function IsInCollection(val As Variant, coll As Collection) As Boolean
Dim i As Long
On Error Resume Next
IsInCollection = False
For i = 1 To coll.Count
If coll(i) = val Then
IsInCollection = True
Exit Function
End If
Next i
End Function
处理时间确实有一点长,如果你想看起来很酷,那你可以把禁用屏幕更新和启用屏幕更新的那两段给注释掉。


