【问题标题】:How to remove leading and trailing spaces from all cells of a excel sheet at once如何一次从Excel工作表的所有单元格中删除前导和尾随空格
【发布时间】:2015-08-24 11:39:24
【问题描述】:

我有一个 Excel 表格,其中包含大量带有前导和尾随空格的数据。

使用TRIM() 手动删除这些空格需要很多时间。

我怎样才能有效地做到这一点。

【问题讨论】:

  • 内部空间怎么样??

标签: excel excel-formula vba


【解决方案1】:

要有效地做到这一点,请使用变体数组,例如:

Sub VBATrim()
    Dim rng1 As Range
    Dim rngArea As Range
    Dim lngRow As Long
    Dim lngCol As Long
    Dim lngCalc As Long
    Dim X()


    On Error Resume Next
    Set rng1 = Application.InputBox("Select range for the replacement of non-number", "User select", Selection.Address, , , , , 8)
    If rng1 Is Nothing Then Exit Sub
    On Error GoTo 0


   'Speed up the code by turning off screenupdating and setting calculation to manual
   'Disable any code events that may occur when writing to cells
    With Application
        lngCalc = .Calculation
        .ScreenUpdating = False
        .Calculation = xlCalculationManual
        .EnableEvents = False
    End With

    'Test each area in the user selected range

    'Non contiguous range areas are common when using SpecialCells to define specific cell types to work on
    For Each rngArea In rng1.Areas
        'The most common outcome is used for the True outcome to optimise code speed
        If rngArea.Cells.Count > 1 Then
           'If there is more than once cell then set the variant array to the dimensions of the range area
           'Using Value2 provides a useful speed improvement over Value. On my testing it was 2% on blank cells, up to 10% on non-blanks
            X = rngArea.Value2
            For lngRow = 1 To rngArea.Rows.Count
                For lngCol = 1 To rngArea.Columns.Count
                    'replace the leading zeroes
                    X(lngRow, lngCol) = Trim(X(lngRow, lngCol))
                Next lngCol
            Next lngRow
            'Dump the updated array sans leading zeroes back over the initial range
            rngArea.Value2 = X
        Else
            'caters for a single cell range area. No variant array required
            rngArea.Value = Trim(rngArea.Value)
        End If
    Next rngArea

    'cleanup the Application settings
    With Application
        .ScreenUpdating = True
        .Calculation = lngCalc
        .EnableEvents = True
    End With

End Sub

【讨论】:

    【解决方案2】:

    试试这个小宏:

    Sub KleanUp()
      Dim r As Range
      For Each r In ActiveSheet.UsedRange
        v = r.Value
        If v <> "" Then
          If Not r.HasFormula Then
            r.Value = Trim(v)
          End If
        End If
      Next r
    End Sub
    

    此宏不会影响内部空格或包含公式的单元格。

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 2018-10-04
      • 2012-02-28
      • 2020-08-20
      • 2018-10-06
      • 2013-05-10
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      相关资源
      最近更新 更多