1

我对 VBA 有点陌生,我确实尝试在论坛中搜索这个主题,但我不确定我使用了正确的词来搜索。这是我的问题:

我正在使用 VBA 通过正则表达式提取缺失的信息。假设我有一个包含电话和传真号码的文本表。我想将这些数字收集到一个表格中。到目前为止,我的代码工作正常,但是当我有多个数字(比如常规和 800 #s)由于某种原因时,只检索到一个数字,而不是其他数字。如何将所有结果添加到表中?

询问:

SELECT regxtr([Table1]![field1]) AS phone FROM Table1;

(regxtr) 函数的 VBA 代码:

Option Compare Database

Function regxtr(ByVal Target As String) As String 'Target is the field we are 'extracting from

Dim re As New RegExp
Dim oMatches As Object
Dim oMatch As Object
Dim n As Long
n = 0

'Set re = CreateObject("vbscript.regexp")
With re
.Global = True
.IgnoreCase = True
.Multiline = True
.Pattern = "(\d\d\d.\d\d\d\.\d\d\d\d)" 'keeping the pattern simple for now just to test
End With

    'test before executing
If re.Test(Target) = True Then
Set oMatches = re.Execute(Target)

         'attempt to get all matches. THIS IS WHERE I AM FAILING
For n = 0 To oMatches.Count - 1
Set oMatch = oMatches(n)

   regxtr = oMatch.Value
    n = n + 1  ' does this even belong here?

    Next
End If


End Function

我怎样才能让所有匹配项都填充查询中的字段 [phone]?任何帮助将不胜感激。

4

1 回答 1

0

首先是术语的更正。您不是在寻找“子匹配”(在其他正则表达式实现中也称为“捕获组”)。您正在为您的正则表达式寻找“匹配项”,因此您可以删除括号并使用\d{3}.\d{3}.\d{4}也就是说,这可能是您需要的:

Function regxtr(ByVal Target As String) As String 'Target is the field we are 'extracting from
Dim re As New RegExp
Dim oMatches As Object
Dim oMatch As Object

With re
    .Global = True
    .IgnoreCase = True
    .Multiline = True
    .Pattern = "\d{3}.\d{3}.\d{4}" 'keeping the pattern simple for now just to test
End With

If re.Test(Target) = True Then
    Set oMatches = re.Execute(Target)
    For Each oMatch In oMatches  'Note: you may get multiple matches because you set re.Global = True above, otherwise you would only get the first match
        regxtr = regxtr & " " & oMatch 'Note: this is awkward and not advisable as a way to return the values. This is just an example.
    Next oMatch
End If
End Function

作为测试:

?regxtr("foo 993-242.1231bar994.425-1234hello987.234.2424 world 999.342-5252")
 993-242.1231 994.425-1234 987.234.2424 999.342-5252
于 2012-06-11T18:14:36.513 回答