VBA查找范围内的特定文本,删除行

我在一个文件中使用下面的代码,我有多个值(即DWG,_MS,_AN,_NAS和_PKG),我试图删除行,如果存在。 有没有办法使用此代码来一次查找所有这些值,并删除行而不是为每个值执行此代码。 每个值的工作,但只是试图使它更干净,希望更快,因为个人价值代码在一个大的Excel文件上执行的意志。

On Error Resume Next With Columns("K") .Replace "*DWG*", "=1", xlWhole .SpecialCells(xlFormulas).EntireRow.Delete End With On Error Resume Next With Columns("K") .Replace "*_MS*", "=1", xlWhole .SpecialCells(xlFormulas).EntireRow.Delete End With On Error Resume Next With Columns("K") .Replace "*_AN*", "=1", xlWhole .SpecialCells(xlFormulas).EntireRow.Delete End With On Error Resume Next With Columns("K") .Replace "*_NAS*", "=1", xlWhole .SpecialCells(xlFormulas).EntireRow.Delete End With On Error Resume Next With Columns("K") .Replace "*_PKG*", "=1", xlWhole .SpecialCells(xlFormulas).EntireRow.Delete End With 

尝试这个:

 With Columns("K") .Replace "*DWG*", "=1", xlWhole .Replace "*_MS*", "=1", xlWhole .Replace "*_AN*", "=1", xlWhole .Replace "*_NAS*", "=1", xlWhole .Replace "*_PKG*", "=1", xlWhole .SpecialCells(xlFormulas).EntireRow.Delete End With 

除了Excel Hero的答案,你可以使用一个数组来存储你的查找/replacestring,然后循环遍历它:

 Sub test() Dim myStrings() As Variant Dim i& myStrings() = Array("*DWG*", "*_MS*", "*_AN*", "*_NAS*", "*_PKG*") On Error Resume Next With Columns("K") For i = 0 To UBound(myStrings) .Replace myStrings(i), "=1", xlWhole Next i .SpecialCells(xlFormulas).EntireRow.Delete End With End Sub 

所以,将来如果你想添加/删除string,只需在一个地方修改myStrings()数组,然后你就可以开始了。