在Excel上,我试图“查找和替换”一些文本(每个单元格的文本相同),然后将其更改为多个单元格(600多个单元格)。问题是当我这样做时,excel会从文本中删除格式。
我搜索了一些内容,显然您可以通过VBA进行搜索,所以我找到了此VBA宏:
Sub CharactersReplace(Rng As Range, FindText As String, ReplaceText As String, Optional MatchCase As Boolean = False)
'UpdatebyExtendoffice20160711
Dim I As Long
Dim xLenFind As Long
Dim xLenRep As Long
Dim K As Long
Dim xValue As String
Dim M As Long
Dim xCell As Range
xLenFind = Len(FindText)
xLenRep = Len(ReplaceText)
If Not MatchCase Then M = 1
For Each xCell In Rng
If VarType(xCell) = vbString Then
xValue = xCell.Value
K = 0
For I = 1 To Len(xValue)
If StrComp(Mid$(xValue, I, xLenFind), FindText, M) = 0 Then
xCell.Characters(I + K, xLenFind).Insert ReplaceText
K = K + xLenRep - xLenFind
End If
Next
End If
Next
End Sub
Sub Test_CharactersReplace()
Dim xRg As Range
Dim xTxt As String
Dim xCell As Range
On Error Resume Next
If ActiveWindow.RangeSelection.Count > 1 Then
xTxt = ActiveWindow.RangeSelection.AddressLocal
Else
xTxt = ActiveSheet.UsedRange.AddressLocal
End If
Set xRg = Application.InputBox("Select a range:", "Kutools for Excel", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
Call CharactersReplace(xRg, "<span style="background-color: #ffff00;">##</span>", "<span style="background-color: #ffff00;">asdasd</span>", True)
End Sub
(我张贴了一张图片,因为我不知道如何使用CTRL + K命令粘贴整个代码)。 该代码似乎还可以,但是在代码的最后一行(在我必须决定要更改哪个单词的那一行)上是红色的。
有什么建议吗?
非常感谢您
答案 0 :(得分:0)
最后一行代码应该是:
Call CharactersReplace(xRg, "<span style=""background-color: #ffff00;"">KK</span>"", ""<span style=""background-color: #ffff00;"">Kutools</span>", True)
最外面引号内的每个"
都加倍。
要回答您在评论中发布的问题, Alt + Enter 等同于VBA中的vbLf
或Chr(10)
。