使用vba,把一个excel表中,具有相同内容的行挑出来并重新排序
时间: 2023-05-11 16:03:20 浏览: 476
VBA排序,相同的加~
可以使用VBA中的循环和条件语句来实现这个功能。具体步骤如下:
1. 定义一个数组,用于存储具有相同内容的行的行号。
2. 循环遍历每一行,比较当前行的内容是否与之前的行相同,如果相同则将当前行的行号添加到数组中。
3. 对数组进行排序,可以使用VBA中的Sort函数。
4. 根据排序后的数组,将相同内容的行按照指定顺序重新排列。
下面是一个示例代码:
Sub SortSameRows()
Dim rowNums() As Long
Dim lastRow As Long
Dim i As Long, j As Long, k As Long
lastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
ReDim rowNums(1 To lastRow)
k = 1
For i = 1 To lastRow
If i = 1 Or ActiveSheet.Cells(i, 1).Value <> ActiveSheet.Cells(i - 1, 1).Value Then
rowNums(k) = i
k = k + 1
End If
Next i
ReDim Preserve rowNums(1 To k - 1)
If UBound(rowNums) > 1 Then
Call QuickSort(rowNums, LBound(rowNums), UBound(rowNums))
End If
For i = 1 To UBound(rowNums)
For j = i + 1 To UBound(rowNums)
If ActiveSheet.Cells(rowNums(i), 1).Value > ActiveSheet.Cells(rowNums(j), 1).Value Then
Call Swap(rowNums(i), rowNums(j))
End If
Next j
Next i
For i = 1 To UBound(rowNums)
If rowNums(i) <> i Then
ActiveSheet.Rows(rowNums(i)).Cut
ActiveSheet.Rows(i).Insert Shift:=xlDown
End If
Next i
End Sub
Sub QuickSort(arr() As Long, left As Long, right As Long)
Dim i As Long, j As Long
Dim pivot As Long
i = left
j = right
pivot = arr((left + right) \ 2)
Do While i <= j
Do While arr(i) < pivot
i = i + 1
Loop
Do While arr(j) > pivot
j = j - 1
Loop
If i <= j Then
Call Swap(arr(i), arr(j))
i = i + 1
j = j - 1
End If
Loop
If left < j Then
Call QuickSort(arr, left, j)
End If
If i < right Then
Call QuickSort(arr, i, right)
End If
End Sub
Sub Swap(ByRef a As Long, ByRef b As Long)
Dim temp As Long
temp = a
a = b
b = temp
End Sub
阅读全文