Excel VBA - 从单元格中删除单个字符而不会丢失剩余单元格内容的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13150231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA - Delete Single Character from Cell without losing formatting of remainder of cell contents
提问by IIIOXIII
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:
说“A1”包含文本:
"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.
<placeholder>
用实际文本替换文本,在这种情况下是两位数字。
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.
提前致谢。
采纳答案by mwolfe02
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.
Some <bold> text I just <made> up.
Into this:
进入这个:
Some bold text I just <made> up.
Is that what you are looking for?
这就是你要找的吗?