【问题标题】:How To Find And Replace Text Then Preserve Formatting In Excel?如何在 Excel 中查找和替换文本然后保留格式?
【发布时间】:2019-03-19 16:12:56
【问题描述】:

在 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 命令粘贴整个代码)。 代码看起来没问题,但在代码的最后一行是红色的(在我必须决定要更改哪个单词的那一行)。

有什么建议吗?

非常感谢

【问题讨论】:

  • minimal reproducible example 是必需的,如果您遇到困难,请参阅 stackoverflow.com/editing-help
  • 你能发布代码吗?有人会编辑您的代码以使其适合。
  • 您在过程调用上有一条红线,因为有很多 ",所以它使用的字符串比它应该的要多。
  • 您遇到了引号问题。见how do I put double quotes in a string in vba
  • 大家好,我用这行代码解决了这个问题: Call CharactersReplace(xRg, "Test1", "Test2", True) 工作正常,但我有一个问题:而不是 "Test2 ",我想在 Excel 行上按 ALT+ENTER。 VBA上有代码可以做到吗?非常感谢。

标签: excel vba


【解决方案1】:

最后一行代码应该是:

Call CharactersReplace(xRg, "<span style=""background-color: #ffff00;"">KK</span>"", ""<span style=""background-color: #ffff00;"">Kutools</span>", True)

最外层引号内的每个" 都加倍。

要回答您在 cmets 中发布的问题,Alt+Enter 相当于 VBA 中的 vbLfChr(10)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 2014-11-06
    • 2015-09-23
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多