【问题标题】:Trimming blank spaces in Excel without losing formatting在 Excel 中修剪空格而不丢失格式
【发布时间】:2021-06-04 09:25:51
【问题描述】:

我找到了一个可以修剪尾随空格的 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
        '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

问题是在包含部分格式的单元格上运行时,格式会丢失。例如,“此此处已格式化。”变为“此处已格式化。”

我修改了代码来遍历字符串,只保留左边的部分,但是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() 保持格式化的解决方法?

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果您需要保留仅应用于单元格内容的任何格式,则必须使用单元格的Characters 属性来修改内容。

    例如删除最后一个字符:

    c.Characters(Len(c.Value),1).Delete
    

    https://docs.microsoft.com/en-us/office/vba/api/excel.range.characters

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      相关资源
      最近更新 更多