在Excel中使用VBA修剪单元格

Gre*_*lds 8 excel vba excel-vba

我对Excel中的某些数据有一个简单的问题.我有很多数据与从Web表粘贴的前导空格,我想摆脱最初的空间.我抄了下面的代码(我对VBA来说是全新的),但似乎没有用.当我在调试器中单步执行它时,它看起来像一个无限循环.任何帮助,将不胜感激!

Sub DoTrim()
  For Each cell In Selection.Cells
    If cell.HasFormula = False Then
      cell = Trim(cell)
    End If
  Next
End Sub
Run Code Online (Sandbox Code Playgroud)

编辑:看起来TRIM函数遇到了"空格"字符的问题.这段代码:

Sub DoTrim()
Dim cell As Range, areaToTrim As Range
Set areaToTrim = Selection.Cells
For Each cell In areaToTrim
    cell.Value = "MUPPET"
Next cell
End Sub
Run Code Online (Sandbox Code Playgroud)

更改了单元格的值,所以我猜这是一个非空格的空格!关于如何摆脱那些的任何想法?

Jim*_*ena 10

这对我很有用.它使用一个数组,因此您不会循环遍历每个单元格.在大型工作表部分上运行得更快.

Sub Trim_Cells_Array_Method()

Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long

  lRows = Selection.Rows.count
  lCols = Selection.Columns.count

  ReDim arrData(1 To lRows, 1 To lCols)
  ReDim arrReturnData(1 To lRows, 1 To lCols)

  Set rng = Selection
  arrData = rng.value

  For j = 1 To lCols
    For i = 1 To lRows
      arrReturnData(i, j) = Trim(arrData(i, j))
    Next i
  Next j

  rng.value = arrReturnData

  Set rng = Nothing
End Sub
Run Code Online (Sandbox Code Playgroud)


Cha*_*ams 8

如果字符串前面有非打印字符,请尝试此操作


Option Explicit
Sub DoTrim()
    Dim cell As Range
    Dim str As String
    Dim nAscii As Integer
    For Each cell In Selection.Cells
        If cell.HasFormula = False Then
            str = Trim(CStr(cell))
            If Len(str) > 0 Then
                nAscii = Asc(Left(str, 1))
                If nAscii < 33 Or nAscii = 160 Then
                    If Len(str) > 1 Then
                        str = Right(str, Len(str) - 1)
                    Else
                        strl = ""
                    End If
                End If
            End If
            cell=str
        End If
    Next
End Sub
Run Code Online (Sandbox Code Playgroud)