我的VBA函數應該採用引用一系列單位的字符串(即"WAL1-5"
),然後返回另一個字符串。正則表達式只返回1個匹配
我要帶的說法,並把它放在一個逗號分隔字符串, 所以"WAL1-5"
應該成爲"WAL1, WAL2, WAL3, WAL4, WAL5".
它並不總是將是一個單一的數字。例如,我可能需要分開"DEV11-18"
或類似的東西。
我從來沒有使用正則表達式,但不斷嘗試不同的東西,使這項工作,它似乎只能找到1場,而不是3
任何想法?這是我的代碼:
Private Function split_metergroup(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_metergroup = result & prefix & endVar
Else
MsgBox "There is an error with splitting a meter group."
split_metergroup = "ERROR"
End If
End Function
我試着設置global = true,但我意識到這不是問題。該錯誤實際上發生在評論行上,但我認爲這是因爲只有1次匹配。
我試過Google搜索它,但每個人的情況似乎都與我的有點不同,因爲這是我第一次使用RE,我不認爲我理解模式足以查看是否可能是問題所在。
謝謝!
這工作!非常感謝你。:) 你知道原始圖案可能發生了什麼嗎?這並不重要,因爲我有工作代碼,但我只是好奇未來的參考。 –
@TiannaProcon歡迎您,不要忘記標記爲「答案」 –