代码之家  ›  专栏  ›  技术社区  ›  TylerH Ash Burlaczenko

如何匹配字符串末尾的子字符串,然后仅删除该子字符串?

  •  -4
  • TylerH Ash Burlaczenko  · 技术社区  · 8 年前

    每个单元格中都有一列文本,带有字符串 null 如果单元格的内容以该字符串结尾,则从单元格中删除。

    如果它和前一个单词之间有空格,但删除了 整个细胞的 无效的

    Sub TruncateNulls()
    
        Dim strPattern As String: strPattern = "\w*null\b"
        Dim strReplace As String: strReplace = ""
        Dim regEx As New RegExp
        Dim strInput As String
    
        ActiveSheet.Range("A2").Select
    
        Do While ActiveCell.Value <> ""
            strInput = ActiveCell.Value
    
            With regEx
                .Global = False
                .MultiLine = True
                .IgnoreCase = True
                .Pattern = strPattern
            End With
    
            If regEx.Test(strInput) Then
                ActiveCell = regEx.Replace(strInput, strReplace)
            End If
    
            ActiveCell.Offset(1, 0).Select
        Loop
    
    End Sub
    

    输入数据示例:

    words
    null
    wordsnull
    words null
    nullwords
    

    所需输出数据:

    words
    
    words
    words
    nullwords
    

    我如何调整此选项以仅删除结尾 无效的 ,不考虑前面的字符?

    Find 功能,或搜索中的特定通配符/通配符组合;如果这些选项中的任何一个起作用,则替换窗口。

    3 回复  |  直到 8 年前
        1
  •  3
  •   Wiktor Stribiżew    8 年前

    如果您更喜欢当前的方法,则需要将您的模式替换为

    \s*null\s*$
    

    请参阅 regex demo

    • \s* \s 带有空格或 [^\S\r\n] 如果您不想跨行溢出)
    • null 无效的 子字符串
    • -1个或多个空格(请参见上述注释)
    • $ .Multiline
        2
  •  2
  •   Florent B.    8 年前

    .Replace 带图案 \s*null$ 删除每个单元格末尾的所有引用。您还应该考虑在数组中加载范围,以缩短执行时间。

    Sub TruncateNulls()
        Dim rg As Range, data()
    
        ' select the range to the last row
        Set rg = Range(Range("A2"), Range("A" & rows.Count).end(xlUp))
    
        ' load the data in an array
        data = rg.value
    
        ' replace each value with a regex
        ArrayReplace data, pattern:="\s*null$", replacement:=Empty
    
        ' write the array back to the sheet
        rg.value = data
    End Sub
    
    
    Sub ArrayReplace(data(), pattern As String, replacement As String)
        Dim re As New RegExp, r As Long, c As Long
    
        re.Global = True
        re.MultiLine = False
        re.IgnoreCase = True
        re.pattern = pattern
    
        For c = 1 To UBound(data, 2)
            For r = 1 To UBound(data, 1)
                If VarType(data(r, c)) = vbString Then
                    data(r, c) = re.Replace(data(r, c), replacement)
                End If
            Next
        Next
    End Sub
    
        3
  •  2
  •   TBlock    8 年前

    Right() 作用你的代码可以减少到

    Do While ActiveCell.Value <> ""
        strInput = ActiveCell.Value
        If Right(strInput, 4) = "null" Then
            ActiveCell.Value = Left(strInput, Len(strInput)-4)
        End If
        ActiveCell.Offset(1, 0).Select
    Loop