使用RegEx在VBA中分割string

我是VBA的新手,想要寻求一些关于使用正则expression式的帮助,我希望能够启发我做错了什么。 我目前正在尝试将date分成单独的date,月份和年份,可能的分隔符包括“,”,“ – ”和“/”。

Function formattedDate(inputDate As String) As String Dim dateString As String Dim dateStringArray() As String Dim day As Integer Dim month As String Dim year As Integer Dim assembledDate As String Dim monthNum As Integer Dim tempArray() As String Dim pattern As String() Dim RegEx As Object dateString = inputDate Set RegEx = CreateObject("VBScript.RegExp") pattern = "(/)|(,)|(-)" dateStringArray() = RegEx.Split(dateString, pattern) ' .... code continues 

这是我目前正在做的。 但是,在RegEx.Split函数中似乎有什么错误,因为它似乎导致我的代码挂起,而不是进一步处理。

为了确认,我做了一些简单的事情:

 MsgBox("Hi") pattern = "(/)|(,)|(-)" dateStringArray() = RegEx.Split(dateString, pattern) MsgBox("Bye") 

“嗨”msgboxpopup,但“再见”msgbox永远不会popup,进一步下来的代码似乎根本没有得到执行,这导致我怀疑RegEx.Split导致它被卡住。

我可以检查我是否真正使用RegEx.Split正确的方式吗? 根据这里的 MSDN,Split(String,String)也返回一个string数组。

谢谢!

编辑 :我试图不去探索CDate()函数,因为我试图不依赖于用户的计算机的区域设置。

在VBA中用正则expression式分割string:

 Public Function SplitRe(text As String, pattern As String, Optional ignorecase As Boolean) As String() Static re As Object If re Is Nothing Then Set re = CreateObject("VBScript.RegExp") re.Global = True re.MultiLine = True End If re.ignorecase = ignorecase re.pattern = pattern SplitRe = Strings.Split(re.Replace(text, vbNullChar), vbNullChar) End Function 

用法示例:

 Dim v v = SplitRe("a,b/c;d", "[,;/]") 

引用VbScript Regexp文档中的示例: https : //msdn.microsoft.com/en-us/library/y27d2​​s18%28v=vs.84%29.aspx

 Function SubMatchTest(inpStr) Dim retStr Dim oRe, oMatch, oMatches Set oRe = New RegExp ' Look for an e-mail address (not a perfect RegExp) oRe.Pattern = "(\w+)@(\w+)\.(\w+)" ' Get the Matches collection Set oMatches = oRe.Execute(inpStr) ' Get the first item in the Matches collection Set oMatch = oMatches(0) ' Create the results string. ' The Match object is the entire match - dragon@xyzzy.com retStr = "Email address is: " & oMatch & vbNewLine ' Get the sub-matched parts of the address. retStr = retStr & "Email alias is: " & oMatch.SubMatches(0) ' dragon retStr = retStr & vbNewLine retStr = retStr & "Organization is: " & oMatch.SubMatches(1) ' xyzzy SubMatchTest = retStr End Function 

要testing,请致电:

 MsgBox(SubMatchTest("Please send mail to dragon@xyzzy.com. Thanks!")) 

总之,你需要你的模式来匹配你想要提取的各个部分,与之间的分隔符,可能是这样的:

 "(\d+)[/-,](\d+)[/-,](\d+)" 

整个事情将在oMatch,而数字(\ d)将结束在oMatch.SubMatches(0)oMatch.SubMatches(2)。