Excel VBA将变量传递给正则表达式模式

时间:2020-04-10 09:25:54

标签: regex excel

我正在使用以下代码从字符串中提取5个或更多连续数字的模式

Public Function ExtractConsNo(Cno As String)

Dim regEx As New RegExp

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        'This matches the pattern: e.g. five or more consecutive numbers
        .Pattern = "(\d{5,})"
    End With

    If regEx.Test(Cno) Then
        ExtractConsNo = regEx.Execute(Cno)(0)
    Else
        ExtractConsNo = 0
    End If

End Function

我试图使“ 5”成为变量并将其传递给正则表达式模式,我尝试添加变量并在VBA中编译String,即

Public Function ExtractConsNo(Cno As String, X As Integer)
Dim S As String
    S = """(\d{" & X & ",})"""
    .pattern = S

显然失败了,我尝试了很多方法,现在我很困惑,任何帮助将不胜感激

吉姆

0 个答案:

没有答案