如何删除基于特定值的Excel中的行

我有一个10张工作簿。 每张表都有大约30,000行的URL。 我有一大堆url(约10个不同的url),我需要保留这些数据。 如果第一列(列A – URL)不包含一个URL,是否有办法删除所有工作表中的所有行。

例如,我想保留we.abc.us,ss.boli.us和3m.mark.us,并删除工作簿中所有工作表中的其余行。

Sub delete0rows() Dim Worksheet As Excel.Worksheet Dim lastRow As Long Dim i As Integer For Each Worksheet In Application.ThisWorkbook.Worksheets lastRow = Worksheet.Cells(Rows.Count, 1).End(xlUp).Row i = 1 Do While i <= lastRow If Worksheet.Range("A" & i).Value = 0 Then Worksheet.Rows(i).Delete i = i - 1 lastRow = lastRow - 1 End i = i + 1 Loop Next Worksheet End Sub 

我build议你使用步骤-1引入反向For循环

 Sub delete0rows() Dim Worksheet As Excel.Worksheet Dim lastRow As Long Dim i As Integer For Each Worksheet In Application.ThisWorkbook.Worksheets lastRow = Worksheet.Cells(Rows.Count, 1).End(xlUp).Row For i = lastRow To 1 Step -1 If Worksheet.Range("A" & i).Value = 0 Then Worksheet.Rows(i).EntireRow.Delete End If Next i Next Worksheet End Sub 

我发现这一段时间回来了。 我不记得谁是原作者,还是我会赞扬他们。 我做了一些微调,把variables传递给它

关于这一点的好处是你可以传递一个空格分隔的string来传递多个删除标准

从本质上讲,你可以给它一行开始(如果你有头),告诉它的列查看,列的工作表和你的标准/标准。 所以例如,如果我想要它开始在第5行检查下面的每一行下面的名单“清理”检查列“D”单词“猫”“狗”和“鱼”我会写

叫DelRow(5,“D”,“清理”,“猫狗鱼”)

 Public Sub DelRow(DataStartRow As Long, SearchColumn As String, SheetName As String, myTextString As String) ' This macro will delete an entire row based on the presence of a predefined word or set of words. 'If that word or set of words is 'found in a cell, in a specified column, the entire row will be 'deleted 'Note the seperator is a space. To change this modify the split parameter 'EXAMPLE CALL: Call DelRow(1, "AH", "Cut Data", "DEL") Dim X As Long Dim Z As Long Dim LastRow As Long Dim FoundRowToDelete As Boolean Dim OriginalCalculationMode As Integer Dim RowsToDelete As Range Dim SearchItems() As String SearchItems = Split(myTextString) On Error GoTo ResetCalcs OriginalCalculationMode = Application.Calculation Application.Calculation = xlCalculationManual With Worksheets(SheetName) LastRow = .Cells(.Rows.Count, SearchColumn).End(xlUp).Row Application.StatusBar = "**** Working on the '" & SheetName & "' Sheet: Number of Rows to be scanned(" & LastRow & "). Deletion keyword " & myTextString & " ***" 'Extra line added For X = LastRow To DataStartRow Step -1 FoundRowToDelete = False For Z = 0 To UBound(SearchItems) If InStr(.Cells(X, SearchColumn).Value, SearchItems(Z)) Then FoundRowToDelete = True Exit For End If Next If FoundRowToDelete Then If RowsToDelete Is Nothing Then Set RowsToDelete = .Cells(X, SearchColumn) Else Set RowsToDelete = Union(RowsToDelete, .Cells(X, SearchColumn)) End If If RowsToDelete.Areas.Count > 100 Then RowsToDelete.EntireRow.Delete Set RowsToDelete = Nothing End If End If Next End With If Not RowsToDelete Is Nothing Then RowsToDelete.EntireRow.Delete End If ResetCalcs: Application.Calculation = OriginalCalculationMode End Sub