VBA正则表达式替换循环

问题描述 投票:0回答:3

目前正在使用正则表达式替换循环以进行票证系统格式化

我正在测试一段代码,它将使正则表达式匹配票号的特定格式。票号应为“INC01234567”(最多8位数字)。 “INC”可以是可选的,因此用户只需输入结束号码(IE 1234567),循环就会添加额外的“0”以使数字量最多为8位。但是,目前我仍然遇到一个数学逻辑问题,如果你输入一个完整的票号,它会在结果中添加一个太多的0。

一世

Sub Incident()
Dim sInc As String  'Incident Number Field
Dim strPattern As String: strPattern = "^(?:INC|NC|C)?([0-9]{1,8}$)"
Dim strReplaceINC As String: strReplaceINC = "$1"
Dim regEx As New RegExp
Dim strInput As String
Dim IncResult As Boolean

Do
    If strPattern <> "" Then

        strInput = inputbox("Input Incident Number", "Ticket Number")

        If strInput = vbNullString Then
            Exit Sub
        End If

        IncResult = False

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            sInc = regEx.Replace(strInput, strReplaceINC)
            Dim L As Integer: L = Len(sInc)
            Do
                sInc = "0" & sInc
                L = L + 1
            Loop While L <= 8
            sInc = "INC" & sInc
            IncResult = True
            'sInc = strInput
        Else
            MsgBox ("Please input a valid ticket number format")
            IncResult = False
        End If
    End If

Loop While IncResult = False
MsgBox (sInc)
End Sub
regex vba outlook-vba
3个回答
2
投票

循环是不必要的开销,只需使用Format()

替换所有这些:

Dim L As Integer: L = Len(sInc)
Do
    sInc = "0" & sInc
    L = L + 1
Loop While L <= 8
sInc = "INC" & sInc

有了这个:

sInc = "INC" & Format(sInc, "00000000")

0
投票

您正在检查循环结束时的条件,这意味着无论sInc的长度如何,循环将始终至少运行一次。

只需更换:

Do
    sInc = "0" & sInc
    L = L + 1
Loop While L <= 8

附:

While L < 8
    sInc = "0" & sInc
    L = L + 1
Wend

0
投票

正则表达式"^(?:INC|NC|C)?([0-9]{1,8}$)"匹配8位票号012345678,不是吗?所以If regEx.Test(strInput) Then将是真的,并且do..loop至少在它休息之前运行

© www.soinside.com 2019 - 2024. All rights reserved.