仅更改单元格中字符串的特定部分,保持原样

时间:2015-03-26 08:36:23

标签: excel vba replace

从单元格中取值,如果单元格中显示“show”,则将其替换为“change”。 单元格有多种颜色,我必须保持所有单词的颜色(显示除外)。

text = Cells(row, col).value
' text have other colors then black – and I want to keep that
text = “hi, this test show how the text can look like”

enter image description here

' want to replace “show” to “change” and keep the text coloring.
' similarly I can set the color with
Cells(row, col).Characters(15, Len(show)).Font.Color = vbBlue
' Can I change the text in a similar way?
' If I use:
Cells(row, col).value = text
' All color is gone!

1 个答案:

答案 0 :(得分:3)

下面是一个示例代码,它将更改文本而不更改文本其他部分的当前颜色或其他字体属性。我将带有字体颜色的示例文本字符串显示在单元格A1中。

Public Sub test()
  Dim str As String, pos As Long
  str = Range("A1").Value
  pos = InStr(str, "show")
  Range("A1").Characters(pos, 4).Insert ("change")
End Sub

注意Characters()的重要方面。插入()行。字符(开头,长度)是您要删除的部分和大小,插入将新(和更长)的文本放在其位置。