2011-11-16 65 views
38

我想为excel 2010编写一个函数,它将采用非结构化文本的单元格,查找称为sdi值的东西,如果找到,则返回该编号。 sdi值将显示为sdi ####。我要的是回到SDI和它后面的数字sepecific,因此,如果单元格中包含“一些文本SDI 1234一些文字”功能将返回SDI 1234在VBA中返回一个正则表达式匹配(excel)

这是我的函数:

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 

如果没有sdi号码,它永远不会输入if语句并忠实地返回空字符串。如果有sdi号码,我会获得#VALUE!

我错过了什么?

是的,VBScript已启用。另外,我发现在VBA中使用正则表达式令人沮丧,并且很难在网上找到有用的信息。链接到良好的在线资源将不胜感激。

谢谢

回答

61

您需要访问匹配以获得SDI编号。这是一个可以实现的功能(假设每个单元只有一个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 

如果一个单元格可能有多个要提取的SDI编号,这里是我的RegexExtract函数。您可以在第三放慢参数传递到单独的每场比赛(如逗号它们分开),并且您在实际的函数调用手动输入模式:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ") 

这里是:

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 

*请请注意,我从RegexExtract中取出了“RE.IgnoreCase = True”,但可以将其重新添加,或者如果您愿意,可以将其添加为可选的第4个参数。

+0

很好的答案,谢谢你的功能! –

+0

谢谢Issun - 你的功能奇妙地工作 – TheoRose

+0

+1很好做Issun – brettdj

相关问题