【问题标题】:Remove strings in a line in multiline Excel cells if they do not start with a certain string如果多行 Excel 单元格中的一行中的字符串不是以某个字符串开头,则删除它们
【发布时间】:2021-05-03 20:34:40
【问题描述】:

我有一列遵循这种格式的 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

【问题讨论】:

  • 那么 - 您在实现此功能时遇到的具体问题是什么?你尝试了什么,发生了什么?一种方法可能是在vbLf 上使用Split() 来获取行数组,然后循环遍历数组,将您不想要的行设置为空字符串,然后Join() 数组以获取结果。

标签: excel vba excel-formula line-breaks string-matching


【解决方案1】:

以下代码将从第 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      相关资源
      最近更新 更多