我有几个带文字的栏目。此外,我有一个名为Replacement text
的列。此列包含其中包含标记的字符串,如[1], [2], etc.
我想用标记行中的文本替换标记。
例如,Here you can find [5]
变为Here you can find b
,因为[5]
是标记列,而字符串b
的行中是标记的值。
我在考虑创建一个大if-else
构造和substitute
文本,这非常容易出错。
但是,我问你是否有更简单的解决方案?
感谢您的投入!
答案 0 :(得分:3)
这个答案是托马斯·因兹纳(Thomas Inzina)的第一个答案的高度抄袭,但是一个非常简单的替代方法是:
Sub ReplaceText()
Dim r As Long
Dim c As Long
With ActiveSheet
For r = 3 To .Range("K" & .Rows.Count).End(xlUp).Row
For c = 1 To 10
.Cells(r, "K").Replace "[" & c & "]", .Cells(r, c).Value
Next
Next
End With
End Sub
上述代码将尝试使用所有十个列进行替换。
正如托马斯所指出的,以下代码只会在需要替换时进行替换,因此可能会快一个数量级,因此无疑是一个更好的解决方案:
Sub ReplaceText()
Dim r As Long
Dim c As Long
With ActiveSheet
For r = 3 To .Range("K" & .Rows.Count).End(xlUp).Row
For c = 1 To 10
If Instr(.Cells(r, "K").Value, "[" & c & "]") > 0 Then
.Cells(r, "K").Replace "[" & c & "]", .Cells(r, c).Value
End If
Next
Next
End With
End Sub
(非常感谢Thomas为两种不同方法进行速度测试所做的努力。)
答案 1 :(得分:2)
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:将数据存入数组,使用RegEx提取列号,只写入工作表一次。处理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