我有一個包含 20K 行的 Excel 作業表,如下所示:
| 標題1 | 標頭2 |
|---|---|
| 1 | 磷 |
| 2 | 磷 |
| 3 | 磷 |
| 4 | 問 |
| 5 | R |
| 6 | R |
| 7 | R |
| 8 | R |
| 9 | 小號 |
| 10 | 小號 |
我想要一個 VBA 代碼來洗掉包含重復項的行,但保留重復項的第一行和最后一行。結果應該是這樣的:
| 標題1 | 標頭2 |
|---|---|
| 1 | 磷 |
| 3 | 磷 |
| 4 | 問 |
| 5 | R |
| 8 | R |
| 9 | 小號 |
| 10 | 小號 |

uj5u.com熱心網友回復:
簡單的解決方案:
Sub KeepFirstLast()
Application.ScreenUpdating = False
Dim lastRow As Long
lastRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Long
Dim x As Long
Dim currentValue As String
For i = lastRow To 2 Step -1
If i = 2 Then
Application.ScreenUpdating = True
Exit For
End If
currentValue = Sheets(1).Cells(i, 2).Value
x = i - 1
Do While Sheets(1).Cells(x, 2).Value = currentValue And Sheets(1).Cells(x - 1, 2).Value = currentValue
Sheets(1).Rows(x).Delete
x = x - 1
Loop
i = x 1
Next i
Application.ScreenUpdating = True
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492096.html
上一篇:加速回圈
下一篇:添加到字典時VBA錯誤457鍵
