我在一个文件中使用下面的代码,我有多个值(即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
答案 0 :(得分: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
答案 1 :(得分:3)
除了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()
数组,就可以了。