如何构build正则expression式来查找单元格中的“”的不常见
我有一个大桌子,其中包含以下方式的描述+项目代码:
"description [#######]" (Code being enclosed in "[]" and composed of 8 numbers)
我需要在不同的列中分离代码和描述。 正则expression式需要的原因是上面的描述是在excel公式里面find的:=
=IF(xyz, "description1 [1######]", "description2 [2######]")
所以最终的结果应该是:
column 1: =IF(xyz, 1######, 2######) column 2: =IF(xyz, "description1 ", "description2 ")
有没有人做过类似的事情? 我发现这些答案有点相关,但是目前还不知道破解正则expression式:
在VBA中返回一个正则expression式匹配(excel)
VBA正则expression式匹配date
使用RegExp
replace简化了replace
此代码在列A上使用variables数组,结果在列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
这将遍历前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
如果代码总是括在括号内,并且总是8个数字…您可以使用常规文本查找公式。
A1 = "DescriptionText1231 [CODE8DIG]" B1 = MID(B1,FIND("[",B1)+1,8)
希望我明白你的问题。