我的VBA函数应采用一个引用一定范围单位的字符串(即"WWW1-5"),然后返回另一个字符串。

我想将参数放在逗号分隔的字符串中,
所以"WWW1-5"应该变成"WWW1, WWW2, WWW3, WWW4, WWW5".

并非总是一个数字。例如,我可能需要分隔"XXX11-18"或类似内容。

我从没使用过正则表达式,但是一直在尝试不同的方法来完成这项工作,而且似乎只能找到1个匹配项而不是3个匹配项。

有任何想法吗?这是我的代码:

Private Function split_group(ByVal group As String) As String
    Dim re As Object
    Dim matches As Object
    Dim result As String
    Dim prefix As String
    Dim startVar As Integer
    Dim endVar As Integer
    Dim i As Integer

    Set re = CreateObject("vbscript.regexp")
    re.Pattern = "([A-Z]+)(\d+)[-](\d+)"
    re.IgnoreCase = False
    Set matches = re.Execute(group)

    Debug.Print matches.Count

    If matches.Count <> 0 Then
        prefix = matches.Item(0)
        startVar = CInt(matches.Item(1)) 'error occurs here
        endVar = CInt(matches.Item(2))
        result = ""

        For i = startVar To endVar - 1
            result = result & prefix & i & ","
        Next i

        split_group = result & prefix & endVar
    Else
        MsgBox "There is an error with splitting a group."
        split_group = "ERROR"
    End If

End Function


我尝试设置global = true,但我意识到这不是问题。该错误实际上是在带有注释的行上发生的,但我认为是因为只有1个匹配项。

我尝试使用谷歌搜索,但是每个人的情况似乎都与我的有所不同,并且由于这是我第一次使用RE,所以我认为我对模式的理解不足以了解是否可能是问题所在。

谢谢!

最佳答案

请尝试以下修改后的Function

Private Function split_metergroup(ByVal group As String) As String

    Dim re As Object
    Dim matches As Variant
    Dim result As String
    Dim prefix As String
    Dim startVar As Integer
    Dim endVar As Integer
    Dim i As Integer

    Set re = CreateObject("VBScript.RegExp")
    With re
        .Global = True
        .IgnoreCase = True
        .Pattern = "[0-9]{1,20}" '<-- Modified the Pattern
    End With

    Set matches = re.Execute(group)
    If matches.Count > 0 Then
        startVar = CInt(matches.Item(0)) ' <-- modified
        endVar = CInt(matches.Item(1)) ' <-- modified
        prefix = Left(group, InStr(group, startVar) - 1) ' <-- modified
        result = ""

        For i = startVar To endVar - 1
            result = result & prefix & i & ","
        Next i
        split_metergroup = result & prefix & endVar
    Else
        MsgBox "There is an error with splitting a meter group."
        split_metergroup = "ERROR"
    End If

End Function


我用以下方法测试过的Sub

Option Explicit

Sub TestRegEx()

Dim Res As String

Res = split_metergroup("DEV11-18")
Debug.Print Res

End Sub


结果我进入即时窗口:

DEV11,DEV12,DEV13,DEV14,DEV15,DEV16,DEV17,DEV18

09-17 20:56