[英]Excel VBA - UDF text replace
我試圖用UDF替換空括號中的所有文本,包括它們–單元格中的“ []”:
Function RMV(iCell As Range) As Variant
RMV = Replace(iCell.Value, "[*]", "")
End Function
但是我猜星號(“ *”)在這里不起作用。
要使用reGex,可以將其用作函數,請記住啟用Microsoft VBScript正則表達式5.5
Function RMV(iCell As Range) As Variant
Dim regEx As Object: Set regEx = CreateObject("VBScript.RegExp") 'If Error Set regEx = New regexp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim strOutput As String
strPattern = "\[\]|\[.+?\]|$"
If strPattern <> "" Then
strInput = CStr(iCell.Value)
strReplace = ""
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.test(strInput) Then
RMV = regEx.Replace(strInput, strReplace)
Else
RMV = "Not matched"
End If
End If
End Function
ReGex測試使用\\[\\]|\\[.+?\\]|$
表達式。 我也是Regex的新手,因此可以優化此表達式。
在子過程中,這可行。
Sub RMV(rng As Range)
rng.Replace "[*]", ""
End Sub
Sub Test()
RMV Range("A2")
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.