[英]Search Multiple strings and assign a string in previous cell in Excel VBA Macro
[英]VBA regex: extract multiple strings between strings within Excel cell with custom function
在 Excel 列中,我有以下數據:
“奧迪 (ADI)、梅賽德斯 (modelx) (MEX)、法拉利超快、高 PS (FEH)”
有數百個模型由名稱和括號中三個大寫字母的縮寫描述。
我只需要提取名稱和縮寫來分隔單元格。 我通過以下模塊成功地為縮寫做到了這一點:
Function extrABR(cellRef) As String
Dim RE As Object, MC As Object, M As Object
Dim sTemp As Variant
Const sPat As String = "([A-Z][A-Z][A-Z][A-Z]?)" ' this is my regex to match my string
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.MultiLine = True
.Pattern = sPat
If .Test(cellRef) Then
Set MC = .Execute(cellRef)
For Each M In MC
sTemp = sTemp & ", " & M.SubMatches(0)
Next M
End If
End With
extrABR = Mid(sTemp, 3)
End Function
但是,我無法為 names 這樣做。 我想通過以下正則表達式交換正則表達式: (^(.*?)(?= \\([AZ][AZ][AZ])|(?<=, )(.*)(?= \\([AZ][AZ][AZ]))
,但 VBA 似乎不允許后視。
任何想法?
正確,不支持后視,但只有在您預期的匹配重疊時才需要它們。 情況並非如此,您的所有匹配項都不重疊。 因此,您可以再次依賴capture :
(?:^|,)\s*(.*?)(?=\s*\([A-Z]{3,}\))
請參閱正則表達式演示。 第 1 組值通過.Submatches(0)
訪問。
詳情:
(?:^|,)
- 字符串開頭或逗號\\s*
- 零個或多個空白字符(.*?)
- 捕獲組 1:盡可能少的除換行符以外的任何零個或多個字符(?=\\s*\\([AZ]{3,}\\))
- 一個正向前瞻,匹配緊跟其后的位置
\\s*
- 零個或多個空白字符\\(
- a (
字符[AZ]{3,}
- 三個或更多大寫字符\\)
- a )
字符。演示截圖:
RE.REPLACE——試試這個函數。括號之間的任何東西都將被替換為“”,只給你一串模型名稱,如果需要,你可以用逗號分割並獲取字符串數組。
Function ModelNames(cellRef) As String
Dim RE As Object, MC As Object, M As Object
Dim sTemp As Variant, sPat As String
sPat = "\([^)]+\)"
'Or you can use your formula pattern "([A-Z][A-Z][A-Z][A-Z]?)" to get (modelx) in the final output.
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.MultiLine = True
.Pattern = sPat
End With
ModelNames = RE.Replace(cellRef, "")
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.