我只有一列數據。我需要編寫一個可以遍歷所有值並刪除包含單詞「paper」的所有行的宏。如何刪除包含字符串的行?
A B
1 678
2 paper
3 3
4 09
5 89
6 paper
問題是行數不固定。表格可能有不同的行數。
我只有一列數據。我需要編寫一個可以遍歷所有值並刪除包含單詞「paper」的所有行的宏。如何刪除包含字符串的行?
A B
1 678
2 paper
3 3
4 09
5 89
6 paper
問題是行數不固定。表格可能有不同的行數。
這是另一個簡單的宏,它將刪除列A中除非第1行以外的所有具有非數字值的行。
Sub DeleteRowsWithStringsInColumnA()
Dim i As Long
With ActiveSheet '<~~ Or whatever sheet you may want to use the code for
For i = .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1).Row To 2 Step -1 '<~~ To row 2 keeps the header
If IsNumeric(.Cells(i, 1).Value) = False Then .Cells(i, 1).EntireRow.Delete
Next i
End With
End Sub
如果您確信所涉及的行總是包含"paper"
,並且永遠不會包含任何其他字符串,則應該根據值paper
進行匹配,而不是字符串。這是因爲,特別是在Excel中,有時候您可能會將數字存儲爲字符串而沒有意識到它 - 而且您不想刪除這些行。
Sub DeleteRowsWithPaper()
Dim a As Integer
a = 1
Do While Cells(a, 1) <> ""
If Cells(a, 1) = "paper" Then
Rows(a).Delete Shift:=xlUp
'Row counter should not be incremented if row was just deleted
Else
'Increment a for next row only if row not deleted
a = a + 1
End If
Loop
End Sub
以下是一個靈活的宏,允許您輸入一個字符串或數字來查找和刪除其各自的行。它能夠在2.7秒內處理104萬行簡單字符串和數字。
Sub DeleteRows()
Dim Wsht As Worksheet
Dim LRow, Iter As Long
Dim Var As Variant
Var = InputBox("Please specify value to find and delete.")
Set Wsht = ThisWorkbook.ActiveSheet
LRow = Wsht.Cells(Rows.Count, 1).End(xlUp).Row
StartTime = Timer
Application.ScreenUpdating = False
With Wsht
For Iter = LRow To 1 Step -1
If InStr(.Cells(Iter, 1), Var) > 0 Then
.Cells(Iter, 1).EntireRow.Delete
End If
Next Iter
End With
Application.ScreenUpdating = True
Debug.Print Timer - StartTime
End Sub
請參閱:http://stackoverflow.com/questions/17606045/delete-entire-row-if-cell-contains-the-string-x – tigeravatar