如何使用Excel VBA正则表达式in-cell函数来移动字符串的一部分

问题描述 投票:2回答:1

编辑我原来的帖子。

在Excel和正则表达式中使用VBA的新功能。我认为正则表达式为我提供了最好的解决方案,因为字符串的变化很大。 我真的很感激任何帮助 - 不是寻找讲义 - 只是想学习。

我的工作簿中有数以千计的文本条目(一列):

911407 - Ariens 34" Wide-Area Walk-Behind Mower, 10.5hp Briggs & Stratton, Gear, CARB (SN: 000101 & Above)
911379 (LMSPE CE) - Ariens Razor 21" Self-Propelled Lawn Mower, 175cc Subaru (SN: 020347 - 025999)
08200835 (CE) - Ariens CE AX 136cc Recoil Engine
922013 (ST4) - Ariens Snow Blower, CE 4hp Tecumseh (SN: 000101 & Above)

我想使用Excel VBA in-cell函数(宏也很好,但我必须从某处开始):

  • 查找包含在多字符括号表达式中的子字符串“(CE)”或“CE”或“CE”的每次出现
  • 将其从当前位置移除
  • 编辑它(去掉前导空格,剥去开/关的parantheses,添加一个逗号)
  • 将新编辑移动到字符串中的新位置,位于“(SN:...)”之前的位置

使用上面引用的条目获得的期望结果是:

911407 - Ariens 34" Wide-Area Walk-Behind Mower, 10.5hp Briggs & Stratton, Gear, CARB (SN: 000101 & Above)
911373 (LMP) - Ariens Razor 21" Push Lawn Mower, 175cc Subaru, CE (SN: 035000 - 054999)
08200835  - Ariens CE AX 136cc Recoil Engine, CE
922013 (ST4) - Ariens Snow Blower, 4hp Tecumseh, CE (SN: 000101 & Above)

这是我到目前为止创建的“(CE)”并删除它。我只是通过阅读过去的帖子和实验来做到这一点。

Function TomCEregex(Myrange As Range) As String
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String

strPattern = " \(CE\)"

If strPattern <> "" Then
    strInput = Myrange.Value
    strReplace = ""

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regEx.Test(strInput) Then
        TomCEregex = regEx.Replace(strInput, strReplace)
    Else
        TomCEregex = "Not Matched"
    End If
End If

End Function

显然,我甚至都不亲近,但我希望你看到我在努力。

谢谢。

regex excel-vba vba excel
1个回答
2
投票

这里不需要RegEx或VBA,当SUBSTITUTE函数可以做到这一点:

=SUBSTITUTE(SUBSTITUTE(A1," (CE) ","")," (",", CE (")

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.