通过search提高excel RegExp用户function,并按列表进行replace

我在Excel中有简单的vba用户函数,使用RegEx在文本中进行replace:

Function RegExReplace (SearchPattern As String, TextToSearch As String, _                           ReplacePattern As String, _                           Optional GlobalReplace As Boolean = True, _                           Optional IgnoreCase As Boolean = False, _                           Optional MultiLine As Boolean = False) As String     Dim RE As Object         Set RE = CreateObject ( "vbscript.regexp")     With RE         .MultiLine = MultiLine         .Global = GlobalReplace         .IgnoreCase = IgnoreCase         .Pattern = SearchPattern     End With         RegExReplace = RE.Replace (TextToSearch, ReplacePattern)         End Function 

但它可以只search和replace一个

– search模式(在单元格C2中)和一个 – replace模式(在单元格D2中)

所以,我想要什么 – 当没有匹配从单元格C2模式 – 它采取search和replace单元格C3和D3的模式。

在这里输入图像说明

更实际的例子的屏幕截图 在这里输入图像说明

之前我发布了一个代码,用RegEx模式列表replace,我想这可能会有所帮助:

 Sub regexpreplace ()    Set Myrange = ActiveSheet.Range ( "A2: A1000") 'range in which we make replace    Set regrange = ActiveSheet.Range ( "B2: B6") 'range with RegExp pattern    'In range C1: C6 we have pattern for replace       For Each D In regrange            For Each C In Myrange            Set rgx = CreateObject ( "VBScript.RegExp")            rgx.IgnoreCase = True            rgx.Pattern = D.Value            rgx.Global = True            C.Value = rgx.Replace (C.Value, D.Offset (0, 1) .Value)        Next       Next End Sub 

在这个代码中:

A1:A1000 – 具有input值的范围

B1:B6 – RegExp模式列表

C1:C6 – 输出模式列表

那么,如何从单元格C2中找不到匹配的模式 – 从单元格C3和D3中search并replace模式?

肯定有一种方法来检查正则expression式匹配,并检查另一个正则expression式,如果有必要,但为什么不使用一个匹配两种情况?

例如下面的这个在两种情况下select第二个数字:

  • 正则expression式模式: .* \d+x(\d+)x?.*
  • replace为: \1

在这里testing


对于你原来的问题,要改变正则expression式,你可以使用这样的东西:

 Sub regexpreplace() Dim Rgx As RegExp Dim MyRange As Range Dim RegRange As Range Dim C As Range Dim D As Range Set MyRange = ActiveSheet.Range("A2: A1000") 'range in which we make replace Set RegRange = ActiveSheet.Range("B2: B6") 'range with RegExp pattern 'In range C1: C6 we have pattern for replace Set Rgx = CreateObject("VBScript.RegExp") Rgx.IgnoreCase = True Rgx.Global = True For Each C In MyRange rgxrow = 1 Do Rgx.Pattern = RegRange.Cells(rgxrow, 1) If Rgx.Test(C) Then C.Value = Rgx.Replace(C.Value, RegRange(rgxrow, 2)) rgxrow = D.Rows.Count + 1 Else rgxrow = rgxrow + 1 End If Loop Until rgxrow > D.Rows.Count Next C End Sub