1

我有一个大表,其中包含以下方式的项目描述+代码:

"description [#######]" 
(Code being enclosed in "[]" and composed of 8 numbers)

我需要在不同的列中分离代码和描述。需要正则表达式的原因是上述描述通常在 excel 公式中找到,例如:=

=IF(xyz, "description1 [1######]", "description2 [2######]")

所以最终结果应该是:

column 1: =IF(xyz, 1######, 2######)
column 2: =IF(xyz, "description1 ", "description2 ")

有没有人做过类似的事情?我发现这些答案有些相关,但目前还不足以破解正则表达式:

在 VBA (excel) 中返回正则表达式匹配

匹配日期的 VBA 正则表达式

4

3 回答 3

1

使用RegExp替换简化了替换

此代码在 A 列上使用变体数组,导致 B 到 D 列

在此处输入图像描述

Sub Spliced()
Dim objRegex As Object
Dim objRegMC As Object
Dim X
Dim lngRow As Long
X = Range([a1], Cells(Rows.Count, "A").End(xlUp)).Formula
ReDim Preserve X(1 To UBound(X), 1 To 3)
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Global = True
    .Pattern = """(\w+) (\[)(\d{8})(\])"""

For lngRow = 1 To UBound(X)
If .test(X(lngRow, 1)) Then
X(lngRow, 2) = .Replace(X(lngRow, 1), "$3")
X(lngRow, 3) = .Replace(X(lngRow, 1), """$1""")
End If
Next
End With
[b1].Resize(UBound(X, 1), 3) = X
End Sub
于 2013-03-27T05:25:17.170 回答
1

这将遍历前 200 行,这是非常原始的代码,没有错误捕获。它假设 RE 中总是有 8 个数字。如果任何公式中存在语法错误,则在尝试将错误公式分配给单元格时会引发错误。

Sub splitSpecial()
    Dim aParts As Variant
    Dim i As Long
    Dim RE As Object
    Dim ret As Object
    Dim sNewFormula As String

    Set RE = CreateObject("vbscript.regexp")

    For i = 1 To 200 'change 200 to be the last row
        aParts = Split(Range("A" & i).Formula, ",")
        RE.Pattern = "\[\d{8}\]"
        RE.Global = True
        Set ret = RE.Execute(Range("A" & i).Formula)
        If ret.Count <> 0 Then
            sNewFormula = aParts(0) & "," & Replace(Replace(ret.Item(0), "[", ""), "]", "") & _
                "," & Replace(Replace(ret.Item(0), "[", ""), "]", "") & ")"
            Range("B" & i).Formula = sNewFormula
            sNewFormula = aParts(0) & "," & Replace(aParts(1), ret.Item(0), "") & _
                "," & Replace(aParts(2), ret.Item(1), "")
            Range("C" & i).Formula = sNewFormula
        End If
    Next i

End Sub
于 2013-03-26T22:25:53.287 回答
0

如果代码总是括在括号中并且总是 8 个数字......您可以使用常规文本查找公式。

    A1 = "DescriptionText1231 [CODE8DIG]"
    B1 = MID(B1,FIND("[",B1)+1,8)

希望我理解你的问题。

于 2013-03-26T21:33:30.947 回答