如果删除一行,如果它包含一个string?

我只有一列数据。 我需要编写一个可以遍历所有值的macros,并删除包含单词“paper”的所有行。

AB 1 678 2 paper 3 3 4 09 5 89 6 paper 

问题是行数不固定。 表格可能有不同的行数。

这里是另一个简单的macros,它将删除列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"而不是任何其他的string,你应该根据价值paper匹配,而不是一个string。 这是因为,特别是在Excel中,有时您可能会将数字存储为string,而没有意识到这一点 – 而且您不想删除这些行。

 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 

以下是一个灵活的macros,允许您input一个string或数字来查找和删除其各自的行。 它能够在2.7秒内处理104万行简单的string和数字。

 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