Excel VBA - Delete Single Character from Cell without losing formatting of remainder of cell contents

爱⌒轻易说出口 提交于 2021-01-27 22:07:45

问题


I am trying to delete the first occurrence of "<" and ">" in a cell without losing formatting of the remainder of the cell's contents.

I have looked in several places here, and other, to no avail.

This is what I am trying to do:

Say "A1" contains the text:

"This is <a> long string with several <occurrences> of a <special> character."

In any case, What I am trying to do is remove the ">", and in a perfect world the "<", from the first word which contains them while maintaining the bold formatting as well as the "<" and ">" on the next word containing them.

This is ONLY other code executing prior to the code I am having issues with.

inTx = Range("A2").Value
outTx = Replace(inTx, "Init_Day", Range("A3").Value)
Range("A2").Value = outTx

Which replaces the <placeholder> text with the actual text, a two digit number in this case.

Here is the code that is not working for me:

SearchString = Range("A2").Value
Char1 = "<"
Char2 = ">"
For i = 1 To Len(SearchString)
    If Mid(SearchString, i, 1) = Char1 Then
        startPos = i
        Exit For
    End If
Next i
For i = 1 To Len(SearchString)
    If Mid(SearchString, i, 1) = Char2 Then
        endPos = i
        Exit For
    End If
Next i
Range("A2").Characters(startPos, endPos - startPos).Font.Bold = True
Range("A2").Characters(startPos - 1, 1).Delete

All code works fine until I reach the last line:

Range("A2").Characters(startPos - 1, 1).Delete

then nothing happens.

I've even tried:

Range("A2").Characters(startPos - 1, 20).Delete

Still nothing...

I know this should be easy but I can't seem to figure it out.

Thanks in advance.


回答1:


The following code:

Sub Foo()
    Const Char1 As String = "<", Char2 As String = ">"
    Dim SearchString As String
    Dim i As Integer, startPos As Integer, endPos As Integer
    SearchString = Range("A2").Value
    startPos = InStr(SearchString, Char1)
    endPos = InStr(SearchString, Char2)
    Range("A2").Characters(startPos, endPos - startPos).Font.Bold = True
    Range("A2").Characters(startPos, 1).Delete
    Range("A2").Characters(endPos - 1, 1).Delete
End Sub

Turns this:

Some <bold> text I just <made> up.

Into this:

Some bold text I just <made> up.

Is that what you are looking for?



来源:https://stackoverflow.com/questions/13150231/excel-vba-delete-single-character-from-cell-without-losing-formatting-of-remai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!