这里是对 UDF² 中正则表达式¹ 的简要介绍。
Function partNums(str As String, _
Optional num As Integer = 1)
Dim tmp As String
Static rgx As Object
'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF
If rgx Is Nothing Then
Set rgx = CreateObject("VBScript.RegExp")
End If
partNums = vbNullString
With rgx
.Global = True
.IgnoreCase = True
.MultiLine = False
.Pattern = "\([A-Z]{1}/[A-Z]{1}\)"
If .Test(str) Then
tmp = .Execute(str)(0)
Select Case num
Case 2
tmp = Mid(tmp, 4, 1)
Case Else
tmp = Mid(tmp, 2, 1)
End Select
partNums = .Replace(str, tmp)
End If
End With
End Function
在 B2:B3 中,
=partNums(A2)
=partNums(A3,2)
这是一个大量重复的 UDF,可处理 1 到 3 个字符。
Function partNums(str As String, _
Optional num As Integer = 1)
Dim tmp As String
Static rgx As Object
'with rgx as static, it only has to be created once; beneficial when filling a long column with this UDF
If rgx Is Nothing Then
Set rgx = CreateObject("VBScript.RegExp")
End If
partNums = vbNullString
With rgx
.Global = True
.IgnoreCase = True
.MultiLine = False
.Pattern = "\([A-Z]{1,3}/[A-Z]{1,3}\)"
If .Test(str) Then
tmp = .Execute(str)(0)
tmp = Split(Replace(Replace(tmp, Chr(40), vbNullString), Chr(41), vbNullString), Chr(47))(num - 1)
partNums = .Replace(str, tmp)
End If
End With
End Function
¹ regex 的问题通常可以通过How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops 中的解决方案来回答。
² 用户定义函数(又名 UDF)被放入标准模块代码表中。点击Alt+F11,当VBE打开时,立即使用下拉菜单Insert ► Module(Alt+I,M)。将功能代码粘贴到标题为 Book1 - Module1 (Code) 的新模块代码表中。点击 Alt+Q 返回您的工作表。