我有什么:
(3672)
)在一串文字和数字中。 到目前为止我所拥有的:
我可以成功识别B列中有括号括起来的四位数的单元格。问题是它返回整个标题,包括四个数字。
取自:VBA RegEx extracting data from within a string
注意:我正在使用Excel Professional Plus 2010,选中了“Microsoft VBScript Regular Expressions 5.5”旁边的框。
Sub ExtractTicker()
Dim regEx
Dim i As Long
Dim pattern As String
Set regEx = CreateObject("VBScript.RegExp")
regEx.IgnoreCase = True
regEx.Global = True
regEx.pattern = "(\()([0-9]{4})(\))"
For i = 2 To ActiveSheet.UsedRange.Rows.Count
If (regEx.Test(Cells(i, 2).Value)) Then
Cells(i, 3).Value = regEx.Replace(Cells(i, 2).Value, "$2")
End If
Next i
End Sub
答案 0 :(得分:0)
尝试
regEx.pattern = "(.*\()([0-9]{4})(\).*)"
.*
以及字符串的开头和结尾确保您捕获整个字符串,然后将其完全替换为第二个子匹配([0-9] {4})
完全优化代码
码
Sub ExtractTicker()
Dim regEx As Object
Dim pattern As String
Dim X
Dim lngCNt As Long
X = Range([b1], Cells(Rows.Count, "B").End(xlUp)).Value2
Set regEx = CreateObject("VBScript.RegExp")
With regEx
.pattern = "(.*\()([0-9]{4})(\).*)"
For lngCNt = 1 To UBound(X)
If .Test(X(lngCNt, 1)) Then
X(lngCNt, 1) = .Replace(X(lngCNt, 1), "$2")
Else
X(lngCNt, 1) = vbNullString
End If
Next
End With
[c1].Resize(UBound(X, 1), 1).Value2 = X
End Sub