VBA Regex Replace Loop

纵饮孤独 提交于 2019-12-13 02:56:22

问题


Currently having issues with a regex replace loop for ticketing system formatting

I am testing a segment of code that will regex match a specific format for a ticket number. The ticket number should be in a format of "INC01234567" (up to 8 numeric digits). The "INC" can be optional so that the user can just type in the ending number (IE 1234567) and the loop will add the additional "0's" to give the numeric amount up to 8 digits. Currently, however, I am stuck on a math logic issue where it is adding one too many 0's to the result if you type in a full ticket number.

I

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

回答1:


The loop is unnecessary overhead, just use Format()

Replace all of this:

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

With this:

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



回答2:


You're checking the condition at the end of the loop, meaning the loop will always run at least once, regardless of the length of sInc.

Just replace:

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

With:

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



回答3:


The regex "^(?:INC|NC|C)?([0-9]{1,8}$)" does match a 8 digit ticket number 012345678, doesn't it? So If regEx.Test(strInput) Then will be true, and the do..loop runs at least on time before it breaks



来源:https://stackoverflow.com/questions/52482997/vba-regex-replace-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!