我只有一列数据。我需要编写一个宏,它将遍历所有值并删除包含单词“paper”的所有行。
A B
1 678
2 paper
3 3
4 09
5 89
6 paper
问题是行数不固定。表格可能具有不同的行数。
答案 0 :(得分:3)
这是另一个简单的宏,它将删除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
答案 1 :(得分:2)
如果您确信有问题的行总是包含"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 :(得分:2)
以下是一个灵活的宏,允许您输入字符串或数字以查找和删除其各自的行。它能够在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