在此外@RolandSmith寫道,這是一種在Excel中使用正則表達式的方法 - VBA
Option Explicit
Function ExtractSpecial(S As String, Index As Long) As String
Dim RE As Object, MC As Object
Const sPat As String = "([a-z]+)\s+(special)\s+([^a-z]+)"
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.ignorecase = True
.MultiLine = False
.Pattern = sPat
If .test(S) = True Then
Set MC = .Execute(S)
ExtractSpecial = MC(0).submatches(Index - 1)
End If
End With
End Function
在此UDF的Index
參數對應於從匹配集合返回無論是第一,第二或第三子匹配,所以你可以很容易地分割原始字符串轉換成你的三個所需的組件。
既然你寫你有「千行」,你可能更願意運行宏。宏將更快地處理數據,但不是動態的。下面的宏假設您的原始數據位於Sheet2的A列中,並將結果放在同一工作表上的C:E列中。您可以輕鬆地改變這些參數:
Sub ExtractSpec()
Dim RE As Object, MC As Object
Dim wsSrc As Worksheet, wsRes As Worksheet, rRes As Range
Dim vSrc As Variant, vRes As Variant
Dim I As Long
Set wsSrc = Worksheets("sheet2")
Set wsRes = Worksheets("sheet2")
Set rRes = wsRes.Cells(1, 3)
With wsSrc
vSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.MultiLine = False
.ignorecase = True
.Pattern = "([a-z]+)\s+(special)\s+([^a-z]+)"
ReDim vRes(1 To UBound(vSrc), 1 To 3)
For I = 1 To UBound(vSrc)
If .test(vSrc(I, 1)) = True Then
Set MC = .Execute(vSrc(I, 1))
vRes(I, 1) = MC(0).submatches(0)
vRes(I, 2) = MC(0).submatches(1)
vRes(I, 3) = MC(0).submatches(2)
End If
Next I
End With
Set rRes = rRes.Resize(UBound(vRes, 1), UBound(vRes, 2))
With rRes
.EntireColumn.Clear
.Value = vRes
.EntireColumn.AutoFit
End With
End Sub
這是完美的。我唯一的問題是它會自動將一些數字轉換爲日期。我嘗試了建議的方法[例如將列設置爲文本],但仍然存在此問題。 – KitKat
我刪除了.EntireColumn.Clear,它工作! – KitKat
@KitKat嘗試在CStr函數中包裝MC(0)...。或者用單引號前置 –