如何使用VBA在文本字符串中提取多个六位数字

时间:2016-10-06 14:47:37

标签: vba excel-vba excel

我尝试了下面的代码,但它只给了我前6位数字。如何编辑它以从同一个字符串中获取多个6位数字?

Function SixDigit(S As String, Optional index As Long = 0) As String
    Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
    .Pattern = "(?:\b|\D)(\d{6})(?:\b|\D)"
    .Global = True
        SixDigit = .Execute(S)(index).submatches(0)
End With
End Function

1 个答案:

答案 0 :(得分:0)

使用以下代码,来源:

https://msdn.microsoft.com/en-us/library/tdte5kwf(v=vs.84)

Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches, s

' Create the regular expression.
Set regEx = New RegExp
regEx.Pattern = patrn
regEx.IgnoreCase = True
regEx.Global = True

' Do the search.
Set Matches = regEx.Execute(strng)

' Iterate through the Matches collection.
s = ""
For Each Match in Matches
  s = s & "Match found at position "
  s = s & Match.FirstIndex & ". "
  s = s & "Match Value is '"
  s = s & Match.Value & "'."
  s = s & vbCRLF
Next

RegExpTest = s
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))