在不丢失格式的情况下修剪Excel中的空格
我找到了一个Excel宏,它将修剪尾随空格:在不丢失格式的情况下修剪Excel中的空格,excel,vba,Excel,Vba,我找到了一个Excel宏,它将修剪尾随空格: Sub trimspace() Dim c As Range Dim rngConstants As Range On Error Resume Next Set rngConstants = ActiveSheet.UsedRange.SpecialCells(2, 2) On Error GoTo 0 If Not rngConstants Is Nothing Then 'opti
Sub trimspace()
Dim c As Range
Dim rngConstants As Range
On Error Resume Next
Set rngConstants = ActiveSheet.UsedRange.SpecialCells(2, 2)
On Error GoTo 0
If Not rngConstants Is Nothing Then
'optimize performance
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'trim cells incl char 160
For Each c In rngConstants
c.Value = Trim$(Application.Clean(Replace(c.Value, Chr(160), " ")))
Next c
'reset settings
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End If
End Sub
问题是,在包含部分格式的单元格上运行时,格式会丢失。例如,“Thishere已格式化。”变为“This here is formatted”
我修改了代码,使其遍历字符串并仅保留左侧部分,但left()函数还删除了格式
Sub trimspace2()
Dim c As Range
Dim rngConstants As Range
On Error Resume Next
Set rngConstants = ActiveSheet.UsedRange.SpecialCells(2, 2)
On Error GoTo 0
If Not rngConstants Is Nothing Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For Each c In rngConstants
While Asc(Right(c.Value, 1)) = 32
c.Value = Left(c.Value, Len(c.Value) - 1)
Wend
Next c
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End If
End Sub
是否有手动方法在迭代过程中删除最后一个字符,以避免处理单元格值的格式化部分?或者使用trim()保留格式的变通方法?如果需要保留仅应用于单元格内容一部分的任何格式,则必须使用单元格的
字符
属性修改内容
例如,要删除最后一个字符:
c.Characters(Len(c.Value),1).Delete
这很好用——谢谢!