Excel VBA如果满足三个值,或者三个值之一为空,则删除行

这里是克里斯! 本周早些时候,我发布了一个关于代码的问题,如果不同列(同一行)中的三个单元格符合某个文本值条件,那么这个代码就是要删除一行。 在这种情况下,所有三个单元的文本值是“PURGE”,不区分大小写。

该方法是search一个列(在这种情况下,D),find满足search条件的第一个值,然后偏移到下一个指定的列以validation是否存在以下值标准来满足。

我今天的问题是,如何指定我接受的标准之一是一个空白值? 我想修改我的代码,例如,在第4列(D)中search“PURGE”,如果列5(E)是空白的(无),列6(F)是“PURGE”,则删除那一行。

我将张贴汤姆帮助我的一个好伙伴的代码。

此外,我将复制和移动代码,以满足search条件不同的条件。 我可能还想编辑代码以接受多个空白单元格值作为删除条件。

让我知道,如果有什么办法可以让我的问题更清楚,或者如果已经有一个职位的答案,我需要我找不到!

非常感谢大家,你们在这里的时间意味着比我能用文字写的更多! -克里斯

这是我得到的:

Option Explicit Sub DeleteRows() Dim wbk As Workbook Dim wsh As Worksheet Dim strPath As String, strFile As String, strFind As String, firstAddress As String Dim x As Range, y As Range, z As Range Dim DelRng As Range 'searches directory for any and all excel files With Application.FileDialog(msoFileDialogFolderPicker) If .Show Then strPath = .SelectedItems(1) Else MsgBox "No folder selected!", vbExclamation Exit Sub End If End With If Right(strPath, 1) <> "\" Then strPath = strPath & "\" End If With Application .ScreenUpdating = False ' Stops xlsm files on Open event .EnableEvents = False ' uncomment to hide any deletion message boxes ' .DisplayAlerts = False End With strFile = Dir(strPath & "*.xls*") 'end file finding and such Do While Len(strFile) > 0 Set wbk = Workbooks.Open(Filename:=strPath & strFile, AddToMRU:=False) For Each wsh In wbk.Worksheets 'supposed to search column d, offset column +1 in same row, 'then do same for a third row. 'if all three cells contain "PURGE" then delete cell With wsh.Columns(4) Set x = .Find("PURGE", Lookat:=xlPart) If Not x Is Nothing Then firstAddress = x.Address Do If InStr(1, x.Offset(0, 1), "purge", vbTextCompare) > 0 And InStr(1, x.Offset(0, 2), "purge", vbTextCompare) > 0 Then If DelRng Is Nothing Then Set DelRng = x Else Set DelRng = Union(DelRng, x) End If End If Set x = .FindNext(x) Loop While Not x Is Nothing And x.Address <> firstAddress End If End With Next wsh If Not DelRng Is Nothing Then DelRng.EntireRow.Delete wbk.Close SaveChanges:=True strFile = Dir() Loop With Application .DisplayAlerts = True .EnableEvents = True .ScreenUpdating = True End With End Sub 

使用两个标准.AutoFilter与xlOr似乎是一个更有效的方法。

 For Each wsh In wbk.Worksheets With wsh If .AutoFilterMode Then .AutoFilterMode = False With .Cells(1, "A").CurrentRegion .AutoFilter Field:=4, Criteria1:="*purge*", Operator:=xlOr, Criteria2:="" .AutoFilter Field:=5, Criteria1:="*purge*", Operator:=xlOr, Criteria2:="" .AutoFilter Field:=6, Criteria1:="*purge*", Operator:=xlOr, Criteria2:="" With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0) If CBool(Application.Subtotal(103, .Cells)) Then .Cells.EntireRow.Delete End If End With End With If .AutoFilterMode Then .AutoFilterMode = False End With Next wsh