2017-08-01 104 views
1

我在每个单元格中都有一列文字,字符串null位于其中许多字段的末尾。我想解析列中的每个单元格,如果单元格的内容以该字符串结尾,则从该单元格中删除只需null如何匹配字符串末尾的子字符串,然后只删除该子字符串?

我写什么,到目前为止去除成功结束null如果它和前面的单词之间的空间,但如果有前一个字和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 

如何调整此仅删除结束null,不论前面的字符?

或者,我愿意使用搜索& Excel的Find功能,或特定的通配符/通配符的组合替换窗口,如果任这些选项的作用。

+0

'如果strInput喜欢“* null”那么' –

回答

1

使用.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 
+0

所有的答案都能正常工作,而且速度相当快,但这似乎是最有效的,这使得它对于今后的工作最有用。 – TylerH

2

如果你喜欢目前的做法,你需要

\s*null\s*$ 

更换你的模式查看regex demo

详细

  • \s* - 0+空格(更换\s与一个空格或[^\S\r\n],如果你不想跨行溢出)
  • null - 一个null
  • \s* - 1以上空白字符(见与上述相同的注释)
  • $ - 线的端部(设置.Multiline标志到字符串的末尾匹配)。不是在这种情况下,正则表达式
+0

该网站是非常有用的,谢谢!如果我知道这个解决方案,可能会更容易地弄出一个解决方案。就此而言,我发现'\ snull $'和'\ snull \ b'似乎同样适用。 – TylerH

+1

@TylerH请记住'\ b'是一个[*字边界*](https://stackoverflow.com/documentation/regex/1539/word-boundary),'$'是字符串的[*结尾锚*](https://stackoverflow.com/documentation/regex/1603/anchor-characters-dollar)。他们的行为不同。 'null'后的'\ b'要求下一个字符是非字母,非数字和非'_'或字符串的结尾。 '$'只需要字符串的结尾。 –

1

简单的方法是简单地检查与Right()功能的最后4个字符。您的代码可以减少到

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 

据我了解,这也是更有效的(并且可以由通过定义范围,并复制其价值到一个数组更有效)。