保留多个字符串并删除其他数据

时间:2019-05-15 06:53:19

标签: excel vba

我面临一个小问题,基本上我已经成功完成了一个字符串的宏处理。但是我无法处理用于保留多个字符串的同一个vba宏,也无法删除CSV文件中存在的不需要的数据。

当前,以下代码仅保留带有字符串Event Magnitude:的行,并删除其余的行。

但是我想添加多个字符串,例如Event Duration:
Trigger Date:Trigger Time:在同一宏中,我不确定该怎么做。

如果我可以添加多个字符串,则此宏将检查所有4个字符串,并保留该数据并删除其余数据。

Sub DeleteNotMIS()
    Dim r As Long, lr As Long
    lr = Cells(Rows.Count, 1).End(xlUp).Row
    For r = lr To 2 Step -1
        If InStr(Cells(r, 1), "Event Magnitude: ") = 0 Then Rows(r).Delete
    Next r
 End Sub

Sample CSV

1 个答案:

答案 0 :(得分:2)

您需要定义关键字列表以保留KeywordsToKeep = Array("Event Magnitude: ", "Trigger Date:"),然后在另一个循环中检查每个关键字

Option Explicit

Public Sub DeleteNotMIS()
    Dim LastRow As Long
    LastRow = Cells(Rows.Count, 1).End(xlUp).Row

    Dim KeywordsToKeep() As Variant
    KeywordsToKeep = Array("Event Magnitude: ", "Trigger Date:")  'Add other keywords here

    Dim iRow As Long, eKey As Variant, FoundKey As Boolean
    For iRow = LastRow To 2 Step -1
        FoundKey = False 'initialize
        For Each eKey In KeywordsToKeep
            If InStr(Cells(iRow, 1), eKey) <> 0 Then 
                FoundKey = True
                Exit For 'we don't need to check further keys if we already found one.
            End If
        Next eKey
        If Not FoundKey Then Rows(iRow).Delete
    Next iRow 
End Sub

如果每个关键字在CSV文件中只能出现一次...
这种方法很慢,因为它必须检查行(逐行)。更快的方法是使用Range.Find method直接查找每个关键字,然后将其提取/复制到新的表格中。