简体   繁体   English

如果找到字符串,则删除行vba excel

[英]delete row if string found vba excel

I am trying to delete rows if the excel file does not contain a certain word. 我正在尝试删除Excel文件中不包含特定单词的行。

I loop through the cells within column B and check if the cell value contains this string and if not then I will delete it. 我遍历B列中的单元格,并检查该单元格值是否包含此字符串,如果没有,则将其删除。

However, I am getting an error saying Delete method of range class failed . 但是,我收到一个错误消息,说范围类的Delete方法失败了

Sub macro()

Dim i As Integer, intValueToFind As Integer
Dim ws As Worksheet

Set ws = Worksheets("RAW DATA (2)")

For i = 1 To 500    ' Revise the 500 to include all of your values

    If InStr(Cells(i, 2).Value, "Error") = False Or InStr(Cells(i, 2).Value, "No credentials") = False Or InStr(Cells(i, 2).Value, "Connection Failed") = False Then
        ws.Rows(i).EntireRow.Delete
    End If

Next i

End Sub

You are mixing your methods a bit. 您正在混合使用一些方法。

'.EntireRow' Is the property of a Range, not a Row. '.EntireRow'是范围的属性,而不是行的属性。

So where you have: 所以你有:

ws.rows(i).EntireRow.Delete

You should put something like: 您应该输入以下内容:

ws.Range("B"&i).EntireRow.Delete

But really, you could simplify this with one of the .Row methods, which is just Delete. 但实际上,您可以使用.Row方法之一(只是Delete)简化此过程。 So, you could alternatively just say: 因此,您也可以说:

ws.rows(i).Delete

I've tested both and confirmed syntax is correct; 我都进行了测试,并确认语法正确; I can't see any other issues with your code. 我看不到您的代码有任何其他问题。

修改所有字符串比较,使其更接近,

    If NOT InStr(1, " error no credentials connection failed ", lcase(Cells(i, 2).Value), vbTextCompare) Then

Autofilter is more efficient than looping 自动筛选比循环更有效

Sub DeleteRows()
    Sheet1.Range("a1:c35").AutoFilter Field:=2, Criteria1:="<>error"
    Sheet1.UsedRange.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    Sheet1.UsedRange.AutoFilter
'repeat for each value
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM