0

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

   A       B  
1  678     
2  paper 
3  3
4  09
5  89
6  paper

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

4

3 回答 3

3

如果您确信有问题的行将始终包含"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
于 2013-10-09T21:59:33.760 回答
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
于 2013-10-09T22:09:48.423 回答
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
于 2013-10-10T02:51:50.977 回答