我有一个大表,其中包含以下方式的描述+项目代码:
"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 ")
有没有人做过类似的事情?我发现这些答案有些相关,但目前还不足以破解正则表达式:
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
如果代码总是用括号括起来,并且总是8个数字......你可以使用常规的文本查找公式。
A1 = "DescriptionText1231 [CODE8DIG]"
B1 = MID(B1,FIND("[",B1)+1,8)
希望我理解你的问题。