以下是兩個VBA解決方案。第一個是用戶定義函數,它將所需的段提取到公式所在的單元格中。代碼中定義了不同的索引。
第二個宏是一個宏,處理列A中的條目,從A2開始,並將三個段分解爲相鄰的三列。不知道哪個會更適合你。
它們都使用正則表達式來獲取不同的子字符串。
都進入常規模塊。
功能:
Option Explicit
'Returns the three components
' Index 1 = Time
' Index 2 = User
' Index 3 = inbox file
Function ParseInbox(S As String, Index As Long) As Variant
Dim RE As Object, MC As Object
'Check that Index is proper
If Index < 1 Or Index > 3 Then
ParseInbox = CVErr(xlErrNum)
Exit Function
End If
Set RE = CreateObject("vbscript.regexp")
With RE
.ignorecase = True
.MultiLine = True
.Pattern = "^.*((?:\d{2}:\d{2}:)\d{2}).*User\s*\[([^]]+).*Inbox/([^]]+)"
If .test(S) = True Then
Set MC = .Execute(S)
ParseInbox = MC(0).submatches(Index - 1)
End If
End With
End Function
宏:
Sub ProcInbox()
'Assumes Data in Column A; starts in A2, and
' to be split into columns B, C & D
Dim RE As Object, MC As Object
Dim S As String
Dim vSrc As Variant, vRes() As Variant
Dim rRes As Range
Dim I As Long, J As Long
'Set upper left corner for results
Set rRes = Range("B1")
'Get data
vSrc = Range("a2", Cells(Rows.Count, "A").End(xlUp))
'Dim Results Array
If IsArray(vSrc) Then
ReDim vRes(1 To UBound(vSrc) + 1, 1 To 3)
Else
ReDim vRes(1 To 2, 1 To 3)
End If
vRes(1, 1) = "Time"
vRes(1, 2) = "User"
vRes(1, 3) = "Inbox File"
Set RE = CreateObject("vbscript.regexp")
With RE
.ignorecase = True
.MultiLine = True
.Pattern = "^.*((?:\d{2}:\d{2}:)\d{2}).*User\s*\[([^]]+).*Inbox/([^]]+)"
If IsArray(vSrc) Then
For I = 1 To UBound(vSrc)
S = vSrc(I, 1)
If .test(S) = True Then
Set MC = .Execute(S)
For J = 0 To 2
vRes(I + 1, J + 1) = MC(0).submatches(J)
Next J
End If
Next I
Else
S = vSrc
If .test(S) = True Then
Set MC = .Execute(S)
For J = 0 To 2
vRes(2, J + 1) = MC(0).submatches(J)
Next J
End If
End If
End With
Set rRes = rRes.Resize(rowsize:=UBound(vRes, 1), columnsize:=UBound(vRes, 2))
rRes.EntireColumn.Clear
rRes = vRes
rRes.EntireColumn.AutoFit
End Sub
有沒有你已經嘗試任何代碼?如果是這樣,結果如何?如果你不知道從哪裏開始,我建議查看'For'循環和'InStr'函數。 – thunderblaster