Excel VBA-从单元格中删除单个字符,而不会丢失其余单元格内容的格式 [英] Excel VBA - Delete Single Character from Cell without losing formatting of remainder of cell contents
问题描述
我正在尝试删除首次出现的<".和>",而不会丢失该单元格其余内容的格式.
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.
这就是我想要做的:
说"A1"包含以下文本:
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
将< placeholder>
文本替换为实际文本,在这种情况下为两位数.
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
那什么也没发生.
我什至尝试过:
Range("A2").Characters(startPos - 1, 20).Delete
什么都没有...
我知道这应该很容易,但是我似乎无法弄清楚.
I know this should be easy but I can't seem to figure it out.
谢谢.
推荐答案
以下代码:
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
将其转为:
有些< bold>我刚刚< made>
在此:
Some bold text I just <made> up.
您正在寻找什么吗?
这篇关于Excel VBA-从单元格中删除单个字符,而不会丢失其余单元格内容的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!