[英]Usage of WorksheetFunction.Trim in Excel VBA is removing coloring in cell
I'm developing in VBA Excel and I discovered that I use WorksheetFunction.Trim(Cells(1,1)) where this cells contain any colored element, this element become colored by default.我正在 VBA Excel 开发,我发现我使用 WorksheetFunction.Trim(Cells(1,1)) ,其中该单元格包含任何彩色元素,该元素默认为彩色。
Here is my code:这是我的代码:
Cells(4, 2) = Application.WorksheetFunction.Trim(UCase(Cells(4, 2)))
Did you see this issue before?你以前见过这个问题吗?
How can I remove blank in the text without this issue?如何在没有此问题的情况下删除文本中的空白?
Thanks for your help !谢谢你的帮助 !
For cells with mixed formatting, replacing the cell value will lose the mixed format: instead you need to work with the cell's Characters
collection:对于具有混合格式的单元格,替换单元格值将丢失混合格式:相反,您需要使用单元格的
Characters
集合:
Sub tester()
Dim c As Range
For Each c In Range("B3:B10").Cells
TrimAndUppercase c
Next c
End Sub
Sub TrimAndUppercase(c As Range)
Dim i, prevSpace As Boolean
If Len(c.Value) > 0 Then
'trim the ends of the text
Do While Left(c.Value, 1) = " "
c.Characters(1, 1).Text = ""
Loop
Do While Right(c.Value, 1) = " "
c.Characters(Len(c.Value), 1).Text = ""
Loop
'reduce runs of multiple spaces to a single space
For i = c.Characters.Count To 1 Step -1
With c.Characters(i, 1)
If .Text = " " Then
'was the previous character a space?
If prevSpace Then
.Text = "" 'remove this space
Else
prevSpace = True
End If
Else
.Text = UCase(.Text)
prevSpace = False
End If
End With
Next i
End If
End Sub
Note there are some limits to the length of the text using this method, and it can be a little slow with large ranges.请注意,使用此方法对文本的长度有一些限制,如果范围较大,它可能会有点慢。
finally, I used this instruction.最后,我使用了这个指令。
Cells(4, 2) = Replace(UCase(Cells(4, 2)), " ", "")
In fact, my cell contain parameters and we perfers to avoid to have blank between them for visibility.事实上,我的单元格包含参数,我们希望避免在它们之间留有空白以提高可见性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.