2015-10-29 90 views
0

我在具有多個值(即DWG,_MS,_AN,_NAS和_PKG)的文件中使用以下代碼,我嘗試刪除行(如果存在)。有沒有辦法使用這個代碼來一次查找所有這些值,並刪除行而不是爲每個值執行此代碼。每個值的工作原理,但只是試圖使它更乾淨,希望更快,因爲個人價值代碼在一個大的Excel文件上執行意志。VBA查找範圍內的特定文本,刪除行

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 

回答

3

試試這個:

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 
2

除了Excel中英雄的回答,您可以使用一個數組來存儲您的查找/替換字符串,然後通過它的循環:

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 

所以,將來如果您想要添加/刪除字符串,只需在一個地方修改myStrings()陣列,然後您就可以走了。