簡體   English   中英

VBA 在范圍中查找特定文本,刪除行

[英]VBA Find specific text in Range, Delete row

我在我有多個值(即 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 的答案之外,您還可以使用數組來存儲查找/替換字符串,然后循環遍歷它:

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()數組,就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM