只更改单元格中string的特定部分,保持原样

如果单元格中的“show”在“单元格”中,则用“更改”replace单元格中的值。 细胞有一个以上的颜色,我必须保留所有的颜色(除了显示)。

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” 

在这里输入图像说明

 ' 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! 

这是一个示例代码,它将更改文本而不更改文本其他部分的当前颜色或其他字体属性。 我把你的示例文本string与字体颜色显示在单元格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()。Insert()行的重要方面。 字符(开始,长度)是要删除的部分和大小,插入将新的(和更长的)文本置于其位置。