VBA Excel - 使用特定关键字删除行上方的2行

时间:2015-02-04 03:24:53

标签: excel-vba vba excel

我对VBA没什么了解,因此我需要有人帮助我使用脚本来实现标题中所述的结果。

我需要从我拥有的日志文件中提取特定行。

摘自excel中的实际日志文件:

=====================================

Encrypted file: C:\[specific path]      
Algorithm picked for decryption: RC4        
Status: Successfully decrypted!     

Encrypted file: C:\[specific path]          
File looks like it is not encrypted. Skipping ...       

Encrypted file: C:\[specific path]      
File could not be decrypted properly. Skipping ...      

=====================================

大约90k行就是这样的。我需要摆脱所有“状态:成功解密!”行上面有2行。 我需要的最终数据只是跳过路径的行,解密失败。

此日志中的每个文本块后跟空行。

尝试以下方法:

Sub DeleteRowsBelow()

Dim x As Long
Dim y As Long

x = ActiveSheet.UsedRange.Rows.Count

Cells.Find(What:="Macro", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Select
y = Selection.Row + 1
Rows(x & ":" & y).EntireRow.Delete

End Sub

但它会删除某个关键字下方的所有行,因此这对我不起作用。

然后尝试将以下内容合并到上面的脚本中:

行(“1:”& Cells.Find(“KEY WORD”)。行 - 1)。删除

但运气不好,并且它会删除某个关键字上方的所有行。

1 个答案:

答案 0 :(得分:1)

不确定这是否是您正在寻找的,但也许它会有所帮助

只需选择列表顶部的单元格并运行宏

即可
Sub DeleteSuccessfulRows()

Application.ScreenUpdating = False
Dim x
For x = Cells(Rows.Count, ActiveCell.Column).End(xlUp).Row To ActiveCell.Row Step -1
    If Cells(x, 1) = "Status: Successfully decrypted!" Then 'If we find this text
        Cells(x, 1).EntireRow.Delete      'Delete the entire row
        Cells(x - 1, 1).EntireRow.Delete  'Delete the row above it
        Cells(x - 2, 1).EntireRow.Delete  'Delete the row 2 rows above it
        x = x - 2
    'Delete blank rows
    ElseIf Cells(x, 1) = vbNullString Then Cells(x, 1).EntireRow.Delete
    'Optional delete rows that contain "File looks like ..."
    'ElseIf Cells(x, 1) = "File looks like it is not encrypted. Skipping ..." Then Cells(x, 1).EntireRow.Delete
    'ElseIf Cells(x, 1) = "File could not be decrypted properly. Skipping ..." Then Cells(x, 1).EntireRow.Delete
    End If
Next x
Application.ScreenUpdating = True

End Sub

结果:

After