如果字符串不以特定字符串开头,则删除多行 Excel 单元格中一行的字符串

Remove strings in a line in multiline Excel cells if they do not start with a certain string

我有一列 Excel 遵循这种格式的单元格(随机字符串没有固定顺序)。不以特定字符串开头的字符串需要删除。

randomstringA text_that_needs_to_be_kept1
text_that_needs_to_be_removed1
randomstringB text_that_needs_to_be_kept2
randomstringA text_that_needs_to_be_kept3
text_that_needs_to_be_removed2

我希望单元格的输出是这样的(必须保留换行符):

text_that_needs_to_be_kept1

text_that_needs_to_be_kept2
text_that_needs_to_be_kept3

而不是这个(换行符被删除):

text_that_needs_to_be_kept1
text_that_needs_to_be_kept2
text_that_needs_to_be_kept3

在 B1 中放置此公式 =IF(LEFT(A1;1)="r";MID(A1;FIND(" ";A1;1)+1;500);"") 并复制并粘贴到 B 列中的其他单元格。

以下代码将从第 1 行开始沿着 A 列向下移动,并删除任何不是以数组 arrToKeep 中的值开头的行,并保留换行符。

Option Explicit

Sub RemoveStrings()
Dim rngData As Range
Dim arrData As Variant
Dim arrLines As Variant
Dim arrToKeep As Variant
Dim idx1 As Long
Dim idx2 As Long
Dim idxRow As Long
Dim boolKeep As Boolean

    arrToKeep = Array("randomstringA", "randomstringB")

    Set rngData = Range("A1", Range("A" & Rows.Count).End(xlUp))

    arrData = rngData.Value

    For idxRow = LBound(arrData, 1) To UBound(arrData, 1)

        arrLines = Split(arrData(idxRow, 1), vbLf)

        For idx1 = LBound(arrLines) To UBound(arrLines)
        
            boolKeep = False
            
            For idx2 = LBound(arrToKeep) To UBound(arrToKeep)
                If arrLines(idx1) Like arrToKeep(idx2) & "*" Then
                    boolKeep = True
                    Exit For
                End If
            Next idx2
            
            If Not boolKeep Then
                arrLines(idx1) = ""
            End If
            
        Next idx1

        arrData(idxRow, 1) = Join(arrLines, vbLf)

    Next idxRow

    rngData.Value = arrData

End Sub