2017-08-01 65 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 

據我瞭解,這也是更有效的(並且可以由通過定義範圍,並複製其價值到一個數組更有效)。