ReplaceBrackets1:使用RegEx提取列號。處理100K記錄需要15.03秒。
Sub ReplaceBrackets1()
'http://analystcave.com/excel-regex-tutorial/
Dim c As Range
Dim Match As Object, Matches As Object, regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Global = True
.Pattern = "\[(.*?)\]"
End With
For Each c In Range("K3", Range("K" & Rows.Count).End(xlUp))
If regex.Test(c.Text) Then
Set Matches = regex.Execute(c.Text)
For Each Match In Matches
c.Replace Match, c.EntireRow.Columns(CInt(Match.SubMatches(0)))
Next Match
End If
Next
End Sub
ReplaceBrackets2:loades數據到陣列,使用正則表達式提取的列數和只寫工作表1時間。處理100K記錄需要1.27秒。
Sub ReplaceBrackets2()
'http://analystcave.com/excel-regex-tutorial/
Dim x As Long, column As Long
Dim arData, values
Dim Match As Object, Matches As Object, regex As Object
Set regex = CreateObject("VBScript.RegExp")
With regex
.Global = True
.Pattern = "\[(.*?)\]"
End With
values = Range("K3", Range("K" & Rows.Count).End(xlUp))
arData = Range("A3", "L" & UBound(values, 1) + 2)
For x = 1 To UBound(values, 1)
If regex.Test(values(x, 1)) Then
Set Matches = regex.Execute(values(x, 1))
For Each Match In Matches
column = Match.SubMatches(0)
values(x, 1) = arData(x, column)
Next Match
End If
Next
Range("K3", Range("K" & Rows.Count).End(xlUp)) = values
End Sub
轉換ReplaceBrackets1
爲UDF
(getReplacedText
)後,我驚訝地發現,只用了2.53秒填寫爲100K記錄的配方。我不知道這樣做會比原來快。但擁有這麼多公式確實會減慢電子表格的速度。
getReplacedText:使用靜態RegEx解析數據。
Function getReplacedText(ReplacementText As String, Source As Range)
'http://analystcave.com/excel-regex-tutorial/
Dim Match As Object, Matches As Object
Static regex As Object
If regex Is Nothing Then
Set regex = CreateObject("VBScript.RegExp")
With regex
.Global = True
.Pattern = "\[(.*?)\]"
End With
End If
If regex.Test(ReplacementText) Then
Set Matches = regex.Execute(ReplacementText)
For Each Match In Matches
ReplacementText = Replace(ReplacementText, Match, Source.Columns(CInt(Match.SubMatches(0))))
Next Match
End If
getReplacedText = ReplacementText
End Function
是的,VBA很容易處理這個問題。你確實需要提供你到目前爲止所嘗試過的。請記住,SO不是一個代碼編寫服務,而是一個在編碼問題上得到尖銳問題的論壇。作爲開始的一點,您可以創建一個循環遍歷K列中的範圍,爲每個單元格提取標記並替換適當的字符串。一旦你有了你的代碼,如果你仍然有問題,你可以在SO上分享代碼來獲得有關你的問題的幫助。問候, – nbayly