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

The*_*ose 45 regex excel vba

我正在尝试为excel 2010编写一个函数,它将获取非结构化文本的单元格,查找称为sdi值的内容,如果找到,则返回该数字.sdi值将显示为sdi ####.我想要的是返回sdi及其后面的特定数字,因此如果单元格包含"some text sdi 1234 some some text",则该函数将返回sdi 1234.

这是我的功能:

Function SdiTest(LookIn As String) As String
  Dim temp As String
  Dim STA As Object
  temp = ""

  Set SDI = CreateObject("VBScript.RegExp")
  SDI.IgnoreCase = True
  SDI.Pattern = "sdi [1-9]*"
  SDI.Global = True

  If SDI.Test(LookIn) Then
    temp = SDI.Execute(LookIn)
  End If

  SdiTest = temp
End Function
Run Code Online (Sandbox Code Playgroud)

如果没有sdi号,它永远不会进入if语句并尽职尽责地返回空字符串.如果有一个sdi号码,我会得到#VALUE!

我错过了什么?

是的,VBScript已启用.另外,我发现在VBA中使用正则表达式很难受,并且很难在线查找有用的信息.很高兴能够获得良好在线资源的链接.

谢谢

aev*_*nko 73

您需要访问匹配项才能获得SDI号码.这是一个可以执行此操作的函数(假设每个单元只有1个SDI编号).

对于正则表达式,我使用"sdi后跟一个空格和一个或多个数字".你有"sdi后跟一个空格和零个或多个数字".您可以简单地将我的模式中的+更改为*以返回到您拥有的内容.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function
Run Code Online (Sandbox Code Playgroud)

如果一个单元格可能有多个要提取的SDI编号,这里是我的RegexExtract函数.您可以传入第三个参数来分隔每个匹配(如逗号分隔它们),然后在实际函数调用中手动输入模式:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Run Code Online (Sandbox Code Playgroud)

这是:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function
Run Code Online (Sandbox Code Playgroud)

*请注意我从RegexExtract中取出了"RE.IgnoreCase = True",但您可以将其添加回来,如果愿意,甚至可以将其添加为可选的第4个参数.