regex - 如何使用 Excel VBA 正则表达式单元格内函数移动字符串的一部分

标签 regex excel vba

编辑我的原始帖子。

不熟悉在 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 单元格内函数(宏也不错,但我必须从某个地方开始)来:

  • 查找多字符括号表达式中包含的子字符串“(CE) ”或“CE”或“CE”的每次出现
  • 将其从当前位置删除
  • 编辑它(去掉前导空格、去掉左/右括号、添加逗号)
  • 将新编辑移动到字符串中的新位置,即“(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 或 VBA,当 SUBSTITUTE 函数可以解决问题时:

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

enter image description here

关于regex - 如何使用 Excel VBA 正则表达式单元格内函数移动字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47913839/

相关文章:

ms-access - ms access 获取从 FileDialog 中选择的文件名

Python 正则表达式lookbehind 交换组

html - 使用css选择器excel vba从网站抓取数据

javascript - 查找链接并使其可点击

excel - 在 VB 问题中使用 Excel 函数

文本框中的VBA文本字符串限制

excel - Excel 公式,查找最大值并检查多个条件

excel - 我可以仅对特定列使用 worksheet_change 吗?

python - 找出正则表达式的每个部分匹配的内容

regex - Perl:正则表达式模式内的条件代码执行